diff --git a/gabinete-digital-fo.code-workspace b/gabinete-digital-fo.code-workspace index 4d32d5e79..1911f5b96 100644 --- a/gabinete-digital-fo.code-workspace +++ b/gabinete-digital-fo.code-workspace @@ -20,10 +20,6 @@ "name": "grayLog", "path": "../grayLog" }, - { - "name": "equilibriumito-gabinete-digital-fo-23cf0fc4cbaa", - "path": "../../../Downloads/equilibriumito-gabinete-digital-fo-23cf0fc4cbaa/equilibriumito-gabinete-digital-fo-23cf0fc4cbaa" - }, { "path": "../../../Downloads/nestjs-microservice-boilerplate-api-master" }, diff --git a/package-lock.json b/package-lock.json index be9f672a9..ea85ff25e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -98,6 +98,7 @@ "@ngx-translate/core": "^13.0.0", "@ngxs/store": "^3.8.2", "@opentelemetry/exporter-metrics-otlp-http": "^0.52.1", + "@opentelemetry/exporter-trace-otlp-http": "^0.52.1", "@opentelemetry/exporter-zipkin": "^1.25.1", "@opentelemetry/resources": "^1.25.1", "@opentelemetry/sdk-metrics": "^1.25.1", @@ -193,6 +194,7 @@ "ts-jest": "^27.0.3", "ts-jest-puppeteer": "^0.0.5", "tslib": "^2.0.0", + "typedoc": "^0.26.5", "uuidv4": "^6.2.11", "videogular2": "^7.0.2", "webpack": "^5.88.2", @@ -7794,6 +7796,24 @@ "@opentelemetry/api": "^1.3.0" } }, + "node_modules/@opentelemetry/exporter-trace-otlp-http": { + "version": "0.52.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-trace-otlp-http/-/exporter-trace-otlp-http-0.52.1.tgz", + "integrity": "sha512-05HcNizx0BxcFKKnS5rwOV+2GevLTVIRA0tRgWYyw4yCgR53Ic/xk83toYKts7kbzcI+dswInUg/4s8oyA+tqg==", + "dependencies": { + "@opentelemetry/core": "1.25.1", + "@opentelemetry/otlp-exporter-base": "0.52.1", + "@opentelemetry/otlp-transformer": "0.52.1", + "@opentelemetry/resources": "1.25.1", + "@opentelemetry/sdk-trace-base": "1.25.1" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.0.0" + } + }, "node_modules/@opentelemetry/exporter-zipkin": { "version": "1.25.1", "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-zipkin/-/exporter-zipkin-1.25.1.tgz", @@ -8324,6 +8344,14 @@ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.2.tgz", "integrity": "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==" }, + "node_modules/@shikijs/core": { + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-1.12.1.tgz", + "integrity": "sha512-biCz/mnkMktImI6hMfMX3H9kOeqsInxWEyCHbSlL8C/2TR1FqfmGxTLRNwYCKsyCyxWLbB8rEqXRVZuyxuLFmA==", + "dependencies": { + "@types/hast": "^3.0.4" + } + }, "node_modules/@sideway/address": { "version": "4.1.4", "resolved": "https://registry.npmjs.org/@sideway/address/-/address-4.1.4.tgz", @@ -8597,6 +8625,14 @@ "resolved": "https://registry.npmjs.org/@types/hammerjs/-/hammerjs-2.0.40.tgz", "integrity": "sha512-VbjwR1fhsn2h2KXAY4oy1fm7dCxaKy0D+deTb8Ilc3Eo3rc5+5eA4rfYmZaHgNJKxVyI0f6WIXzO2zLkVmQPHA==" }, + "node_modules/@types/hast": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz", + "integrity": "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==", + "dependencies": { + "@types/unist": "*" + } + }, "node_modules/@types/istanbul-lib-coverage": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.3.tgz", @@ -8757,6 +8793,11 @@ "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.1.tgz", "integrity": "sha512-Hl219/BT5fLAaz6NDkSuhzasy49dwQS/DSdu4MdggFB8zcXv7vflBI3xp7FEmkmdDkBUI2bPUNeMttp2knYdxw==" }, + "node_modules/@types/unist": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.2.tgz", + "integrity": "sha512-dqId9J8K/vGi5Zr7oo212BGii5m3q5Hxlkwy3WpYuKPklmBEvsbMYYyLxAQpSffdLl/gdW0XUpKWFvYmyoWCoQ==" + }, "node_modules/@types/uuid": { "version": "8.3.1", "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-8.3.1.tgz", @@ -26135,6 +26176,14 @@ "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.1.6.tgz", "integrity": "sha512-8ZmlJFVK9iCmtLz19HpSsR8HaAMWBT284VMNednLwlIMDP2hJDCIhUp0IZ2xUcZ+Ob6BM0VvCSJwzASDM45NLQ==" }, + "node_modules/linkify-it": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-5.0.0.tgz", + "integrity": "sha512-5aHCbzQRADcdP+ATqnDuhhJ/MRIqDkZX5pyjFHRRysS8vZ5AbqGEoFIb6pYHPZ+L/OC2Lc+xT8uHVVR5CAK/wQ==", + "dependencies": { + "uc.micro": "^2.0.0" + } + }, "node_modules/listr2": { "version": "3.14.0", "resolved": "https://registry.npmjs.org/listr2/-/listr2-3.14.0.tgz", @@ -26546,6 +26595,11 @@ "node": ">=10" } }, + "node_modules/lunr": { + "version": "2.3.9", + "resolved": "https://registry.npmjs.org/lunr/-/lunr-2.3.9.tgz", + "integrity": "sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow==" + }, "node_modules/luxon": { "version": "3.4.4", "resolved": "https://registry.npmjs.org/luxon/-/luxon-3.4.4.tgz", @@ -26665,6 +26719,38 @@ "node": ">=0.10.0" } }, + "node_modules/markdown-it": { + "version": "14.1.0", + "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.1.0.tgz", + "integrity": "sha512-a54IwgWPaeBCAAsv13YgmALOF1elABB08FxO9i+r4VFk5Vl4pKokRPeX8u5TCgSsPi6ec1otfLjdOpVcgbpshg==", + "dependencies": { + "argparse": "^2.0.1", + "entities": "^4.4.0", + "linkify-it": "^5.0.0", + "mdurl": "^2.0.0", + "punycode.js": "^2.3.1", + "uc.micro": "^2.1.0" + }, + "bin": { + "markdown-it": "bin/markdown-it.mjs" + } + }, + "node_modules/markdown-it/node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==" + }, + "node_modules/markdown-it/node_modules/entities": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/md5-file": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/md5-file/-/md5-file-5.0.0.tgz", @@ -26693,6 +26779,11 @@ "integrity": "sha512-dn6wd0uw5GsdswPFfsgMp5NSB0/aDe6fK94YJV/AJDYXL6HVLWBsxeq7js7Ad+mU2K9LAlwpk6kN2D5mwCPVow==", "dev": true }, + "node_modules/mdurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-2.0.0.tgz", + "integrity": "sha512-Lf+9+2r+Tdp5wXDXC4PcIBjTDtq4UKjCPMQhKIuzpJNW0b96kVqSwW0bT7FhRSfmAiFYgP+SCRvdrDozfh0U5w==" + }, "node_modules/media-typer": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", @@ -32306,6 +32397,14 @@ "node": ">=6" } }, + "node_modules/punycode.js": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode.js/-/punycode.js-2.3.1.tgz", + "integrity": "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==", + "engines": { + "node": ">=6" + } + }, "node_modules/pupa": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/pupa/-/pupa-2.1.1.tgz", @@ -34551,6 +34650,15 @@ "optional": true, "peer": true }, + "node_modules/shiki": { + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/shiki/-/shiki-1.12.1.tgz", + "integrity": "sha512-nwmjbHKnOYYAe1aaQyEBHvQymJgfm86ZSS7fT8OaPRr4sbAcBNz7PbfAikMEFSDQ6se2j2zobkXvVKcBOm0ysg==", + "dependencies": { + "@shikijs/core": "1.12.1", + "@types/hast": "^3.0.4" + } + }, "node_modules/side-channel": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", @@ -41794,6 +41902,60 @@ "is-typedarray": "^1.0.0" } }, + "node_modules/typedoc": { + "version": "0.26.5", + "resolved": "https://registry.npmjs.org/typedoc/-/typedoc-0.26.5.tgz", + "integrity": "sha512-Vn9YKdjKtDZqSk+by7beZ+xzkkr8T8CYoiasqyt4TTRFy5+UHzL/mF/o4wGBjRF+rlWQHDb0t6xCpA3JNL5phg==", + "dependencies": { + "lunr": "^2.3.9", + "markdown-it": "^14.1.0", + "minimatch": "^9.0.5", + "shiki": "^1.9.1", + "yaml": "^2.4.5" + }, + "bin": { + "typedoc": "bin/typedoc" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "typescript": "4.6.x || 4.7.x || 4.8.x || 4.9.x || 5.0.x || 5.1.x || 5.2.x || 5.3.x || 5.4.x || 5.5.x" + } + }, + "node_modules/typedoc/node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/typedoc/node_modules/minimatch": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/typedoc/node_modules/yaml": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.5.0.tgz", + "integrity": "sha512-2wWLbGbYDiSqqIKoPjar3MPgB94ErzCtrNE1FdqGuaO0pi2JGjmE8aW8TDZwzU7vuxcGRdL/4gPQwQ7hD5AMSw==", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14" + } + }, "node_modules/typescript": { "version": "4.3.5", "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.3.5.tgz", @@ -41825,6 +41987,11 @@ "node": "*" } }, + "node_modules/uc.micro": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-2.1.0.tgz", + "integrity": "sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==" + }, "node_modules/uglify-js": { "version": "1.3.5", "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-1.3.5.tgz", @@ -49820,6 +49987,18 @@ "@opentelemetry/sdk-metrics": "1.25.1" } }, + "@opentelemetry/exporter-trace-otlp-http": { + "version": "0.52.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-trace-otlp-http/-/exporter-trace-otlp-http-0.52.1.tgz", + "integrity": "sha512-05HcNizx0BxcFKKnS5rwOV+2GevLTVIRA0tRgWYyw4yCgR53Ic/xk83toYKts7kbzcI+dswInUg/4s8oyA+tqg==", + "requires": { + "@opentelemetry/core": "1.25.1", + "@opentelemetry/otlp-exporter-base": "0.52.1", + "@opentelemetry/otlp-transformer": "0.52.1", + "@opentelemetry/resources": "1.25.1", + "@opentelemetry/sdk-trace-base": "1.25.1" + } + }, "@opentelemetry/exporter-zipkin": { "version": "1.25.1", "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-zipkin/-/exporter-zipkin-1.25.1.tgz", @@ -50235,6 +50414,14 @@ } } }, + "@shikijs/core": { + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-1.12.1.tgz", + "integrity": "sha512-biCz/mnkMktImI6hMfMX3H9kOeqsInxWEyCHbSlL8C/2TR1FqfmGxTLRNwYCKsyCyxWLbB8rEqXRVZuyxuLFmA==", + "requires": { + "@types/hast": "^3.0.4" + } + }, "@sideway/address": { "version": "4.1.4", "resolved": "https://registry.npmjs.org/@sideway/address/-/address-4.1.4.tgz", @@ -50484,6 +50671,14 @@ "resolved": "https://registry.npmjs.org/@types/hammerjs/-/hammerjs-2.0.40.tgz", "integrity": "sha512-VbjwR1fhsn2h2KXAY4oy1fm7dCxaKy0D+deTb8Ilc3Eo3rc5+5eA4rfYmZaHgNJKxVyI0f6WIXzO2zLkVmQPHA==" }, + "@types/hast": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz", + "integrity": "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==", + "requires": { + "@types/unist": "*" + } + }, "@types/istanbul-lib-coverage": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.3.tgz", @@ -50645,6 +50840,11 @@ "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.1.tgz", "integrity": "sha512-Hl219/BT5fLAaz6NDkSuhzasy49dwQS/DSdu4MdggFB8zcXv7vflBI3xp7FEmkmdDkBUI2bPUNeMttp2knYdxw==" }, + "@types/unist": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.2.tgz", + "integrity": "sha512-dqId9J8K/vGi5Zr7oo212BGii5m3q5Hxlkwy3WpYuKPklmBEvsbMYYyLxAQpSffdLl/gdW0XUpKWFvYmyoWCoQ==" + }, "@types/uuid": { "version": "8.3.1", "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-8.3.1.tgz", @@ -64086,6 +64286,14 @@ "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.1.6.tgz", "integrity": "sha512-8ZmlJFVK9iCmtLz19HpSsR8HaAMWBT284VMNednLwlIMDP2hJDCIhUp0IZ2xUcZ+Ob6BM0VvCSJwzASDM45NLQ==" }, + "linkify-it": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-5.0.0.tgz", + "integrity": "sha512-5aHCbzQRADcdP+ATqnDuhhJ/MRIqDkZX5pyjFHRRysS8vZ5AbqGEoFIb6pYHPZ+L/OC2Lc+xT8uHVVR5CAK/wQ==", + "requires": { + "uc.micro": "^2.0.0" + } + }, "listr2": { "version": "3.14.0", "resolved": "https://registry.npmjs.org/listr2/-/listr2-3.14.0.tgz", @@ -64409,6 +64617,11 @@ "yallist": "^4.0.0" } }, + "lunr": { + "version": "2.3.9", + "resolved": "https://registry.npmjs.org/lunr/-/lunr-2.3.9.tgz", + "integrity": "sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow==" + }, "luxon": { "version": "3.4.4", "resolved": "https://registry.npmjs.org/luxon/-/luxon-3.4.4.tgz", @@ -64500,6 +64713,31 @@ "object-visit": "^1.0.0" } }, + "markdown-it": { + "version": "14.1.0", + "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.1.0.tgz", + "integrity": "sha512-a54IwgWPaeBCAAsv13YgmALOF1elABB08FxO9i+r4VFk5Vl4pKokRPeX8u5TCgSsPi6ec1otfLjdOpVcgbpshg==", + "requires": { + "argparse": "^2.0.1", + "entities": "^4.4.0", + "linkify-it": "^5.0.0", + "mdurl": "^2.0.0", + "punycode.js": "^2.3.1", + "uc.micro": "^2.1.0" + }, + "dependencies": { + "argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==" + }, + "entities": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==" + } + } + }, "md5-file": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/md5-file/-/md5-file-5.0.0.tgz", @@ -64522,6 +64760,11 @@ "integrity": "sha512-dn6wd0uw5GsdswPFfsgMp5NSB0/aDe6fK94YJV/AJDYXL6HVLWBsxeq7js7Ad+mU2K9LAlwpk6kN2D5mwCPVow==", "dev": true }, + "mdurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-2.0.0.tgz", + "integrity": "sha512-Lf+9+2r+Tdp5wXDXC4PcIBjTDtq4UKjCPMQhKIuzpJNW0b96kVqSwW0bT7FhRSfmAiFYgP+SCRvdrDozfh0U5w==" + }, "media-typer": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", @@ -68812,6 +69055,11 @@ "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==" }, + "punycode.js": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode.js/-/punycode.js-2.3.1.tgz", + "integrity": "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==" + }, "pupa": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/pupa/-/pupa-2.1.1.tgz", @@ -70498,6 +70746,15 @@ "optional": true, "peer": true }, + "shiki": { + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/shiki/-/shiki-1.12.1.tgz", + "integrity": "sha512-nwmjbHKnOYYAe1aaQyEBHvQymJgfm86ZSS7fT8OaPRr4sbAcBNz7PbfAikMEFSDQ6se2j2zobkXvVKcBOm0ysg==", + "requires": { + "@shikijs/core": "1.12.1", + "@types/hast": "^3.0.4" + } + }, "side-channel": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", @@ -76164,6 +76421,41 @@ "is-typedarray": "^1.0.0" } }, + "typedoc": { + "version": "0.26.5", + "resolved": "https://registry.npmjs.org/typedoc/-/typedoc-0.26.5.tgz", + "integrity": "sha512-Vn9YKdjKtDZqSk+by7beZ+xzkkr8T8CYoiasqyt4TTRFy5+UHzL/mF/o4wGBjRF+rlWQHDb0t6xCpA3JNL5phg==", + "requires": { + "lunr": "^2.3.9", + "markdown-it": "^14.1.0", + "minimatch": "^9.0.5", + "shiki": "^1.9.1", + "yaml": "^2.4.5" + }, + "dependencies": { + "brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "requires": { + "balanced-match": "^1.0.0" + } + }, + "minimatch": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "requires": { + "brace-expansion": "^2.0.1" + } + }, + "yaml": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.5.0.tgz", + "integrity": "sha512-2wWLbGbYDiSqqIKoPjar3MPgB94ErzCtrNE1FdqGuaO0pi2JGjmE8aW8TDZwzU7vuxcGRdL/4gPQwQ7hD5AMSw==" + } + } + }, "typescript": { "version": "4.3.5", "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.3.5.tgz", @@ -76175,6 +76467,11 @@ "integrity": "sha512-qLK/Xe9E2uzmYI3qLeOmI0tEOt+TBBQyUIAh4aAgU05FVYzeZrKUdkAZfBNVGRaHVgV0TDkdEngJSw/SyQchkQ==", "dev": true }, + "uc.micro": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-2.1.0.tgz", + "integrity": "sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==" + }, "uglify-js": { "version": "1.3.5", "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-1.3.5.tgz", diff --git a/package.json b/package.json index a832dfdce..d28f072c1 100644 --- a/package.json +++ b/package.json @@ -114,6 +114,7 @@ "@ngx-translate/core": "^13.0.0", "@ngxs/store": "^3.8.2", "@opentelemetry/exporter-metrics-otlp-http": "^0.52.1", + "@opentelemetry/exporter-trace-otlp-http": "^0.52.1", "@opentelemetry/exporter-zipkin": "^1.25.1", "@opentelemetry/resources": "^1.25.1", "@opentelemetry/sdk-metrics": "^1.25.1", @@ -209,6 +210,7 @@ "ts-jest": "^27.0.3", "ts-jest-puppeteer": "^0.0.5", "tslib": "^2.0.0", + "typedoc": "^0.26.5", "uuidv4": "^6.2.11", "videogular2": "^7.0.2", "webpack": "^5.88.2", diff --git a/src/app/animations/animations.ts b/src/app/animations/animations.ts deleted file mode 100644 index ce536f126..000000000 --- a/src/app/animations/animations.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { Animation, AnimationController } from '@ionic/angular'; - -/* export const enterAnimation = (base) */ \ No newline at end of file diff --git a/src/app/config/auth-constants.ts b/src/app/config/auth-constants.ts deleted file mode 100644 index 677d091cc..000000000 --- a/src/app/config/auth-constants.ts +++ /dev/null @@ -1,8 +0,0 @@ -/* This file stores all the keys */ -export class AuthConnstants{ - /* My reference key */ - public static readonly AUTH = 'userDataKey'; - public static readonly PROFILE = 'profile'; - public static readonly USER = 'userId'; - public static readonly USERCHAT = 'userChat'; -} \ No newline at end of file diff --git a/src/app/controller/chat.ts b/src/app/controller/chat.ts deleted file mode 100644 index 16308223f..000000000 --- a/src/app/controller/chat.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { ChatSystemService } from "../services/chat/chat-system.service"; - -export class ChatController { - - static ChatSystemService: ChatSystemService - - static async createGroup(name) { - let data: any = await this.ChatSystemService.createGroup(name) - - if(data?.error?.error == 'error-invalid-room-name') { - name = name.slice(0, 12) - data = await this.ChatSystemService.createGroup(name) - return { - data, - roomName: name - } - } - - return { - data, - roomName: name - } - } - - static async createOrFindGroup(name) { - let data: any = await this.createGroup(name) - } - -} \ No newline at end of file diff --git a/src/app/home/home.page.ts b/src/app/home/home.page.ts index d64991053..005ecffbb 100644 --- a/src/app/home/home.page.ts +++ b/src/app/home/home.page.ts @@ -11,7 +11,7 @@ import { PermissionService } from '../services/permission.service'; import { BackgroundService } from 'src/app/services/background.service'; import { Storage } from '@ionic/storage'; import { EventsService } from 'src/app/services/events.service'; -import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service'; +// import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service'; import { ProcessesService } from 'src/app/services/processes.service'; import { RoleIdService } from 'src/app/services/role-id.service'; import { ActiveTabService } from 'src/app/services/active-tab.service'; @@ -98,7 +98,7 @@ export class HomePage implements OnInit { private eventservice: EventsService, private processservice: ProcessesService, public RouteService: RouteService, - private RochetChatConnectorService: RochetChatConnectorService, + // private RochetChatConnectorService: RochetChatConnectorService, private NetworkServiceService: NetworkServiceService, public eventService: EventsService, public ActiveTabService: ActiveTabService, @@ -214,12 +214,12 @@ export class HomePage implements OnInit { } }); - this.RochetChatConnectorService.registerCallback({ - type: 'reConnect', - funx: async () => { - this.backgroundservice.online() - } - }) + // this.RochetChatConnectorService.registerCallback({ + // type: 'reConnect', + // funx: async () => { + // this.backgroundservice.online() + // } + // }) this.NetworkServiceService.onNetworkChange().subscribe((status) => { if (status == ConnectionStatus.Online) { diff --git a/src/app/infra/file-picker/adapter.ts b/src/app/infra/file-picker/adapter.ts new file mode 100644 index 000000000..e69de29bb diff --git a/src/app/infra/file-picker/web/file-picker-web.service.ts b/src/app/infra/file-picker/web/file-picker-web.service.ts new file mode 100644 index 000000000..9a203669a --- /dev/null +++ b/src/app/infra/file-picker/web/file-picker-web.service.ts @@ -0,0 +1,26 @@ +import { Injectable } from '@angular/core'; +import { FileType } from 'src/app/models/fileType'; + +@Injectable({ + providedIn: 'root' +}) +export class FilePickerWebService { + + constructor() { } + + getFileFromDevice(types: typeof FileType[]): Promise { + let input = document.createElement('input'); + input.type = 'file'; + input.accept = types.join(', ') + + input.click(); + + return new Promise((resolve, reject)=>{ + input.onchange = async () => { + const file = Array.from(input.files) + resolve(file[0] as File); + }; + }) + } + +} diff --git a/src/app/interceptors/chatToken.interceptor.ts b/src/app/interceptors/chatToken.interceptor.ts index 66f27b7e4..6373fd813 100644 --- a/src/app/interceptors/chatToken.interceptor.ts +++ b/src/app/interceptors/chatToken.interceptor.ts @@ -16,7 +16,7 @@ import { SessionStore } from '../store/session.service'; import { environment } from "src/environments/environment"; import { PermissionService } from '../services/permission.service'; import { NetworkServiceService, ConnectionStatus } from 'src/app/services/network-service.service'; -import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service'; +// import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service'; @Injectable() export class ChatTokenInterceptor implements HttpInterceptor { @@ -29,8 +29,7 @@ export class ChatTokenInterceptor implements HttpInterceptor { private excludedDomains = ['Login',environment.apiURL];// Add other domains as needed - constructor(private http: HttpClient, private router: Router, private p: PermissionService, private NetworkServiceService: NetworkServiceService, - private RochetChatConnectorService: RochetChatConnectorService) { } + constructor(private http: HttpClient, private router: Router, private p: PermissionService, private NetworkServiceService: NetworkServiceService) { } intercept( request: HttpRequest, diff --git a/src/app/models/beast-orm-function.ts b/src/app/models/beast-orm-function.ts deleted file mode 100644 index 287f30792..000000000 --- a/src/app/models/beast-orm-function.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { AES, SHA1, enc } from "crypto-js"; -import { environment } from 'src/environments/environment' - - -function prefix() { - return environment.version.lastCommitNumber + environment.id+"-"; -} - -export function GET({key, instance}) { - if(environment.storageProduction) { - - try { - const newKey = prefix() + SHA1(key).toString() - const cipherText = localStorage.getItem(newKey) - const bytes = AES.decrypt(cipherText, newKey) - var decryptedData = bytes.toString(enc.Utf8); - const restoredData = JSON.parse(decryptedData) - - Object.assign(instance, restoredData); - - return restoredData - - } catch(error) { - console.log(error) - return {} - } - - } else { - const newKey = prefix() + key - const restoredData = JSON.parse(localStorage.getItem(newKey)) - Object.assign(instance, restoredData); - - return restoredData - } - -} - -export function SAVE({key, instance, dataToSave}) { - if(environment.storageProduction) { - const newKey = prefix() + SHA1(key).toString() - const stringifyData = JSON.stringify(dataToSave) - - const cipherText = AES.encrypt(stringifyData, newKey).toString(); - - localStorage.setItem(newKey, cipherText) - - } else { - const stringifyData = JSON.stringify(dataToSave) - const newKey = prefix() + key - - localStorage.setItem(newKey, stringifyData) - } -} - -export function DELETE({key, instance}) { - if(environment.storageProduction) { - const newKey = prefix() + SHA1(key).toString() - localStorage.removeItem(newKey) - - } else { - const newKey = prefix() + key - localStorage.removeItem(newKey) - } -} \ No newline at end of file diff --git a/src/app/models/beast-orm.ts b/src/app/models/beast-orm.ts deleted file mode 100644 index e1f119cce..000000000 --- a/src/app/models/beast-orm.ts +++ /dev/null @@ -1,116 +0,0 @@ -//import { models } from 'beast-orm' -import { environment } from 'src/environments/environment' -import { models } from 'src/plugin/src' -const { ArrayField, JsonField} = models.indexedDB.fields - -export class MessageModel extends models.Model { - channels = ArrayField() - mentions = ArrayField() - msg = models.CharField() - sendAttempt = models.IntegerField() - rid = models.CharField() - t = models.CharField({default:'', blank: true}) - ts = JsonField({blank:true}) - u = JsonField() - _id = models.CharField({blank:true}) - origin = models.CharField({blank:true}) - _updatedAt = models.IntegerField() - messageSend = models.BooleanField() - offline = models.BooleanField() - hasFile = models.BooleanField({blank:true}) - viewed = ArrayField({blank:true}) - received = ArrayField({blank:true}) - localReference = models.CharField({blank:true, unique: true}) - attachments = ArrayField({blank:true}) - file = JsonField({blank:true}) - UploadAttachmentsTemp = models.IntegerField() - - async getAttachments() { - console.log('this[id]', this['id']) - const _attachments = await attachments.filter({messageId: this['id']}).execute() - return _attachments[0] - } -} - -export class attachments extends models.Model { - messageId = models.IntegerField() - attachments = ArrayField({blank:true}) - file = JsonField({blank:true}) -} - -export class DeleteMessageModel extends models.Model { - messageId = models.CharField() - rid = models.CharField() - u = JsonField() - needToReceiveBy = ArrayField() -} - -models.register({ - databaseName: 'chat-storage'+environment.version.lastCommitNumber + environment.id + Number(environment.storageProduction), - type: 'indexedDB', - version: 11, - models: [MessageModel, DeleteMessageModel, attachments] -}) - - - -// // acçoes -export class ActionModel extends models.Model{ - static $tableName = 'ActionModel11' - - ProcessId = models.IntegerField({unique: true}) - Description = models.CharField() - Detail = models.CharField() - DateBegin = models.CharField() - DateEnd = models.CharField() - ActionType = models.CharField() - -} - - -export class PublicationFolderModel extends models.Model{ - - DateBegin = models.CharField() - Description = models.CharField() - Detail = models.CharField() -} - -export class PublicationDetailsModel extends models.Model{ - - DateIndex = models.CharField() - DocumentId = models.IntegerField({unique: true}) - ProcessId = models.CharField() - Title = models.CharField() - Message = models.CharField() - DatePublication = models.CharField() - OriginalFileName = models.CharField() - FileBase64 = models.CharField() - FileExtension = models.CharField() - OrganicEntityId = models.IntegerField() -} - - -export class WebtrixUserModel extends models.Model { - - FullName = models.CharField() - Role = models.CharField() -} - -models.register({ - databaseName: 'webtrix'+environment.version.lastCommitNumber + environment.id + Number(environment.storageProduction), - type: 'indexedDB', - version: 1, - models: [WebtrixUserModel] -}) - - -models.register({ - databaseName: 'actions'+environment.version.lastCommitNumber + environment.id + Number(environment.storageProduction), - type: 'indexedDB', - version: 14, - models: [PublicationDetailsModel, ActionModel, PublicationFolderModel] -}) - - - -window["MessageModel"] = MessageModel diff --git a/src/app/module/chat/data/dto/message/messageInputDtO.ts b/src/app/module/chat/data/dto/message/messageInputDtO.ts index 0c1da5a5d..56482772e 100644 --- a/src/app/module/chat/data/dto/message/messageInputDtO.ts +++ b/src/app/module/chat/data/dto/message/messageInputDtO.ts @@ -1,4 +1,5 @@ import { z } from "zod"; +import { MessageAttachmentFileType, MessageAttachmentSource } from "./messageOutputDTO"; export const MessageInputDTOSchema = z.object({ roomId: z.string().uuid(), @@ -8,7 +9,15 @@ export const MessageInputDTOSchema = z.object({ canEdit: z.boolean(), oneShot: z.boolean(), requireUnlock: z.boolean(), - requestId: z.string() + requestId: z.string(), + attachments: z.array(z.object({ + fileType: z.nativeEnum(MessageAttachmentFileType), + source: z.nativeEnum(MessageAttachmentSource), + file: z.string(), + fileName: z.string(), + applicationId: z.string(), + docId: z.string() + })).optional() }); diff --git a/src/app/module/chat/data/dto/message/messageOutputDTO.ts b/src/app/module/chat/data/dto/message/messageOutputDTO.ts index 6b96e927f..6d68be8bb 100644 --- a/src/app/module/chat/data/dto/message/messageOutputDTO.ts +++ b/src/app/module/chat/data/dto/message/messageOutputDTO.ts @@ -41,8 +41,8 @@ export const MessageOutPutDataDTOSchema = z.object({ source: z.nativeEnum(MessageAttachmentSource), file: z.string(), fileName: z.string(), - applicationId: z.string(), - docId: z.string() + applicationId: z.string().optional(), + docId: z.string().optional() })) }); diff --git a/src/app/module/chat/domain/entity/message.ts b/src/app/module/chat/domain/entity/message.ts index ddae7ba6a..119873719 100644 --- a/src/app/module/chat/domain/entity/message.ts +++ b/src/app/module/chat/domain/entity/message.ts @@ -1,4 +1,5 @@ import { z } from "zod"; +import { MessageAttachmentFileType, MessageAttachmentSource } from "../../data/dto/message/messageOutputDTO"; const MessageEntitySchema = z.object({ $id: z.any().optional(), @@ -16,7 +17,15 @@ const MessageEntitySchema = z.object({ wxeMail: z.string(), userPhoto: z.string(), }), - sending: z.boolean().optional() + sending: z.boolean().optional(), + attachments: z.array(z.object({ + fileType: z.nativeEnum(MessageAttachmentFileType), + source: z.nativeEnum(MessageAttachmentSource), + file: z.string(), + fileName: z.string(), + applicationId: z.string(), + docId: z.string() + })) }) type Message = z.infer; @@ -41,6 +50,15 @@ export class MessageEntity implements Message { sending: boolean = false sendAttemp = 0 + attachments: { + fileType: MessageAttachmentFileType, + source: MessageAttachmentSource, + file: string, + fileName: string, + applicationId?: string, + docId?: string + }[] + constructor() {} get messageStatus() { diff --git a/src/app/module/chat/domain/mapper/messageMapper.ts b/src/app/module/chat/domain/mapper/messageMapper.ts index 0b550a11c..861104ded 100644 --- a/src/app/module/chat/domain/mapper/messageMapper.ts +++ b/src/app/module/chat/domain/mapper/messageMapper.ts @@ -1,6 +1,7 @@ import { MessageInputDTO } from "../../data/dto/message/messageInputDtO"; import { MessageOutPutDataDTO } from "../../data/dto/message/messageOutputDTO"; import { MessageEntity } from "../entity/message"; +import { attachments } from '../../../../../../../../../Downloads/equilibriumito-gabinete-digital-fo-23cf0fc4cbaa/equilibriumito-gabinete-digital-fo-23cf0fc4cbaa/src/app/models/beast-orm'; export class MessageMapper { static toDomain(DTO: MessageOutPutDataDTO) : MessageEntity { @@ -16,7 +17,8 @@ export class MessageMapper { requireUnlock: entity.requireUnlock, roomId: entity.roomId, senderId: entity.sender.wxUserId, - requestId: requestId + requestId: requestId, + attachments: entity.attachments } } } diff --git a/src/app/module/chat/domain/use-case/message-delete-live-use-case.service.ts b/src/app/module/chat/domain/use-case/message-delete-live-use-case.service.ts index 9838bea5a..81dc1eae9 100644 --- a/src/app/module/chat/domain/use-case/message-delete-live-use-case.service.ts +++ b/src/app/module/chat/domain/use-case/message-delete-live-use-case.service.ts @@ -20,7 +20,7 @@ export class MessageDeleteLiveUseCaseService { public repository: MessageRepositoryService ) { } - @SafeValidateSchema(MessageDeleteInputDTOSchema, 'MessageDeleteLiveUseCaseService') + @SafeValidateSchema(MessageDeleteInputDTOSchema, 'MessageDeleteUseCaseService') async execute(data: MessageDeleteInputDTO) { return this.repository.sendMessageDelete(data) } diff --git a/src/app/module/chat/infra/socket/signal-r.service.ts b/src/app/module/chat/infra/socket/signal-r.service.ts index c8833ae8e..c0e134054 100644 --- a/src/app/module/chat/infra/socket/signal-r.service.ts +++ b/src/app/module/chat/infra/socket/signal-r.service.ts @@ -41,7 +41,7 @@ export class SignalRService { this.deadConnectionBackGround = new Subject() this.deadConnectionBackGround.pipe( - switchMap(() => timer(300000)), + switchMap(() => timer(150000)), ).subscribe(() => { this.newConnection() }) diff --git a/src/app/pages/agenda/new-event/new-event.page.ts b/src/app/pages/agenda/new-event/new-event.page.ts index dce9c8b2d..8c0283405 100644 --- a/src/app/pages/agenda/new-event/new-event.page.ts +++ b/src/app/pages/agenda/new-event/new-event.page.ts @@ -16,7 +16,7 @@ import { ThemeService } from 'src/app/services/theme.service'; import { NgxMatDateFormats } from '@angular-material-components/datetime-picker'; import { NGX_MAT_DATE_FORMATS } from '@angular-material-components/datetime-picker'; import { SessionStore } from 'src/app/store/session.service'; -import { ChatMethodsService } from 'src/app/services/chat/chat-methods.service'; +// import { ChatMethodsService } from 'src/app/services/chat/chat-methods.service'; import { HttpErrorHandle } from 'src/app/services/http-error-handle.service'; import { environment } from 'src/environments/environment'; import { ProcessesService } from 'src/app/services/processes.service'; @@ -124,7 +124,7 @@ export class NewEventPage implements OnInit { private toastService: ToastService, public ThemeService: ThemeService, private platform: Platform, - private chatMethodService: ChatMethodsService, + // private chatMethodService: ChatMethodsService, private hhtpErrorHandle: HttpErrorHandle, private processeService: ProcessesService, public TaskService: TaskService, @@ -514,9 +514,9 @@ export class NewEventPage implements OnInit { "calendarId": CalendarId } - if (this.roomId) { - this.chatMethodService.sendMessage(this.roomId, data1); - } + // if (this.roomId) { + // this.chatMethodService.sendMessage(this.roomId, data1); + // } this.hhtpErrorHandle.httpsSucessMessagge('new event'); let data = Object.assign(this.postEvent, { id: eventId }) @@ -823,9 +823,9 @@ export class NewEventPage implements OnInit { "id": id, "calendarId": CalendarId } - if (this.roomId) { - this.chatMethodService.sendMessage(this.roomId, data); - } + // if (this.roomId) { + // this.chatMethodService.sendMessage(this.roomId, data); + // } let dataa = Object.assign(this.postEvent, { id: eventId }) this.modalController.dismiss(dataa); @@ -900,13 +900,13 @@ export class NewEventPage implements OnInit { this.postEvent.IsAllDayEvent = this.allDayCheck; this.postEvent.StartDate = this.setAlldayTime(this.postEvent.StartDate) this.postEvent.EndDate = this.setAlldayTimeEndDate(this.postEvent.EndDate) - + console.log('Recurso ativado!!'); } else { this.postEvent.IsAllDayEvent = this.allDayCheck; this.postEvent.EndDate = this.setAlldayTimeEndDateNotAlday(this.postEvent.EndDate) console.log('Recurso desativado'); - + } } diff --git a/src/app/pages/chat/chat.page.ts b/src/app/pages/chat/chat.page.ts index b806390cc..a2ad0c323 100644 --- a/src/app/pages/chat/chat.page.ts +++ b/src/app/pages/chat/chat.page.ts @@ -10,7 +10,7 @@ import { import { ModalController, Platform } from '@ionic/angular'; import { AuthService } from 'src/app/services/auth.service'; import { ChatService } from 'src/app/services/chat.service'; -import { ChatSystemService } from 'src/app/services/chat/chat-system.service' +// import { ChatSystemService } from 'src/app/services/chat/chat-system.service' import { GroupMessagesPage } from './group-messages/group-messages.page'; import { ContactsPage } from './messages/contacts/contacts.page'; import { MessagesPage } from './messages/messages.page'; @@ -117,7 +117,7 @@ export class ChatPage implements OnInit { public ThemeService: ThemeService, private dataService: DataService, private router: Router, - public ChatSystemService: ChatSystemService, + // public ChatSystemService: ChatSystemService, public RouteService: RouteService, private RoomRepositoryService: RoomRepositoryService, private messageLiveDataSourceService: MessageLiveDataSourceService, @@ -272,7 +272,7 @@ export class ChatPage implements OnInit { this.hideRefreshBtn = false; this.closeAllDesktopComponents() - this.ChatSystemService.getRoomById(this.roomId)?.roomLeave() + // this.ChatSystemService.getRoomById(this.roomId)?.roomLeave() } else { this.hideRefreshBtn = true; @@ -446,19 +446,19 @@ export class ChatPage implements OnInit { async closeNewEventComponentAndOpenChat({ roomId }) { this.closeAllDesktopComponents(); - this.ChatSystemService._group.forEach((room) => { - if (room.id == roomId) { + // this.ChatSystemService._group.forEach((room) => { + // if (room.id == roomId) { - this.openGroupMessagesPage(roomId) - } - }) + // this.openGroupMessagesPage(roomId) + // } + // }) - this.ChatSystemService._dm.forEach((room) => { - if (room.id == roomId) { - this.openMessagesPage(roomId) - } - }) + // this.ChatSystemService._dm.forEach((room) => { + // if (room.id == roomId) { + // this.openMessagesPage(roomId) + // } + // }) } @@ -582,7 +582,7 @@ export class ChatPage implements OnInit { }); modal.onDidDismiss().then(() => { - this.ChatSystemService.currentRoom.roomLeave() + // this.ChatSystemService.currentRoom.roomLeave() }); await modal.present(); } diff --git a/src/app/pages/chat/group-messages/group-contacts/group-contacts.page.ts b/src/app/pages/chat/group-messages/group-contacts/group-contacts.page.ts index 19e66eb4e..9494a6169 100644 --- a/src/app/pages/chat/group-messages/group-contacts/group-contacts.page.ts +++ b/src/app/pages/chat/group-messages/group-contacts/group-contacts.page.ts @@ -7,7 +7,7 @@ import { ChatService } from 'src/app/services/chat.service'; import { GroupMessagesPage } from '../group-messages.page'; import { ThemeService } from 'src/app/services/theme.service' import { SessionStore } from 'src/app/store/session.service'; -import { ChatSystemService } from 'src/app/services/chat/chat-system.service'; +// import { ChatSystemService } from 'src/app/services/chat/chat-system.service'; @Component({ selector: 'app-group-contacts', @@ -44,7 +44,7 @@ export class GroupContactsPage implements OnInit { private authService: AuthService, private navParams: NavParams, public ThemeService: ThemeService, - public ChatSystemService: ChatSystemService, + // public ChatSystemService: ChatSystemService, ) { diff --git a/src/app/pages/chat/group-messages/group-messages.page.ts b/src/app/pages/chat/group-messages/group-messages.page.ts index 19a6eb4ae..dc8c6b89a 100644 --- a/src/app/pages/chat/group-messages/group-messages.page.ts +++ b/src/app/pages/chat/group-messages/group-messages.page.ts @@ -25,7 +25,7 @@ import { SearchPage } from 'src/app/pages/search/search.page'; import { VoiceRecorder, RecordingData, GenericResponse } from 'capacitor-voice-recorder'; import { Filesystem, Directory } from '@capacitor/filesystem'; import { DomSanitizer } from '@angular/platform-browser'; -import { MessageService } from 'src/app/services/chat/message.service'; +// import { MessageService } from 'src/app/services/chat/message.service'; import { File } from '@awesome-cordova-plugins/file/ngx'; import { FileOpener } from '@awesome-cordova-plugins/file-opener/ngx'; import { SessionStore } from 'src/app/store/session.service'; @@ -1186,7 +1186,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { }); } - downloadFileMsg(msg: MessageService) { + downloadFileMsg(msg: any) { msg.downloadFileMsg() } @@ -1198,7 +1198,7 @@ export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy { downloadLink.click(); } - async openPreview(msg: MessageService) { + async openPreview(msg: any) { if (msg?.file?.type === "application/webtrix") { this.viewDocument(msg.file, msg.attachments.image_url) diff --git a/src/app/pages/chat/messages/contacts/contacts.page.ts b/src/app/pages/chat/messages/contacts/contacts.page.ts index a304b03f5..6e70a3751 100644 --- a/src/app/pages/chat/messages/contacts/contacts.page.ts +++ b/src/app/pages/chat/messages/contacts/contacts.page.ts @@ -5,7 +5,7 @@ import { AuthService } from 'src/app/services/auth.service'; import { ChatService } from 'src/app/services/chat.service'; import { MessagesPage } from '../messages.page'; import { ThemeService } from 'src/app/services/theme.service' -import { ChatSystemService} from 'src/app/services/chat/chat-system.service' +// import { ChatSystemService} from 'src/app/services/chat/chat-system.service' import { SessionStore } from 'src/app/store/session.service'; @Component({ @@ -23,7 +23,7 @@ export class ContactsPage implements OnInit { room:any; dm:any; sessionStore = SessionStore - userList = this.ChatSystemService.users + userList = [] constructor( private modalController: ModalController, @@ -31,7 +31,7 @@ export class ContactsPage implements OnInit { private chatService: ChatService, private authService: AuthService, public ThemeService: ThemeService, - public ChatSystemService: ChatSystemService, + // public ChatSystemService: ChatSystemService, ) { this.loggedUser = SessionStore.user.ChatData['data']; @@ -44,7 +44,7 @@ export class ContactsPage implements OnInit { ngOnInit() { // this.chatService.refreshtoken(); // this.loadUsers(); - this.ChatSystemService.getUser() + // this.ChatSystemService.getUser() } @@ -52,10 +52,10 @@ export class ContactsPage implements OnInit { this.textSearch = event.detail.value.toLowerCase(); - this.userList = this.ChatSystemService.users.filter((e) => { - const username = e.name.toLowerCase() - return username.includes(this.textSearch) - }) + // this.userList = this.ChatSystemService.users.filter((e) => { + // const username = e.name.toLowerCase() + // return username.includes(this.textSearch) + // }) } @@ -97,10 +97,10 @@ export class ContactsPage implements OnInit { this.chatService.createRoom(body).subscribe(async(res) => { this.room = res['room']; - this.ChatSystemService.getAllRooms(() => { - this.getDirectMessage(this.room._id); - this.loading = false - }, this.room._id); + // this.ChatSystemService.getAllRooms(() => { + // this.getDirectMessage(this.room._id); + // this.loading = false + // }, this.room._id); }, ()=> { diff --git a/src/app/pages/chat/messages/messages.page.ts b/src/app/pages/chat/messages/messages.page.ts index 364b5e0cc..481a24d9f 100644 --- a/src/app/pages/chat/messages/messages.page.ts +++ b/src/app/pages/chat/messages/messages.page.ts @@ -19,8 +19,8 @@ import { ThemeService } from 'src/app/services/theme.service' import { VoiceRecorder, RecordingData, GenericResponse } from 'capacitor-voice-recorder'; import { Haptics, ImpactStyle } from '@capacitor/haptics'; import { ViewEventPage } from 'src/app/modals/view-event/view-event.page'; -import { ChatSystemService } from 'src/app/services/chat/chat-system.service' -import { MessageService } from 'src/app/services/chat/message.service'; +// import { ChatSystemService } from 'src/app/services/chat/chat-system.service' +// import { MessageService } from 'src/app/services/chat/message.service'; import { FileType } from 'src/app/models/fileType'; import { SearchPage } from 'src/app/pages/search/search.page'; import { Storage } from '@ionic/storage'; @@ -33,7 +33,7 @@ import { FileOpener } from '@awesome-cordova-plugins/file-opener/ngx'; import { Filesystem, Directory, Encoding } from '@capacitor/filesystem'; import { NewEventPage } from '../../agenda/new-event/new-event.page'; import { NotificationsService } from 'src/app/services/notifications.service'; -import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service' +// import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service' import { FileValidatorService } from "src/app/services/file/file-validator.service" import { sanitize } from "sanitize-filename-ts"; import { FilePicker } from '@capawesome/capacitor-file-picker'; @@ -141,7 +141,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { private gestureController: GestureController, public ThemeService: ThemeService, private platform: Platform, - public ChatSystemService: ChatSystemService, + // public ChatSystemService: ChatSystemService, private storage: Storage, //private fileOpener: FileOpener, private sanitiser: DomSanitizer, @@ -149,7 +149,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { private file: File, private fileOpener: FileOpener, private router: Router, - public RochetChatConnectorService: RochetChatConnectorService, + // public RochetChatConnectorService: RochetChatConnectorService, private FileValidatorService: FileValidatorService, /// private roomRepositoryService: RoomRepositoryService, @@ -208,11 +208,11 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { // console.log(this.router.url); this.createDirectoryImage() // this.chatService.refreshtoken(); - this.ChatSystemService.getUserOfRoom(this.roomId).then((value) => { + // this.ChatSystemService.getUserOfRoom(this.roomId).then((value) => { - }).catch((error) => { - console.error(error) - }) + // }).catch((error) => { + // console.error(error) + // }) this.getChatMembers(); } catch (error) { @@ -354,8 +354,8 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { } deleteMessage(msgId: string) { - const room = this.ChatSystemService.getDmRoom(this.roomId) - this.alertService.confirmDeleteMessage(msgId, room); + // const room = this.ChatSystemService.getDmRoom(this.roomId) + // this.alertService.confirmDeleteMessage(msgId, room); } @@ -439,8 +439,8 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { } sendMessage() { - this.ChatSystemService.getDmRoom(this.roomId).send({}).then(() => { - }) + // this.ChatSystemService.getDmRoom(this.roomId).send({}).then(() => { + // }) } /* sendMessage(msg) { @@ -480,22 +480,22 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { const formData = new FormData(); formData.append("blobFile", blob); - this.ChatSystemService.getDmRoom(roomId).send({ - file: { - "type": "application/audio", - "msDuration": audioFile.value.msDuration, - "mimeType": audioFile.value.mimeType, - }, - attachments: [{ - "title": sanitize(fileName), - "title_link_download": true, - "type": "audio" - }], - temporaryData: formData, - attachmentsModelData: { - fileBase64: encodedData, - } - }) + // this.ChatSystemService.getDmRoom(roomId).send({ + // file: { + // "type": "application/audio", + // "msDuration": audioFile.value.msDuration, + // "mimeType": audioFile.value.mimeType, + // }, + // attachments: [{ + // "title": sanitize(fileName), + // "title_link_download": true, + // "type": "audio" + // }], + // temporaryData: formData, + // attachmentsModelData: { + // fileBase64: encodedData, + // } + // }) }); this.deleteRecording(); @@ -575,8 +575,8 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { // this.showLoader = false; // }); - this.members = this.ChatSystemService.getDmRoom(this.roomId).members - this.dmUsers = this.ChatSystemService.getDmRoom(this.roomId).membersExcludeMe + // this.members = this.ChatSystemService.getDmRoom(this.roomId).members + // this.dmUsers = this.ChatSystemService.getDmRoom(this.roomId).membersExcludeMe } showDateDuration(start: any) { @@ -644,20 +644,20 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { } async bookMeeting() { - let attendees = this.ChatSystemService.getDmRoom(this.roomId).members.map((val) => { - return { - Name: val.name, - EmailAddress: val.username + "@" + environment.domain, - IsRequired: "true", - } - }); + // let attendees = this.ChatSystemService.getDmRoom(this.roomId).members.map((val) => { + // return { + // Name: val.name, + // EmailAddress: val.username + "@" + environment.domain, + // IsRequired: "true", + // } + // }); this.popoverController.dismiss(); if (window.innerWidth <= 1024) { const modal = await this.modalController.create({ component: NewEventPage, componentProps: { - attendees: attendees, + // attendees: attendees, roomId: this.roomId }, cssClass: 'modal modal-desktop', @@ -719,21 +719,21 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { const formData = new FormData(); formData.append("blobFile", blob); - this.ChatSystemService.getDmRoom(roomId).send({ - file: { - "type": "application/img", - "guid": '' - }, - attachments: [{ - "title": "file.jpg", - "text": "description", - "title_link_download": false, - }], - temporaryData: formData, - attachmentsModelData: { - fileBase64: imageBase64, - } - }) + // this.ChatSystemService.getDmRoom(roomId).send({ + // file: { + // "type": "application/img", + // "guid": '' + // }, + // attachments: [{ + // "title": "file.jpg", + // "text": "description", + // "title_link_download": false, + // }], + // temporaryData: formData, + // attachmentsModelData: { + // fileBase64: imageBase64, + // } + // }) } @@ -791,26 +791,26 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { if (data.selected) { - this.ChatSystemService.getDmRoom(roomId).send({ - file: { - "name": res.data.selected.Assunto, - "type": "application/webtrix", - "ApplicationId": res.data.selected.ApplicationType, - "DocId": res.data.selected.Id, - "Assunto": res.data.selected.Assunto, - }, - temporaryData: res, - attachments: [{ - "title": res.data.selected.Assunto, - "description": res.data.selected.DocTypeDesc, - // "title_link": url_no_options, - "title_link_download": true, - "thumb_url": "https://static.ichimura.ed.jp/uploads/2017/10/pdf-icon.png", - // "message_link": url_no_options, - "text": res.data.selected.DocTypeDesc, - "type": "webtrix" - }], - }) + // this.ChatSystemService.getDmRoom(roomId).send({ + // file: { + // "name": res.data.selected.Assunto, + // "type": "application/webtrix", + // "ApplicationId": res.data.selected.ApplicationType, + // "DocId": res.data.selected.Id, + // "Assunto": res.data.selected.Assunto, + // }, + // temporaryData: res, + // attachments: [{ + // "title": res.data.selected.Assunto, + // "description": res.data.selected.DocTypeDesc, + // // "title_link": url_no_options, + // "title_link_download": true, + // "thumb_url": "https://static.ichimura.ed.jp/uploads/2017/10/pdf-icon.png", + // // "message_link": url_no_options, + // "text": res.data.selected.DocTypeDesc, + // "type": "webtrix" + // }], + // }) } }); @@ -852,21 +852,21 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { formData.append("blobFile", blob); //console.log('add file', formData) - this.ChatSystemService.getDmRoom(roomId).send({ - file: { - "type": "application/img", - "guid": '' - }, - temporaryData: formData, - attachments: [{ - "title": file.path, - "text": "description", - "title_link_download": false, - }], - attachmentsModelData: { - fileBase64: imageBase64, - } - }) + // this.ChatSystemService.getDmRoom(roomId).send({ + // file: { + // "type": "application/img", + // "guid": '' + // }, + // temporaryData: formData, + // attachments: [{ + // "title": file.path, + // "text": "description", + // "title_link_download": false, + // }], + // attachmentsModelData: { + // fileBase64: imageBase64, + // } + // }) } @@ -913,22 +913,22 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { formDataa.append('blobFile', blobb); /* console.log('add file', fileBase64) */ - this.ChatSystemService.getDmRoom(roomId).send({ - file: { - "type": resultt.files[0].mimeType, - "guid": '', - }, - attachments: [{ - "title": sanitize(resultt.files[0].name), - "name": sanitize(resultt.files[0].name), - // "text": "description", - "title_link_download": false, - }], - temporaryData: formDataa, - attachmentsModelData: { - fileBase64: '', - } - }) + // this.ChatSystemService.getDmRoom(roomId).send({ + // file: { + // "type": resultt.files[0].mimeType, + // "guid": '', + // }, + // attachments: [{ + // "title": sanitize(resultt.files[0].name), + // "name": sanitize(resultt.files[0].name), + // // "text": "description", + // "title_link_download": false, + // }], + // temporaryData: formDataa, + // attachmentsModelData: { + // fileBase64: '', + // } + // }) return } @@ -964,22 +964,22 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { formData.append('blobFile', blob); /* console.log('add file', fileBase64) */ - this.ChatSystemService.getDmRoom(roomId).send({ - file: { - "type": file.type, - "guid": '', - }, - attachments: [{ - "title": sanitize(fileName), - "name": sanitize(fileName), - // "text": "description", - "title_link_download": false, - }], - temporaryData: formData, - attachmentsModelData: { - fileBase64: encodedData, - } - }); + // this.ChatSystemService.getDmRoom(roomId).send({ + // file: { + // "type": file.type, + // "guid": '', + // }, + // attachments: [{ + // "title": sanitize(fileName), + // "name": sanitize(fileName), + // // "text": "description", + // "title_link_download": false, + // }], + // temporaryData: formData, + // attachmentsModelData: { + // fileBase64: encodedData, + // } + // }); } else { this.toastService._badRequest("Ficheiro inválido") } @@ -1120,7 +1120,7 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { } */ - downloadFileMsg(msg: MessageService) { + downloadFileMsg(msg: any) { msg.downloadFileMsg(); } @@ -1387,11 +1387,10 @@ export class MessagesPage implements OnInit, AfterViewInit, OnDestroy { } - messageDelete({messageId}) { + messageDelete(message: MessageEntity) { // this.messageRepositoryService.sendMessageDelete() - console.log('messageId', messageId) this.chatServiceService.messageDelete({ - messageId: messageId, + messageId: message.id, roomId: this.roomId, }) } diff --git a/src/app/pages/chat/new-group/new-group.page.ts b/src/app/pages/chat/new-group/new-group.page.ts index b31738dac..74e81adc6 100644 --- a/src/app/pages/chat/new-group/new-group.page.ts +++ b/src/app/pages/chat/new-group/new-group.page.ts @@ -3,7 +3,6 @@ import { ModalController, NavParams, PickerController, PopoverController } from import { GroupDurationPage } from 'src/app/shared/popover/group-duration/group-duration.page'; import { GroupContactsPage } from '../group-messages/group-contacts/group-contacts.page'; import { ThemeService } from 'src/app/services/theme.service'; -import { ChatSystemService } from 'src/app/services/chat/chat-system.service'; import { SessionStore } from 'src/app/store/session.service'; import { ToastService } from 'src/app/services/toast.service'; import { catchError } from 'rxjs/operators'; @@ -30,7 +29,7 @@ export class NewGroupPage implements OnInit { private modalController: ModalController, private navParams: NavParams, public ThemeService: ThemeService, - public ChatSystemService: ChatSystemService, + // public ChatSystemService: ChatSystemService, private toastService: ToastService, ) { this.loggedUserChat = SessionStore.user.ChatData['data']; @@ -60,133 +59,133 @@ export class NewGroupPage implements OnInit { async createGroup() { - let name = this.groupName.split(' ').join('-'); - //Take out all special characters in string - name = name.normalize("NFD").replace(/[\u0300-\u036f]/g, ""); + // let name = this.groupName.split(' ').join('-'); + // //Take out all special characters in string + // name = name.normalize("NFD").replace(/[\u0300-\u036f]/g, ""); - let customFields = {} - let res: any; + // let customFields = {} + // let res: any; - if(!SessionStore.user?.ChatData?.data) { - this.toastService._successMessage("Chat temporariamente indisponível") - } + // if(!SessionStore.user?.ChatData?.data) { + // this.toastService._successMessage("Chat temporariamente indisponível") + // } - try { + // try { - if (this.thedate) { - let customFields = { - "countDownDate": this.thedate - } - res = await this.ChatSystemService.createPrivateRoom(name, SessionStore.user.UserName, customFields); - } - else { - res = await this.ChatSystemService.createPrivateRoom(name, SessionStore.user.UserName, customFields); - } + // if (this.thedate) { + // let customFields = { + // "countDownDate": this.thedate + // } + // res = await this.ChatSystemService.createPrivateRoom(name, SessionStore.user.UserName, customFields); + // } + // else { + // res = await this.ChatSystemService.createPrivateRoom(name, SessionStore.user.UserName, customFields); + // } - try { - this.isGroupCreated = true; - this.addContacts(res.result); - this.ChatSystemService.getRoom([res.result]); + // try { + // this.isGroupCreated = true; + // this.addContacts(res.result); + // this.ChatSystemService.getRoom([res.result]); - setTimeout(() => { - this.ChatSystemService.subscribeToRoomUpdate(res.result.rid, res.result); - }, 10) + // setTimeout(() => { + // this.ChatSystemService.subscribeToRoomUpdate(res.result.rid, res.result); + // }, 10) - } catch (error) { - await this.ChatSystemService.getUser(); - await this.ChatSystemService.getAllRooms(); - await this.ChatSystemService.subscribeToRoom(); + // } catch (error) { + // await this.ChatSystemService.getUser(); + // await this.ChatSystemService.getAllRooms(); + // await this.ChatSystemService.subscribeToRoom(); - this.isGroupCreated = true; - this.addContacts(res.result); - this.ChatSystemService.getRoom([res.result]); + // this.isGroupCreated = true; + // this.addContacts(res.result); + // this.ChatSystemService.getRoom([res.result]); - setTimeout(() => { - this.ChatSystemService.subscribeToRoomUpdate(res.result.rid, res.result); - }, 10) + // setTimeout(() => { + // this.ChatSystemService.subscribeToRoomUpdate(res.result.rid, res.result); + // }, 10) - } + // } - if (res?.result?.rid) { + // if (res?.result?.rid) { - this.ChatSystemService.getAllRooms(() => { - if (!this.ChatSystemService.getGroupRoom(res.result.rid)) { - this.createGroupWithAttachmentsCath(res) - } else { - setTimeout(() => { + // this.ChatSystemService.getAllRooms(() => { + // if (!this.ChatSystemService.getGroupRoom(res.result.rid)) { + // this.createGroupWithAttachmentsCath(res) + // } else { + // setTimeout(() => { - this.createGroupWithAttachments(res) + // this.createGroupWithAttachments(res) - }, 500) - } - }, res.result.rid); + // }, 500) + // } + // }, res.result.rid); - } else { + // } else { - this.toastService._badRequest('Existe um grupo com este nome!'); + // this.toastService._badRequest('Existe um grupo com este nome!'); - } + // } - } catch(error) { - this.toastService._successMessage("Chat temporariamente indisponível") - } + // } catch(error) { + // this.toastService._successMessage("Chat temporariamente indisponível") + // } } createGroupWithAttachmentsCath(res: any) { - if (!this.ChatSystemService.getGroupRoom(res.result.rid)) { - setTimeout(() => { - this.createGroupWithAttachmentsCath(res) - }, 1500) - } else { - this.createGroupWithAttachments(res) - } + // if (!this.ChatSystemService.getGroupRoom(res.result.rid)) { + // setTimeout(() => { + // this.createGroupWithAttachmentsCath(res) + // }, 1500) + // } else { + // this.createGroupWithAttachments(res) + // } } createGroupWithAttachments(res: any) { - this.ChatSystemService.getGroupRoom(res.result.rid).hasLoadHistory = true; + // this.ChatSystemService.getGroupRoom(res.result.rid).hasLoadHistory = true; - if (this.documents) { - this.documents.forEach(element => { - this.ChatSystemService.getGroupRoom(res.result.rid).send({ - file: { - "name": element.Assunto, - "type": "application/webtrix", - "ApplicationId": element.ApplicationId, - "DocId": element.DocId, - "Assunto": element.Assunto, - }, - temporaryData: { - data: { - selected: { - Id: element.DocId, - ApplicationType: element.ApplicationId - } - } - }, - attachments: [{ - "title": element.Assunto, - "description": element.Assunto, - "title_link_download": true, - "type": "webtrix", - "text": element.Assunto, - "thumb_url": "https://static.ichimura.ed.jp/uploads/2017/10/pdf-icon.png", - }], - }) - }); - } + // if (this.documents) { + // this.documents.forEach(element => { + // this.ChatSystemService.getGroupRoom(res.result.rid).send({ + // file: { + // "name": element.Assunto, + // "type": "application/webtrix", + // "ApplicationId": element.ApplicationId, + // "DocId": element.DocId, + // "Assunto": element.Assunto, + // }, + // temporaryData: { + // data: { + // selected: { + // Id: element.DocId, + // ApplicationType: element.ApplicationId + // } + // } + // }, + // attachments: [{ + // "title": element.Assunto, + // "description": element.Assunto, + // "title_link_download": true, + // "type": "webtrix", + // "text": element.Assunto, + // "thumb_url": "https://static.ichimura.ed.jp/uploads/2017/10/pdf-icon.png", + // }], + // }) + // }); + // } - this.ChatSystemService.getAllRooms(); + // this.ChatSystemService.getAllRooms(); - setTimeout(() => { - this.groupName = "" - }, 150); + // setTimeout(() => { + // this.groupName = "" + // }, 150); } async addContacts(room) { diff --git a/src/app/pages/login/login.page.ts b/src/app/pages/login/login.page.ts index 6890a104a..3a62061cd 100644 --- a/src/app/pages/login/login.page.ts +++ b/src/app/pages/login/login.page.ts @@ -11,15 +11,12 @@ import { ClearStoreService } from 'src/app/services/clear-store.service'; import { ChangeProfileService } from 'src/app/services/change-profile.service'; import { ThemeService } from 'src/app/services/theme.service'; import { PermissionService } from 'src/app/services/permission.service'; -import { MessageModel, DeleteMessageModel } from '../../models/beast-orm'; -import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service'; -import { ChatSystemService } from 'src/app/services/chat/chat-system.service'; +// import { ChatSystemService } from 'src/app/services/chat/chat-system.service'; import { ChatService } from 'src/app/services/chat.service'; import { NotificationHolderService } from 'src/app/store/notification-holder.service'; import { Platform } from '@ionic/angular'; import { FirstEnterService } from '../../services/first-enter.service'; import { Storage } from '@ionic/storage'; -import { CPSession } from 'src/app/store/documentManagement'; import { StorageService } from 'src/app/services/storage.service'; import { DeviceService } from 'src/app/services/device.service' import { Cy } from 'cypress/enum' @@ -54,8 +51,7 @@ export class LoginPage implements OnInit { private changeProfileService: ChangeProfileService, public ThemeService: ThemeService, public p: PermissionService, - private RochetChatConnectorService: RochetChatConnectorService, - public ChatSystemService: ChatSystemService, + // public ChatSystemService: ChatSystemService, private ChatService: ChatService, private platform: Platform, private FirstEnterService: FirstEnterService, @@ -141,16 +137,11 @@ export class LoginPage implements OnInit { if (attempt.UserId == SessionStore.user.UserId) { await this.authService.SetSession(attempt, this.userattempt); - /* CPSession.save(data) */ this.changeProfileService.run(); if (attempt.ChatData) { try { - - await MessageModel.deleteAll(); - await DeleteMessageModel.deleteAll(); - this.ChatSystemService.clearChat(); this.NotificationHolderService.clear() await this.authService.loginToChatWs(); this.ChatService.setheader() @@ -172,19 +163,14 @@ export class LoginPage implements OnInit { } else { - this.RochetChatConnectorService.logout(); this.clearStoreService.clear(); - this.ChatSystemService.clearChat(); + // this.ChatSystemService.clearChat(); this.NotificationHolderService.clear() SessionStore.delete(); window.localStorage.clear(); - await MessageModel.deleteAll(); - await DeleteMessageModel.deleteAll(); - CPSession.clear(); this.storage.clear(); await this.authService.SetSession(attempt, this.userattempt); - /* CPSession.save(data) */ this.changeProfileService.run(); diff --git a/src/app/services/alert.service.ts b/src/app/services/alert.service.ts index e3f6895fe..08798eecd 100644 --- a/src/app/services/alert.service.ts +++ b/src/app/services/alert.service.ts @@ -1,6 +1,6 @@ import { Injectable } from '@angular/core'; import { AlertController, AnimationController } from '@ionic/angular'; -import { ChatSystemService } from './chat/chat-system.service'; +// import { ChatSystemService } from './chat/chat-system.service'; import { ToastService } from './toast.service'; @Injectable({ @@ -12,7 +12,7 @@ export class AlertService { public alertController: AlertController, private animationController: AnimationController, private toastService: ToastService, - public ChatSystemService: ChatSystemService, + // public ChatSystemService: ChatSystemService, ) { } async presentAlert(message:string) { @@ -58,9 +58,9 @@ export class AlertService { handler: () => { //const loader = this.toastService.loading(); - this.ChatSystemService.deleteMessage(msgId).then(() => { - room.deleteMessage(msgId) - }).catch((error) => console.error(error)) + // this.ChatSystemService.deleteMessage(msgId).then(() => { + // room.deleteMessage(msgId) + // }).catch((error) => console.error(error)) //this.ChatSystemService.subscribeToRoomUpdate(room._id, room); //loader.remove(); } diff --git a/src/app/services/auth.service.ts b/src/app/services/auth.service.ts index 04657ed71..5b0e2b780 100644 --- a/src/app/services/auth.service.ts +++ b/src/app/services/auth.service.ts @@ -7,20 +7,19 @@ import { BehaviorSubject, of } from 'rxjs'; import { AlertController, Platform } from '@ionic/angular'; import { SessionStore } from '../store/session.service'; import { AESEncrypt } from '../services/aesencrypt.service'; -import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service'; +// import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service'; import { Router } from '@angular/router'; -import { NfService } from 'src/app/services/chat/nf.service'; -import { MessageService } from 'src/app/services/chat/message.service'; +// import { NfService } from 'src/app/services/chat/nf.service'; +//import { MessageService } from 'src/app/services/chat/message.service'; import { ProcessesService } from 'src/app/services/processes.service'; import { AttachmentsService } from 'src/app/services/attachments.service'; -import { RoomService } from './chat/room.service'; +//import { RoomService } from './chat/room.service'; import { Storage } from '@ionic/storage'; import { InitialsService } from './functions/initials.service'; import { PermissionService } from './permission.service'; -import { ChatSystemService } from 'src/app/services/chat/chat-system.service'; +// import { ChatSystemService } from 'src/app/services/chat/chat-system.service'; import { HttpErrorHandle } from 'src/app/services/http-error-handle.service'; import { captureException } from '@sentry/angular'; -import { CPSession } from '../store/documentManagement'; import { catchError, tap } from 'rxjs/operators'; @Injectable({ providedIn: 'root' @@ -40,15 +39,15 @@ export class AuthService { private storageService: StorageService, public alertController: AlertController, private aesencrypt: AESEncrypt, - private RochetChatConnectorService: RochetChatConnectorService, + // private RochetChatConnectorService: RochetChatConnectorService, private router: Router, - private NfService: NfService, + // private NfService: NfService, private processesService: ProcessesService, private AttachmentsService: AttachmentsService, private storage: Storage, private initialsService: InitialsService, public p: PermissionService, - public ChatSystemService: ChatSystemService, + // public ChatSystemService: ChatSystemService, private httpErroHandle: HttpErrorHandle, private errorHandler: ErrorHandler, private platform: Platform,) { @@ -183,110 +182,63 @@ export class AuthService { setTimeout(() => { if (SessionStore.user.ChatData?.data) { - this.RochetChatConnectorService.logout(); - this.RochetChatConnectorService.connect(); - this.RochetChatConnectorService.login().then((message: any) => { - console.log('Chat login', message) + // this.RochetChatConnectorService.logout(); + // this.RochetChatConnectorService.connect(); + // this.RochetChatConnectorService.login().then((message: any) => { + // console.log('Chat login', message) - SessionStore.user.RochetChatUserId = message.result.id - SessionStore.save() + // SessionStore.user.RochetChatUserId = message.result.id + // SessionStore.save() - this.ChatSystemService.loadChat() - this.RochetChatConnectorService.setStatus('online') - window['RochetChatConnectorService'] = this.RochetChatConnectorService - setTimeout(() => { - this.ChatSystemService.getAllRooms(); - this.RochetChatConnectorService.setStatus('online') - }, 200); + // this.ChatSystemService.loadChat() + // this.RochetChatConnectorService.setStatus('online') + // window['RochetChatConnectorService'] = this.RochetChatConnectorService + // setTimeout(() => { + // this.ChatSystemService.getAllRooms(); + // this.RochetChatConnectorService.setStatus('online') + // }, 200); - }).catch((error) => { - console.error(SessionStore.user.ChatData, 'web socket login', error) + // }).catch((error) => { + // console.error(SessionStore.user.ChatData, 'web socket login', error) - if(window.location.pathname.includes('/home/')) { - setTimeout(() => { - this.loginToChatWs(); - }, 4000) - } + // if(window.location.pathname.includes('/home/')) { + // setTimeout(() => { + // this.loginToChatWs(); + // }, 4000) + // } - }) + // }) } // before sending a message with a attachment - this.NfService.beforeSendAttachment = async (message: MessageService, room?: RoomService) => { +8 + // this.NfService.downloadFileMsg = async (message: MessageService, room?: RoomService) => { - if (message.hasFile) { - if (message.file.type != 'application/webtrix') { - const formData = message.temporaryData + // // + // let downloadFile = ""; + // if (message.file.type == "application/img") { + // const event: any = await this.AttachmentsService.downloadFile(message.file.guid).toPromise(); - try { - let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise() - message.file.guid = guid.path + // if (event.type === HttpEventType.DownloadProgress) { + // //this.downloadProgess = Math.round((100 * event.loaded) / event.total); + // return true + // } else if (event.type === HttpEventType.Response) { + // downloadFile = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), '')); - message.downloadFileMsg() - message.uploadingFile = false + // message.file = { + // guid: message.file.guid, + // image_url: downloadFile, + // type: message.file.type + // } - return true - } catch (e) { - window['e'] = e - console.error('BeforesendAtachment', e) - message.uploadingFile = false - this.httpErroHandle.httpStatusHandleUploadFile(e); - return false - } - - } else { - try { - const res = message.temporaryData - - let url = await this.processesService.GetDocumentUrl(res.data.selected.Id, res.data.selected.ApplicationType).toPromise(); - - let url_no_options: string = url.replace("webTRIX.Viewer", "webTRIX.Viewer.Branch1"); - message.attachments[0].title_link = url_no_options - message.attachments[0].message_link = url_no_options - - message.uploadingFile = false - - return true - } catch (e) { - window['e'] = e - console.error('BeforesendAtachment', e) - message.uploadingFile = false - this.httpErroHandle.httpStatusHandleUploadFile(e); - return false - } - } - } - - return false - } - - this.NfService.downloadFileMsg = async (message: MessageService, room?: RoomService) => { - - // - let downloadFile = ""; - if (message.file.type == "application/img") { - const event: any = await this.AttachmentsService.downloadFile(message.file.guid).toPromise(); - - if (event.type === HttpEventType.DownloadProgress) { - //this.downloadProgess = Math.round((100 * event.loaded) / event.total); - return true - } else if (event.type === HttpEventType.Response) { - downloadFile = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), '')); - - message.file = { - guid: message.file.guid, - image_url: downloadFile, - type: message.file.type - } - - return true - } - return false - } - }; + // return true + // } + // return false + // } + // }; }, 1) } diff --git a/src/app/services/chat.service.ts b/src/app/services/chat.service.ts index 5d8072ddb..3cc3017db 100644 --- a/src/app/services/chat.service.ts +++ b/src/app/services/chat.service.ts @@ -9,7 +9,7 @@ import { PermissionService } from './permission.service'; import { SessionStore } from '../store/session.service'; import { ChangeProfileService } from 'src/app/services/change-profile.service'; import { NetworkServiceService , ConnectionStatus} from 'src/app/services/network-service.service'; -import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service'; +// import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service'; @Injectable({ providedIn: 'root' @@ -31,7 +31,8 @@ export class ChatService { public p: PermissionService, private changeProfileService: ChangeProfileService, private NetworkServiceService: NetworkServiceService, - private RochetChatConnectorService: RochetChatConnectorService) { + // private RochetChatConnectorService: RochetChatConnectorService + ) { this.changeProfileService.registerCallback(() => { this.setheader(); diff --git a/src/app/services/chat/change-message-queue.service.spec.ts b/src/app/services/chat/change-message-queue.service.spec.ts deleted file mode 100644 index c6528866a..000000000 --- a/src/app/services/chat/change-message-queue.service.spec.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { TestBed } from '@angular/core/testing'; - -import { ChangeMessageQueueService } from './change-message-queue.service'; - -describe('ChangeMessageQueueService', () => { - let service: ChangeMessageQueueService; - - beforeEach(() => { - TestBed.configureTestingModule({}); - service = TestBed.inject(ChangeMessageQueueService); - }); - - it('should be created', () => { - expect(service).toBeTruthy(); - }); -}); diff --git a/src/app/services/chat/change-message-queue.service.ts b/src/app/services/chat/change-message-queue.service.ts deleted file mode 100644 index 8c37ff81e..000000000 --- a/src/app/services/chat/change-message-queue.service.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { Injectable } from '@angular/core'; - -@Injectable({ - providedIn: 'root' -}) -export class ChangeMessageQueueService { - constructor() {} -} diff --git a/src/app/services/chat/chat-methods.service.spec.ts b/src/app/services/chat/chat-methods.service.spec.ts deleted file mode 100644 index 3e474e69d..000000000 --- a/src/app/services/chat/chat-methods.service.spec.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { TestBed } from '@angular/core/testing'; - -import { ChatMethodsService } from './chat-methods.service'; - -describe('ChatMethodsService', () => { - let service: ChatMethodsService; - - beforeEach(() => { - TestBed.configureTestingModule({}); - service = TestBed.inject(ChatMethodsService); - }); - - it('should be created', () => { - expect(service).toBeTruthy(); - }); -}); diff --git a/src/app/services/chat/chat-methods.service.ts b/src/app/services/chat/chat-methods.service.ts deleted file mode 100644 index abb25e3a4..000000000 --- a/src/app/services/chat/chat-methods.service.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { Injectable } from '@angular/core'; -import { ChatService } from '../chat.service'; -import { v4 as uuidv4 } from 'uuid' - -@Injectable({ - providedIn: 'root' -}) -export class ChatMethodsService { - - constructor( - private chatService: ChatService) { - } - - sendMessage(roomId:string, data:any) { - - let body = { - "message": - { - "rid": roomId, - "msg":"", - "file": { - "type": "application/meeting", - "subject": data.subject, - "start_date": data.start, - "end_date": data.end, - "venue": data.venue, - "id": data.id, - "calendarId": data.calendarId - } - } - } - this.chatService.sendMessage(body).subscribe(res=> {}); - } - - send({roomId, msg, attachments = null, file = null, localReference = null}) { - - let body = { - "message": - { - rid: roomId, - localReference: localReference, - msg: msg, - attachments, - file - } - } - - return this.chatService.sendMessage(body) - } - - deleteMessage(body) { - return this.chatService.deleteMessage(body) - } - -} \ No newline at end of file diff --git a/src/app/services/chat/chat-system.service.spec.ts b/src/app/services/chat/chat-system.service.spec.ts deleted file mode 100644 index 3afb80345..000000000 --- a/src/app/services/chat/chat-system.service.spec.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { TestBed } from '@angular/core/testing'; - -import { ChatSystemService } from './chat-system.service'; - -describe('ChatSystemService', () => { - let service: ChatSystemService; - - beforeEach(() => { - TestBed.configureTestingModule({}); - service = TestBed.inject(ChatSystemService); - }); - - it('should be created', () => { - expect(service).toBeTruthy(); - }); -}); diff --git a/src/app/services/chat/chat-system.service.ts b/src/app/services/chat/chat-system.service.ts deleted file mode 100644 index b7e5b4d02..000000000 --- a/src/app/services/chat/chat-system.service.ts +++ /dev/null @@ -1,813 +0,0 @@ -import { Injectable } from '@angular/core'; -import { RoomService } from './room.service'; -import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service'; -import { MessageService } from 'src/app/services/chat/message.service'; -import { SessionStore } from 'src/app/store/session.service'; -import { capitalizeTxt } from 'src/plugin/text'; -import { Update as room } from 'src/app/models/chatMethod'; -import { Storage } from '@ionic/storage'; -import { ModalController, NavController, Platform } from '@ionic/angular'; -import { SqliteService } from 'src/app/services/sqlite.service'; -import { ChatService } from 'src/app/services/chat.service'; -import { NativeNotificationService } from 'src/app/services/native-notification.service'; -import { SortService } from '../functions/sort.service'; -import { chatUser } from 'src/app/models/chatMethod'; -import { NfService } from 'src/app/services/chat/nf.service' -import { ChangeProfileService } from '../change-profile.service'; -import { ChatMethodsService } from './chat-methods.service'; -import { AESEncrypt } from '../aesencrypt.service' -import { AttachmentsService } from 'src/app/services/attachments.service'; -import { NetworkServiceService } from 'src/app/services/network-service.service'; -import { ViewedMessageService } from './viewed-message.service' -import { NotificationsService } from '../notifications.service'; -import { Subscribe } from '../subcribe'; -import { Plugins } from '@capacitor/core'; - -const { App } = Plugins; - -@Injectable({ - providedIn: 'root' -}) -export class ChatSystemService { - - dm: { [key: string]: RoomService } = {} - group: { [key: string]: RoomService } = {} - - _dm: RoomService[] = [] - _group: RoomService[] = [] - - loadingWholeList = false; - - dmCount = 0; - groupCount = 0; - - currentRoom: RoomService = null - users: chatUser[] = [] - sessionStore = SessionStore - delete = [] - loadingUsers = false - - onRoomsLoad = new Subscribe({ execute: false, deleteOnExecute: true }) - private mainChangeDetector: Function = () => {} - - - constructor( - private RochetChatConnectorService: RochetChatConnectorService, - private storage: Storage, - private platform: Platform, - private sqlservice: SqliteService, - private NativeNotificationService: NativeNotificationService, - private sortService: SortService, - private ChatService: ChatService, - private NfService: NfService, - private changeProfileService: ChangeProfileService, - private chatService: ChatService, - private ChatMethodsService: ChatMethodsService, - private AESEncrypt: AESEncrypt, - private AttachmentsService: AttachmentsService, - private NetworkServiceService: NetworkServiceService, - private ViewedMessageService: ViewedMessageService, - private notificationService: NotificationsService, - private modalController: ModalController, - private navController: NavController - ) { - - - // this.RochetChatConnectorService.registerCallback({ - // type: 'reConnect', - // funx: async () => { - // /** - // * @description when the phone is in the background for a long time it could disconnects from the socket then the socket reconnects automatically, - // * when the connection is lost the subscribe is also lost, so we have to subscribe again when reconnection is establish. - // */ - - // this.RochetChatConnectorService.setStatus('online') - // this.getUserStatus(); - // await this.chatService.refreshtoken(); - // this.getUser(); - // this.getAllRooms(); - // this.subscribeToRoom(); - // // - - - // if (this.currentRoom) { - // this.currentRoom.loadHistory({ forceUpdate: true }) - // } - - // for (const id in this.dm) { - // this.dm[id].hasLoadHistory = false - // } - - // for (const id in this.group) { - // this.group[id].hasLoadHistory = false - // } - - // } - // }) - - // if (this.sessionStore.user.Inactivity) { - // this.loadChat(); - // } - - - // if (SessionStore.user?.ChatData?.data) { - // this.restoreRooms(); - // } - - // document.addEventListener('resume', () => { - // this.RochetChatConnectorService.setStatus('online') - // if (this._dm?.length == 0 && this._group?.length == 0) { - // if (SessionStore.user?.ChatData?.data) { - // this.getAllRooms(); - // } - - // } - // }); - - // try { - // if (!this.platform.is('desktop')) { - // App.addListener('appStateChange', ({ isActive }) => { - // if (isActive) { - // // The app is in the foreground. - // console.log('App is in the foreground'); - - // if (SessionStore.user?.ChatData?.data) { - // this.currentRoom?.loadHistory({ forceUpdate: true }) - // } - - // setTimeout(() => { - // if (SessionStore.user?.ChatData?.data) { - // this.subscribeToRoom() - // this.RochetChatConnectorService.setStatus('online') - // } - // }, 1000); - - // /* this.reloadComponent(true) */ - // } else { - // // The app is in the background. - // console.log('App is in the background'); - // // You can perform actions specific to the background state here. - // } - // }); - // } - // } catch(error) {} - } - - loadChat() { - // if (SessionStore.user?.ChatData?.data) { - // this.ReLoadChat() - // } - } - - private async ReLoadChat() { - - // if (SessionStore.user?.ChatData?.data) { - // this.getUserStatus(); - // await this.chatService.refreshtoken(); - - // this.restoreUsers(); - // await this.getUser(); - // await this.restoreRooms(); - // await this.getAllRooms(); - // this.subscribeToRoom(); - // } - // - - } - - clearChat() { - // this.dm = {} - // this.group = {} - // this._dm = [] - // this._group = [] - - // this.loadingWholeList = false; - - // this.dmCount = 0; - // this.groupCount = 0; - - // this.currentRoom = null - // this.users = [] - // this.storage.remove('Users'); - } - - openRoom(roomId) { - - if (this.currentRoom) { - this.currentRoom.roomLeave() - } - - if (this.getDmRoom(roomId)) { - this.currentRoom = this.getDmRoom(roomId) - } else if (this.getGroupRoom(roomId)) { - this.currentRoom = this.getGroupRoom(roomId) - } - - this.currentRoom.open() - - } - - getRoomById(roomId) { - if (this.getDmRoom(roomId)) { - return this.getDmRoom(roomId) - } else if (this.getGroupRoom(roomId)) { - return this.getGroupRoom(roomId) - } - } - - async restoreRooms() { - - // try { - // const _rooms = await this.storage.get('Rooms'); - - // if (_rooms) { - // for (let roomData of this.sortArrayISODate(_rooms)) { - // await this.prepareRoom(roomData); - // } - // } - // } catch (e) { } - - } - - async restoreUsers() { - const users = await this.storage.get('Users'); - - if (users) { - this.users = users - - } - } - - sortArrayISODate(messages: any): any[] { - - return messages.sort((a, b) => - new Date(b._updatedAt).getTime() - - - new Date(a._updatedAt).getTime()) - } - - async getAllRooms(callback: Function = () => { }, roomIdCallback = "") { - this.loadingWholeList = true - var rooms; - - if (this.RochetChatConnectorService.isLogin) { - try { - rooms = await this.RochetChatConnectorService.getRooms(); - } catch (error) { - this.loadingWholeList = false - console.error('chatgetrooms', error) - } - try { - await this.storage.remove('Rooms'); - } catch (e) { } - } - - let index = 0 - - let _rooms = rooms?.result?.update - - if (_rooms) { - - _rooms = _rooms.map(e => { - e["_updatedAt"] = e._updatedAt || e._updatedAt['$date'] - return e - }) - - for (let roomData of this.sortArrayISODate(_rooms)) { - - const roomId = this.getRoomId(roomData); - - if (roomData.t == 'd') { - await this.prepareRoom(roomData); - } else { - if (roomData.t === 'p') { - await this.prepareRoom(roomData); - } - else { - await this.prepareRoom(roomData); - } - } - - if (roomId == roomIdCallback) { - callback() - } - - index++; - } - } - - this.loadingWholeList = false - this.sortRoomList() - await this.storage.set('Rooms', _rooms); - - this.onRoomsLoad.executor() - } - - - async getRoom(_rooms: any) { - this.loadingWholeList = true - - let index = 0 - - if (_rooms) { - - _rooms = _rooms.map(e => { - e["_updatedAt"] = e._updatedAt || e._updatedAt['$date'] - return e - }) - - for (let roomData of this.sortArrayISODate(_rooms)) { - - if (roomData.t == 'd') { - - await this.prepareRoom(roomData); - } else { - if (roomData.t === 'p') { - - await this.prepareRoom(roomData); - - } - else { - - await this.prepareRoom(roomData); - } - - } - - index++; - } - } - - this.loadingWholeList = false - this.sortRoomList() - - this.onRoomsLoad.executor() - } - - /** - * @description sort room list by last message date - */ - sortRoomList = () => { - - this._dm = this.sortService.sortDate(this._dm, '_updatedAt').reverse() - this._group = this.sortService.sortDate(this._group, '_updatedAt').reverse() - } - - /** - * @description subscribe all room - */ - subscribeToRoom() { - - // if (SessionStore.user?.ChatData?.data) { - - // for (const id in this.dm) { - // this.defaultSubtribe(id) - // } - - // for (const id in this.group) { - // this.defaultSubtribe(id) - // } - - // this.RochetChatConnectorService.streamNotifyLogged().then((subscription => { })) - - // this.RochetChatConnectorService.subStreamMessageUser().then((subscription => { - // console.log({subscription}) - // })) - // } else { - - // setTimeout(() => { - // throw ('No chat data'); - // }, 1000) - // } - - } - - /** - * @description when a new room is create, needs to subtribe in order to receive updates - * @param id - * @param roomData - */ - subscribeToRoomUpdate(id, roomData) { - - // this.defaultSubtribe(id); - - // this.prepareRoom(roomData); - - // this.getGroupRoom(id).loadHistory({}); - - } - - - /** - * @deprecated things a room need to subscribe on - * @param id room id - */ - private defaultSubtribe(id: any) { - - // const room = this.getRoomById(id); - - // if (!room.subscribeAttempt) { - - // try { - - // room.subscribeAttempt = true; - // } catch (error) { - // console.log("error") - // } - - - // this.RochetChatConnectorService.streamRoomMessages(id).then((subscription) => { - // room.status.receive.message = true; - // }) - - // this.RochetChatConnectorService.subStreamNotifyRoom(id, 'typing', false).then((subscription) => { - // room.status.receive.typing = true; - // // - // }) - - // this.RochetChatConnectorService.subStreamNotifyRoom(id, 'readMessage', false).then((subscription) => { - // room.status.receive.readMessage = true; - // }) - - // this.RochetChatConnectorService.streamNotifyRoomDeleteMessage(id).then((subscription) => { - // room.status.receive.deleteMessage = true; - // }) - // } - - } - - private fix_updatedAt(message) { - if (message.result) { - message.result._updatedAt = message.result._updatedAt['$date'] - } else if (message._updatedAt) { - if (message._updatedAt.hasOwnProperty('$date')) { - message._updatedAt = message._updatedAt['$date'] - } - } - return message - } - - /** - * @description create a representation of an room in these instance this.dm, this.group ... - * @param roomData - */ - prepareRoom(roomData) { - - - /** - * @description data used to define or create room - */ - - - roomData = this.fix_updatedAt(roomData) - const setData = { - customFields: roomData.customFields, - id: this.getRoomId(roomData), - name: this.getRoomName(roomData), - t: roomData.t, - lastMessage: this.getRoomLastMessage(roomData), - _updatedAt: new Date(roomData._updatedAt || roomData._updatedAt['$date']), - u: roomData.u || {}, - members: [], - membersExcludeMe: [] - } - - let roomId = this.getRoomId(roomData); - - let chat = false - if (roomData?.usernames) { - if (roomData?.usernames?.includes("chat.admin")) { - chat = true - } - } - - if (setData.name != 'Rocket Cat' && setData.name != 'general' && chat == false) { - // create room - if (!this.roomExist(roomId)) { - let room: RoomService = new RoomService(this.RochetChatConnectorService, new MessageService(this.NfService, this.RochetChatConnectorService, this.ChatMethodsService, this.AESEncrypt, this.AttachmentsService, this.NetworkServiceService, this, this.notificationService), this.storage, this.platform, this.sqlservice, this.NativeNotificationService, this.sortService, this.ChatService, this.NfService, this.ChatMethodsService, this.AESEncrypt, this.AttachmentsService, this.NetworkServiceService, this, this.ViewedMessageService, this.notificationService,this.modalController,this.navController) - room.setData(setData) - room.receiveMessage() - room.getAllUsers = this.getUsers - room.receiveMessageDelete(); - room.sortRoomList = this.sortRoomList - room.chatServiceDeleteRoom = this.deleteRoom - room.isGroup = !this.isIndividual(roomData) - room.info() - - - // create individual room - if (this.isIndividual(roomData)) { - - this.dm[roomId] = room - this._dm.push(room) - this.dmCount++ - - } else { - // create group room - - this.group[roomId] = room - this._group.push(room) - this.groupCount++ - - } - - this.defaultSubtribe(roomId) - } else { - // in this case room is already present, therefor it will only be necessary, - // to redefine - - if (this.dm[roomId]) { - this.dm[roomId].setData(setData) - } else if (this.group[roomId]) { - this.group[roomId].setData(setData) - } - - } - } - - } - - - deleteRoom = (roomId) => { - - this.delete.push(roomId) - delete this.group[roomId]; - this._group = this._group.filter((e) => e.id != roomId); - } - - deleteRecently(roomId) { - return this.delete.includes(roomId) - } - - roomExist(roomId) { - return this.dm[roomId]?.id || this.group[roomId]?.id - } - - getReceptorName(roomData) { - try { - return roomData.usernames.find((e) => e != SessionStore.user.UserName) - } catch (e) { - return '*' - } - } - - /** - * @description update user status. this method is called once only - * @param id user ID - */ - private getUserStatus(id?: string) { - - this.RochetChatConnectorService.getUserStatus(async (d) => { - - const userId = d.fields.args[0][0] - const username = d.fields.args[0][1] - let statusNum = d.fields.args[0][2] - - const statusText = this.statusNumberToText(statusNum) - - for (const user in this.users) { - if (this.users[user]._id == userId) { - this.users[user].status = statusText - } - } - - this.getUser() - - }) - } - - getUserByName(username) { - return this.users.find((user) => user.username == username) - } - - /** - * @description convert rocketchat statues num to readable string - * @param text - * @returns - */ - statusNumberToText(text) { - if (text == '0') { - return "offline" - } - else if (text == '1') { - return "online" - } - else if (text == '2') { - return "away" - } - else if (text == '3') { - return "busy" - } - } - - - deleteMessage(id?) { - return this.RochetChatConnectorService.deleteMessage(id); - } - - leaveRoom(id?) { - return this.RochetChatConnectorService.leaveRoom(id); - } - - async hideRoom(id) { - this._dm.forEach((md, index) => { - if (md.id == id) { - this._dm.splice(index, 1) - delete this.dm[id] - } - }); - - this._group.forEach((group, index) => { - if (group.id == id) { - this._group.splice(index, 1) - delete this.group[id] - } - }) - } - - hidingRoom(id?) { - - return this.RochetChatConnectorService.hidingRoom(id).then(() => { - // this.hideRoom(id) - }) - - } - - addRoomOwner(roomid, userId) { - return this.RochetChatConnectorService.addRoomOwner(roomid, userId); - } - - createPrivateRoom(groupName, username, customFields) { - return this.RochetChatConnectorService.createPrivateRoom(groupName, username, customFields); - } - - getDmRoom(id): RoomService { - try { - return this.dm[id] - } catch (e) { } - } - - getGroupRoom(id): RoomService { - try { - return this.group[id] - } catch (e) { } - } - - getRoomName(roomData: room): string { - if (this.isIndividual(roomData)) { - const names: String[] = roomData.usernames - - - if (roomData.t == 'd') { - - const username = roomData.usernames.find(e => e != SessionStore.user.UserName) - - try { - const firstName = capitalizeTxt(username.split('.')[0]) - const lastName = capitalizeTxt(username.split('.')[1]) - - return firstName + ' ' + lastName - } catch (error) { - const username = roomData.usernames.find(e => e != SessionStore.user.UserName) - - const firstName = capitalizeTxt(username.split('.')[0]) - return firstName - } - - } else { - if (roomData.t === 'p') { - return 'Loading' - } - else { - return 'Loading' - } - } - - } else { - return roomData.fname - } - } - - getRoomId(roomData: room) { - return roomData._id - } - - getRoomLastMessage(roomData: room): any { - return roomData.lastMessage - } - - private isIndividual(roomData: room) { - return !roomData.fname - } - - getUsers = () => { - return this.users - } - - async getUser() { - - this.loadingUsers = true - let _res - - try { - _res = await this.ChatService.getAllUsers().toPromise(); - } catch (error) { - await this.chatService.refreshtoken(); - _res = await this.ChatService.getAllUsers().toPromise(); - } - - let users: chatUser[] = _res['users'].filter(data => data.username != SessionStore.user.UserName); - - users = users.filter((data) => !(data.name == 'Rocket.Cat' || data.name == 'Administrator')) - - const userIds = this.users.map((user) => user._id) - - for (let UserUpdate of users) { - if (userIds.includes(UserUpdate._id)) { - for (var index = 0; index < this.users.length; index++) { - if (UserUpdate._id == this.users[index]._id) { - this.users[index] = UserUpdate - } - } - } else { - this.users.push(UserUpdate) - } - } - - this.users = this.users.sort((a, b) => { - if (a.name < b.name) { - return -1; - } - if (a.name > b.name) { - return 1; - } - return 0; - }); - - await this.storage.set('Users', this.users); - - this.loadingUsers = false - - } - - getUserOfRoom(roomId) { - return this.RochetChatConnectorService.getUserOfRoom(roomId); - } - - - async createGroup(name) { - const res: any = await this.createPrivateRoom(name, SessionStore.user.UserName, {}); - if (res?.result?.rid) { - try { - await this.getAllRooms(); - } catch (e) { } - return res - } else { - return res - } - } - - - async createGroup__(name, customFields = {}) { - const res: any = await this.createPrivateRoom(name, SessionStore.user.UserName, customFields); - console.log('room is created', res) - if (res?.result?.rid) { - try { - await this.getAllRooms(); - return res - } catch (e) { } - console.log('room is loaded') - return res - } else { - return res - } - } - - getGroupByName(name) { - return this._group.find(e => e.name == name) - } - - async waitRoomToCreate(rid): Promise { - return new Promise(async (resolve, reject) => { - let sub; - - sub = this.onRoomsLoad.subscribe(() => { - const room = this.getRoomById(rid) - if (room) { - resolve(room) - sub.unSubscribe() - } - }) - - try { - await this.getAllRooms(); - } catch (e) { } - - }) - } - - searchContact(name, username) { - return this.users.find(e => e.name == name || e.username == username) - } - -} diff --git a/src/app/services/chat/message.service.spec.ts b/src/app/services/chat/message.service.spec.ts deleted file mode 100644 index 1db761b5e..000000000 --- a/src/app/services/chat/message.service.spec.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { TestBed } from '@angular/core/testing'; - -import { MessageService } from './message.service'; - -describe('MessageService', () => { - let service: MessageService; - - beforeEach(() => { - TestBed.configureTestingModule({}); - service = TestBed.inject(MessageService); - }); - - it('should be created', () => { - expect(service).toBeTruthy(); - }); -}); diff --git a/src/app/services/chat/message.service.ts b/src/app/services/chat/message.service.ts deleted file mode 100644 index bc37ba7cc..000000000 --- a/src/app/services/chat/message.service.ts +++ /dev/null @@ -1,1056 +0,0 @@ -import { Injectable } from '@angular/core'; -import { Message } from 'src/app/models/chatMethod'; -import { SessionStore } from 'src/app/store/session.service'; -import { capitalizeTxt } from 'src/plugin/text'; -import { NfService } from 'src/app/services/chat/nf.service'; -import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service'; -import { showDateDuration } from 'src/plugin/showDateDuration'; -import { showTimeDuration } from 'src/plugin/showTimeDuration'; -import { ChatMethodsService } from './chat-methods.service'; -import { MessageModel, attachments } from '../../models/beast-orm'; -import { AESEncrypt } from '../aesencrypt.service'; -import { HttpEventType } from '@angular/common/http'; -import { AttachmentsService } from 'src/app/services/attachments.service'; -import { NetworkServiceService , ConnectionStatus} from 'src/app/services/network-service.service'; -import { ChatSystemService } from './chat-system.service'; -import { v4 as uuidv4 } from 'uuid' -import { NotificationsService } from 'src/app/services/notifications.service'; - -@Injectable({ - providedIn: 'root' -}) -export class MessageService { - - customFields - channels = [] - mentions = [] - msg = '' - rid = '' - ts = {} - - u = { - name: '', - username: '', - _id: "" - } - - t = '' - _id = '' - id = '' // table id - _updatedAt - file - attachments - displayType = '' - temporaryData: any - hasFile = false - hasSendAttachment = false - sendAttempt = 0 - uploadingFile = false - errorUploadingAttachment = false - loadHistory = false - from: 'Offline'|'History'|'stream'| 'send' - duration = '' - time= ''; - localReference = null - viewed: string[] = [] - received: string[]= [] - addToDb = false - - messageSend = false - delate = false - delateRequest = false - downloadLoader: boolean = false - downloadAttachments = false; - downloadAttachmentsTemp = 0; - UploadAttachmentsTemp = 0; - manualRetry = false - origin: 'history' | 'stream' | 'local' - - messageModelInstance: MessageModel - attachmentsModelData: any - - dateLabel = false - - - constructor( - private NfService: NfService, - private RochetChatConnectorService: RochetChatConnectorService, - private ChatMethodsService: ChatMethodsService, - private AESEncrypt: AESEncrypt, - private AttachmentsService: AttachmentsService, - private NetworkServiceService: NetworkServiceService, - private ChatSystemService: ChatSystemService, - private notificationService: NotificationsService) { - } - - setData({customFields = {}, channels, mentions, msg ,rid ,ts, u, t, _id, id, _updatedAt, file, attachments, temporaryData, localReference = 'out-'+uuidv4() , viewed = [], received = [], delate = false, delateRequest =false, from, sendAttempt = 0, origin, attachmentsModelData, hasFile = false, UploadAttachmentsTemp = 0 }:Message) { - - this.channels = channels || [] - this.mentions = mentions || [] - this.msg = msg || "" - this.rid = rid - this.ts = ts - this.u = u || { name: this.usernameToDisplayName(SessionStore.user.UserName), username: SessionStore.user.UserName, _id: ""} - this.t = t - this._id = _id || "" - this._updatedAt = _updatedAt || new Date().getTime() - this.file = file - this.temporaryData = temporaryData - this.localReference = localReference || null - this.id = id - this.delate = delate - this.delateRequest = delateRequest - this.sendAttempt = 0 - this.origin = origin - this.attachmentsModelData = attachmentsModelData - this.UploadAttachmentsTemp = UploadAttachmentsTemp - - if(this.attachments?.length >= 1 && attachments?.length >= 1) { - this.attachments[0] = Object.assign(this.attachments[0], attachments[0]) - } else { - this.attachments = attachments - } - - this.viewed = [...new Set([...viewed,...this.viewed])]; - this.received = [...new Set([...received,...this.received])]; - - if(!this.ts) { - this.messageSend = false - } else { - this.messageSend = true - } - - this.hasFile = hasFile - - if (this.instanceHasAttachment && !this.hasFile) { - this.hasFile = true - } - - if(this.hasFile) { - if(this.file.type != 'application/webtrix') { - this.displayType = this.file.type.replace('application/','').toUpperCase() - } - } - - if(!this.u.name && this.u.username) { - const user = this.ChatSystemService.users.find((u)=> u.username == this.u.username) - if(user) { - this.u.name = user.name - } else if( this.u.username == SessionStore.user.UserName) { - this.u.name = SessionStore.user.FullName - } else { - } - } - - this.calDateDuration() - this.calTime() - } - - - get offline () { - if(!this._id) { - return true - } - - if(!this.ts) { - return true - } - - return false - } - - /** - * Message is on the server - */ - get online() { - return !this.offline - } - - /** - * if Message is already saved on database - */ - get save() { - return this.id != '' - } - - - private usernameToDisplayName(username) { - - try { - const firstName = capitalizeTxt(username.split('.')[0]) - const lastName = capitalizeTxt(username.split('.')[1]) - return firstName + ' ' + lastName - } catch (error) { - return username - } - - } - - async send(): Promise { - if(this.messageSend) { - return new Promise((resolve, reject) => { - resolve('solve') - }) - } - - this.sendAttempt++; - this.manualRetry = false - - if(!this.hasFile) { - - const params = { - roomId:this.rid, - msg:this.msg, - localReference: this.localReference - } - - await this.sendRequest(params) - - } else { - - let uploadSuccessfully = await this.sendRequestAttachment() - - if(uploadSuccessfully) { - - const params = {roomId:this.rid, msg: this.msg, attachments: this.attachments, file: this.file, localReference: this.localReference} - await this.sendRequest(params) - - } else if(this.RochetChatConnectorService.isLogin == false) { - - this.RochetChatConnectorService.registerCallback({ - type: 'reConnect', - funx: async () => { - console.log('send now have login') - this.send().catch((error) =>{ - console.error(error) - }) - return true - } - }) - - console.log('no login') - - } else if (this.UploadAttachmentsTemp <= 3) { - console.log('temp'+ this.UploadAttachmentsTemp) - setTimeout(async () => { - return await this.send() - }, 4000) - } else if(this.NetworkServiceService.getCurrentNetworkStatus() == ConnectionStatus.Offline) { - - console.log('recooonect') - this.RochetChatConnectorService.registerCallback({ - type: 'reConnect', - funx: async ()=> { - - await this.send().catch((error) => { - console.error(error) - }) - return true - } - }) - } else if (this.NetworkServiceService.getCurrentNetworkStatus() == ConnectionStatus.Online) { - console.log('manual') - this.manualRetry = true - } - - } - - } - - - functionTimer = null; - functionTimer2 = null; - - async sendRequestAttachment() { - - console.log('sendRequestAttachment') - this.uploadingFile = true - - let uploadSuccessfully = false - if(!this.instanceHasAttachmentBase64 && !this.temporaryData) { - try { - await this.getFileFromDB() - } catch (error) {} - } - - if(!this.instanceHasTemporaryData) { - - await this.generateTemporaryData() - } - - console.log('send temp') - if(this.hasSendAttachment == false) { - try { - this.manualRetry = false - this.errorUploadingAttachment = false - this.UploadAttachmentsTemp++ - - uploadSuccessfully = await this.NfService.beforeSendAttachment(this) - - this.uploadingFile = false - this.hasSendAttachment = uploadSuccessfully - - if(this.hasSendAttachment) { - console.log('send uploadSuccessfully') - } else { - console.log('not send uploadSuccessfully') - } - - this.saveChanges() - } catch (error) { - this.uploadingFile = false - - console.log('send not uploadSuccessfully') - this.errorUploadingAttachment = true - - this.saveChanges() - } - - } - - return uploadSuccessfully - } - - sendToRocketChatAttemp = 0 - - async sendRequest(params) { - this.sendToRocketChatAttemp++; - - if(params?.attachments) { - if(params?.attachments[0]?.image_url) { - delete params?.attachments[0]?.image_url - delete params?.file?.image_url - // delete - } - } - - if(this.NetworkServiceService.getCurrentNetworkStatus() == ConnectionStatus.Online) { - - if(this.msg == '') { - if(this.sendAttempt >= 4) { - this.RochetChatConnectorService.send(params).then( - (ChatMessage: any) => { - ChatMessage = ChatMessage.message.result - clearTimeout(this.functionTimer); - - this.redefinedMessage(ChatMessage) - } - ).catch((error) => { - clearTimeout(this.functionTimer); - console.error(error) - }) - } - - } else { - // console.log('online') - - this.RochetChatConnectorService.send(params).then( - (ChatMessage: any) => { - ChatMessage = ChatMessage.message.result - clearTimeout(this.functionTimer); - - this.redefinedMessage(ChatMessage) - - } - ).catch((error) => { - clearTimeout(this.functionTimer); - console.error(error) - }) - } - - this.functionTimer = setTimeout(() => { - //console.log('functionTimer') - - this.RochetChatConnectorService.registerCallback({ - type:'Onmessage', - key:'ping-pong-message', - funx:(message: any) => { - - // clearTimeout(this.functionTimer2); - if(message.msg == "ping") { - this.sendRequest(params) - return true - } - - this.saveChanges() - } - }) - - // this.functionTimer2 = setTimeout(() => { - // console.log('set to callback') - // this.RochetChatConnectorService.registerCallback({ - // type: 'reConnect', - // funx: async ()=> { - // this.sendRequest(params) - - // return true - // } - // }) - // }, 4000) - - this.RochetChatConnectorService.wsSend({message:{msg:"pong"}, loginRequired: false}) - - }, 5000) - - } else { - // console.log('offline') - this.RochetChatConnectorService.registerCallback({ - type: 'reConnect', - funx: async ()=> { - this.send().catch((error) =>{ - console.error(error) - }) - return true - } - }) - } - - } - - async redefinedMessage(ChatMessage , update = true) { - // ChatMessage = this.NfService.fix_updatedAt(ChatMessage) - - // const message = this.getChatObj() - - // this.manualRetry = false - // this.messageSend = true - - // ChatMessage = Object.assign(message, ChatMessage) - // this.setData(ChatMessage) - - // const roomObject = this.ChatSystemService.getRoomById(this.rid) - // const users = roomObject.getUsersByStatus('online') - // for(const user of users) { - // this.addReceived(user._id) - // } - - // if(!roomObject.isGroup) { - // var memeberTosend = this.ChatSystemService.getRoomById(this.rid).membersExcludeMe - // this.notificationService.ChatSendMessageNotification(memeberTosend[0].username,ChatMessage.u.name,ChatMessage.msg || "Anexo",this.rid) - // } else { - // var memeberTosend = this.ChatSystemService.getRoomById(this.rid).membersExcludeMe - // var usersNames = []; - // for(let i = 0; i < memeberTosend.length; i++) { - // usersNames.push(memeberTosend[i].username) - // } - // this.notificationService.ChatSendMessageNotificationGrup(usersNames,ChatMessage.u.name,ChatMessage.msg || "Anexo",this.rid) - // } - - - // await this.saveChanges() - } - - sendNotificaton - - downloadFileMsg() { - - this.downloadLoader = true; - let downloadFile = ""; - let downloadUrl = ""; - - this.AttachmentsService.downloadFile(this.file.guid).subscribe(async (event) => { - - console.log('download file',event) - - if (event.type === HttpEventType.DownloadProgress) { - - } else if (event.type === HttpEventType.Response) { - if (this.file.type == "application/img") { - downloadFile = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), '')); - } else if (this.file.type != "application/img") { - - - downloadFile = btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), '')); - downloadUrl = event.url - console.log('downloaded file', downloadFile) - console.log('event body downloaded file', event.url) - - } - - this.attachments[0] = { - image_url: downloadFile, - name: this.attachments[0].name, - title: this.attachments[0].title, - title_link: downloadFile, - title_link_download: this.attachments[0].title_link_download, - ts: this.attachments[0].ts, - attachmentsUrl: downloadUrl - } - - // save the changes to the storage - this.saveChanges() - this.addFileToDb() - this.downloadLoader = false; - this.downloadAttachments = true - this.downloadAttachmentsTemp++; - } - }, ()=>{ - // error - this.downloadLoader = false; - this.downloadAttachments = false - this.downloadAttachmentsTemp++; - }); - - } - - private calDateDuration(date = null) { - this.duration = showDateDuration(date || this._updatedAt); - } - - private calTime(time = null) { - this.time = showTimeDuration(time || this._updatedAt); - } - - - async delateStatusFalse() { - this.delate = true - this.saveChanges() - } - - addViewed(id: string) { - if(this.messageOwner()) { - let found = this.viewed.find((UserId) => UserId == id) - - if(!found) { - this.viewed.push(id) - return true - } - } - - return false - } - - addReceived(id: string) { - if(this.messageOwner()) { - let found = this.received.find((UserId) => UserId == id) - - if(!found) { - this.received.push(id) - return true - } - } - return false - } - - async delateDB() { - - if(!this.messageModelInstance) { - this.messageModelInstance = await this.getRowInstance() - } - - await this.messageModelInstance.delete() - } - - - isSenderIsNotMe(ChatMessage) { - return SessionStore.user.ChatData.data.userId != ChatMessage.u._id - } - - messageOwner() { - return SessionStore.user.ChatData.data.userId == this.u._id - } - - getChatObj() { - return { - channels: this.channels, - mentions: this.mentions, - // msg: this.AESEncrypt.encrypt(this.msg, SessionStore.user.UserName), - sendAttempt: this.sendAttempt, - msg:this.msg, - rid: this.rid, - ts: this.ts, - u: this.u, - _id: this._id, - t: this.t, - id: this.id, - hasFile: this.hasFile, - origin: this.origin, - _updatedAt: this._updatedAt, - messageSend: this.messageSend, - offline: this.offline, - viewed: this.viewed, - received: this.received, - localReference: this.localReference, - attachments: this.attachments, - file: this.file, - delate: this.delate, - UploadAttachmentsTemp: this.UploadAttachmentsTemp - } - } - - earlySave = false - - async addMessageDB() { - if(!this.addToDb && this.save) { - this.addToDb = true - const message = this.getChatObj() - - if(this.instanceHasAttachment) { - this.hasFile = true - } - - delete message.id - const createdMessage = await MessageModel.create(message) - - if(this.instanceHasAttachment) { - this.addFileToDb() - } - - this.messageModelInstance = createdMessage - this.id = createdMessage.id - - if(this.earlySave) { - this.saveChanges(); - } - } - } - - async addFileToDb() { - - if(!this.messageModelInstance) { - this.messageModelInstance = await this.getRowInstance() - } - - - const createdMessage: any = this.messageModelInstance - try { - - let file = {} - - if(this.attachmentsModelData) { - file = {image_url: this.attachmentsModelData?.fileBase64} - } - - await attachments.create({messageId: createdMessage.id, attachments: this.attachments, file: Object.assign(this.file, file) }) - } catch (error) { - console.log(error) - } - } - - async getFileFromDB() { - - if(!this.messageModelInstance) { - this.messageModelInstance = await this.getRowInstance() - } - - - const data = await this.messageModelInstance.getAttachments() - - console.log('data', data); - - this.attachments = data.attachments - this.file = data.file - } - - async generateTemporaryData () { - const blob: any = await this.base64StringToBlob(this.file.image_url) - - const formData = new FormData(); - formData.append("blobFile", blob); - this.temporaryData = formData - } - - - get instanceHasAttachment() { - if (this.file) { - if(this.file.type) { - if(typeof(this.file.type) == 'string') { - return true - } - } - } - - return false - } - - get instanceHasAttachmentBase64() { - if (this.file) { - if(this.file.type) { - if(this.file?.image_url) { - return true - } - } - } - - return false - } - - get instanceHasTemporaryData() { - if (!this.temporaryData) { - return false - } - - return true - } - - - base64StringToBlob(base64Data) { - return new Promise((resolve, reject) => { - - fetch(base64Data) - .then(res => resolve(res.blob())) - .then(console.log) - - }) - } - - - - async getRowInstance () { - - if(this.save) { - const message = this.getChatObj() - let a - - if(!message.id) { - delete message.id - } - - if (this.localReference) { - a = await MessageModel.get({localReference: this.localReference}) - } else if (this._id) { - a = await MessageModel.get({_id: this._id}) - } else if(this.id) { - a = await MessageModel.get({id: this.id}) - } - - return a - } - - } - - async saveChanges() { - - if(!this.messageModelInstance) { - this.messageModelInstance = await this.getRowInstance() - } - - if(this.save && this.messageModelInstance) { - const message = this.getChatObj() - - if(!message.id) { - delete message.id - } - - for( const [name, value] of Object.entries(message)) { - try { - this.messageModelInstance[name] = value - } catch (error) {} - } - - await this.messageModelInstance.save() - - } else { - this.earlySave = true - } - - } - - decryptMessage() { - try { - // this.msg = this.AESEncrypt.decrypt(this.msg, SessionStore.user.UserName) - } catch (error) {} - } - - - - UIdata() { - this.incomingFromCurrentUser = this.u.username!= SessionStore.user.UserName - this.hasMessage = this.msg !='' - } - - incomingFromCurrentUser = false - hasMessage = false -} - - - - - - -export class MessageServiceDateLabel { - - customFields - channels = [] - mentions = [] - msg = '' - rid = '' - ts = {} - - u = { - name: '', - username: '', - _id: "" - } - - t = '' - _id = '' - id = '' // table id - _updatedAt - file - attachments - displayType = '' - temporaryData: any - hasFile = false - hasSendAttachment = false - sendAttempt = 0 - uploadingFile = false - errorUploadingAttachment = false - loadHistory = false - from: 'Offline'|'History'|'stream'| 'send' - duration = '' - time = '' - localReference = null - viewed: string[] = [] - received: string[]= [] - addToDb = false - - messageSend = false - delate = false - delateRequest = false - downloadLoader: boolean = false - downloadAttachments = false; - downloadAttachmentsTemp = 0; - UploadAttachmentsTemp = 0; - manualRetry = false - origin: 'history' | 'stream' | 'local' - - messageModelInstance: MessageModel - attachmentsModelData: any - ChatSystemService - dateLabel = false - - - constructor() {} - - setData({customFields = {}, channels, mentions, msg ,rid ,ts, u, t, _id, id, _updatedAt, file, attachments, temporaryData, localReference = 'out-'+uuidv4() , viewed = [], received = [], delate = false, delateRequest =false, from, sendAttempt = 0, origin, attachmentsModelData, hasFile = false, UploadAttachmentsTemp = 0 }:Message) { - - this.channels = [] - this.mentions = [] - this.rid = rid - this.ts = ts - this.u = u || { name: this.usernameToDisplayName(SessionStore.user.UserName), username: SessionStore.user.UserName, _id: ""} - this.t = t - this._id = "" - this._updatedAt = _updatedAt || new Date().getTime() - this.file = file - this.temporaryData = temporaryData - this.localReference = localReference || null - this.id = id - this.delate = delate - this.delateRequest = delateRequest - this.sendAttempt = 0 - this.origin = origin - this.attachmentsModelData = attachmentsModelData - this.UploadAttachmentsTemp = UploadAttachmentsTemp - - if(this.attachments?.length >= 1 && attachments?.length >= 1) { - this.attachments[0] = Object.assign(this.attachments[0], attachments[0]) - } else { - this.attachments = attachments - } - - this.viewed = []; - this.received = []; - - this.messageSend = true - this.hasFile = hasFile - - this.hasFile = false - - if(!this.u.name && this.u.username) { - const user = this.ChatSystemService.users.find((u)=> u.username == this.u.username) - if(user) { - this.u.name = user.name - } else if( this.u.username == SessionStore.user.UserName) { - this.u.name = SessionStore.user.FullName - } else { - } - } - - this.calDateDuration() - this.calTime(); - } - - - get offline () { - if(!this._id) { - return true - } - - if(!this.ts) { - return true - } - - return false - } - - /** - * Message is on the server - */ - get online() { - return !this.offline - } - - /** - * if Message is already saved on database - */ - get save() { - return this.id != '' - } - - - private usernameToDisplayName(username) { - - try { - const firstName = capitalizeTxt(username.split('.')[0]) - const lastName = capitalizeTxt(username.split('.')[1]) - return firstName + ' ' + lastName - } catch (error) { - return username - } - - } - - async send(): Promise { - - - } - - - functionTimer = null; - - async sendRequestAttachment() { - - } - - async sendRequest(params) { - - - } - - async redefinedMessage(ChatMessage , update = true) { - - } - - sendNotificaton - - downloadFileMsg() { - - } - - private calDateDuration(date = null) { - this.duration = showDateDuration(date || this._updatedAt); - } - - private calTime(time = null) { - this.time = showTimeDuration(time || this._updatedAt); - } - - - async delateStatusFalse() { - - } - - addViewed(id: string) { - - } - - addReceived(id: string) { - - } - - async delateDB() { - - } - - - isSenderIsNotMe(ChatMessage) { - return SessionStore.user.ChatData.data.userId != ChatMessage.u._id - } - - messageOwner() { - return SessionStore.user.ChatData.data.userId == this.u._id - } - - getChatObj() { - - } - - earlySave = false - - async addMessageDB() { - - } - - async addFileToDb() { - - - } - - async getFileFromDB() { - - } - - async generateTemporaryData () { - - } - - - get instanceHasAttachment() { - return false - } - - get instanceHasAttachmentBase64() { - if (this.file) { - if(this.file.type) { - if(this.file?.image_url) { - return true - } - } - } - - return false - } - - get instanceHasTemporaryData() { - if (!this.temporaryData) { - return false - } - - return true - } - - - base64StringToBlob(base64Data) { - - } - - - - async getRowInstance () { - - - } - - async saveChanges() { - - - } - - decryptMessage() { - try { - // this.msg = this.AESEncrypt.decrypt(this.msg, SessionStore.user.UserName) - } catch (error) {} - } - - - - UIdata() { - this.incomingFromCurrentUser = this.u.username!= SessionStore.user.UserName - this.hasMessage = this.msg !='' - } - - incomingFromCurrentUser = false - hasMessage = false -} diff --git a/src/app/services/chat/nf.service.spec.ts b/src/app/services/chat/nf.service.spec.ts deleted file mode 100644 index b8546cad7..000000000 --- a/src/app/services/chat/nf.service.spec.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { TestBed } from '@angular/core/testing'; - -import { NfService } from './nf.service'; - -describe('NfService', () => { - let service: NfService; - - beforeEach(() => { - TestBed.configureTestingModule({}); - service = TestBed.inject(NfService); - }); - - it('should be created', () => { - expect(service).toBeTruthy(); - }); -}); diff --git a/src/app/services/chat/nf.service.ts b/src/app/services/chat/nf.service.ts deleted file mode 100644 index 78719b0c2..000000000 --- a/src/app/services/chat/nf.service.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { Injectable } from '@angular/core'; -import { MessageService } from './message.service'; -import { RoomService } from './room.service'; - -@Injectable({ - providedIn: 'root' -}) -export class NfService { - - beforeSendAttachment = async (message: MessageService, room?: RoomService): Promise => new Promise ((resolve, reject)=> (resolve(true))); - downloadFileMsg = async (message: MessageService, room?: RoomService): Promise => new Promise ((resolve, reject)=> (resolve(true))); - - fix_updatedAt(message) { - if (message?.result) { - message.result._updatedAt = message.result._updatedAt['$date'] - } else if(message?._updatedAt) { - if(message._updatedAt.hasOwnProperty('$date')) { - message._updatedAt = message._updatedAt['$date'] - } - } - return message - } - - constructor() { } -} diff --git a/src/app/services/chat/rochet-chat-connector.service.spec.ts b/src/app/services/chat/rochet-chat-connector.service.spec.ts deleted file mode 100644 index 0535e9dfe..000000000 --- a/src/app/services/chat/rochet-chat-connector.service.spec.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { TestBed } from '@angular/core/testing'; - -import { RochetChatConnectorService } from './rochet-chat-connector.service'; - -describe('RochetChatConnectorService', () => { - let service: RochetChatConnectorService; - - beforeEach(() => { - TestBed.configureTestingModule({}); - service = TestBed.inject(RochetChatConnectorService); - }); - - it('should be created', () => { - expect(service).toBeTruthy(); - }); -}); diff --git a/src/app/services/chat/rochet-chat-connector.service.ts b/src/app/services/chat/rochet-chat-connector.service.ts deleted file mode 100644 index f71c0c0be..000000000 --- a/src/app/services/chat/rochet-chat-connector.service.ts +++ /dev/null @@ -1,961 +0,0 @@ -import { Injectable } from '@angular/core'; -import { v4 as uuidv4 } from 'uuid' -import { wsCallbacksParams, msgQueue, send } from 'src/app/models/rochet-chat-cliente-service' -import { deepFind } from 'src/plugin/deep' -import { environment } from 'src/environments/environment'; -import { SessionStore } from 'src/app/store/session.service'; -import { chatHistory, Rooms } from 'src/app/models/chatMethod'; -import { BackgroundService } from '../background.service'; - -@Injectable({ - providedIn: 'root' -}) -export class RochetChatConnectorService { - - isLogin = false; - loginResponse = {} - - constructor(private backgroundservice: BackgroundService,) { - } - - reConnect() { - - } - - connect() { - // dont connect if is already connected - if (this.ws.connected == true) { - return false - } - - this.ws.connect(); - - const message = { - msg: "connect", - version: "1", - support: ["1"] - } - this.ws.send({ message, loginRequired: false, requestId: 'connectMessage' }) - this.ws.send({ message: { msg: "pong" }, loginRequired: false, requestId: 'connectPong' }) - - this.ws.registerCallback({ - type: 'Onmessage', - key: 'ping-pong', - funx: (message: any) => { - if (message.msg == "ping") { - this.ws.send({ message: { msg: "pong" }, loginRequired: false }) - } - } - }) - - } - - wsSend({ message, requestId = uuidv4(), loginRequired = true }: send) { - // this.ws.send({ message: { msg: "pong" }, loginRequired: false }) - } - - login() { - // dont login if is already login - if (this.isLogin == true) { - return new Promise((resolve, reject) => { - resolve(this.loginResponse) - }) - } - - const requestId = uuidv4() - // - const message = { - msg: "method", - method: "login", - id: requestId, - params: [ - { - user: { email: SessionStore.user.Email }, - password: SessionStore.user.Password - } - ] - } - this.ws.send({ message, requestId: 'login', loginRequired: false }) - - - return new Promise((resolve, reject) => { - // - this.ws.registerCallback({ - type: 'Onmessage', funx: (message) => { - // - if (message.id == requestId) { // same request send - // - // - if (message.result) { - if (message.result.token) { - this.isLogin = true - this.loginResponse = message - - setTimeout(() => { - this.ws.wsMsgQueue() - }, 10) - - resolve(message) - // - } - } else { - this.isLogin = false - // - reject(message) - } - - reject(message) - - return true - } - } - }) - }); - - } - - getRooms(roomOlder = 1480377601) { - - - //const requestId = uuidv4() - const requestId = uuidv4() - const message = { - "msg": "method", - "method": "rooms/get", - "id": requestId, - "params": [{ "$date": 1480377601 }] - } - - this.ws.send({ message, requestId }) - - return new Promise((resolve, reject) => { - this.ws.registerCallback({ - type: 'Onmessage', funx: (message) => { - if (message.id == requestId) { // same request send - resolve(message) - return true - } - } - }) - }); - } - - readMessage(roomId) { - - //const requestId = uuidv4() - const requestId = uuidv4() - - const message = { - "msg": "method", - "method": "readMessages", - "params": [roomId, []], - "id": requestId - } - - this.ws.send({ message, requestId }) - - return new Promise((resolve, reject) => { - this.ws.registerCallback({ - type: 'Onmessage', funx: (message) => { - if (message.id == requestId) { // same request send - resolve(message) - return true - } - } - }) - }); - - } - - getUserOfRoom(roomId) { - - //const requestId = uuidv4() - const requestId = uuidv4() - - const message = { - "msg": "method", - "method": "getUsersOfRoom", - "id": requestId, - "params": [ - roomId, - false, - { - "limit": 100, - "skip": 0 - }] - } - - this.ws.send({ message, requestId }) - - return new Promise((resolve, reject) => { - this.ws.registerCallback({ - type: 'Onmessage', funx: (message) => { - if (message.id == requestId) { // same request send - resolve(message) - return true - } - } - }) - }); - } - - logout() { - this.isLogin = false - this.ws.connected = false - this.ws.disconnect() - } - - // send message to room - send({ roomId, msg, attachments = null, file = null, localReference = null }) { - - //const requestId = uuidv4() - const requestId = uuidv4() - var message = { - msg: "method", - method: "sendMessage", - id: requestId, - params: [{ - rid: roomId, - localReference: localReference, - msg: msg, - attachments, - file - }] - } - - // - - // this.ws.send({ message, requestId }); - - return new Promise((resolve, reject) => { - this.ws.registerCallback({ - type: 'Onmessage', funx: (message) => { - if (message.id == requestId) { // same request send - resolve({ message, requestId }) - return true - } - } - }) - }); - } - - updateMessage(messageObject) { - - //const requestId = uuidv4() - const requestId = uuidv4() - var message = { - msg: "method", - method: "updateMessage", - id: requestId, - params: [messageObject] - } - - this.ws.send({ message, requestId }); - - return new Promise((resolve, reject) => { - this.ws.registerCallback({ - type: 'Onmessage', funx: (message) => { - if (message.id == requestId) { // same request send - resolve({ message, requestId }) - return true - } - } - }) - }) - - } - - leaveRoom(roomId) { - - const requestId = uuidv4() - - var message = { - msg: "method", - method: "leaveRoom", - id: requestId, - params: [ - roomId, - ] - } - - this.ws.send({ message, requestId }); - - return new Promise((resolve, reject) => { - this.ws.registerCallback({ - type: 'Onmessage', funx: (message) => { - if (message.id == requestId) { // same request send - resolve(message) - return true - } - } - }) - }); - } - - addRoomOwner(roomId, userId) { - - const requestId = uuidv4() - - var message = { - msg: "method", - method: "addRoomOwner", - id: requestId, - params: [ - roomId, - userId - ] - } - - this.ws.send({ message, requestId }); - - return new Promise((resolve, reject) => { - this.ws.registerCallback({ - type: 'Onmessage', funx: (message) => { - if (message.id == requestId) { // same request send - resolve(message) - return true - } - } - }) - }); - } - - hidingRoom(roomId) { - - const requestId = uuidv4() - - var message = { - msg: "method", - method: "hideRoom", - id: requestId, - params: [roomId] - } - - this.ws.send({ message, requestId }); - - return new Promise((resolve, reject) => { - this.ws.registerCallback({ - type: 'Onmessage', funx: (message) => { - if (message.id == requestId) { // same request send - resolve(message) - // - - return true - } - } - }) - }); - } - - joinRoom() { } - - deleteMessage(msgId) { - //const requestId = uuidv4(); - const requestId = uuidv4() - var message = { - msg: "method", - method: "deleteMessage", - id: requestId, - params: [{ "_id": msgId }] - } - - this.ws.send({ message, requestId }); - - return new Promise((resolve, reject) => { - this.ws.registerCallback({ - type: 'Onmessage', funx: (message) => { - if (message.id == requestId) { - resolve(message) - return true - } - } - }) - }); - } - - createPrivateRoom(groupName, username, customFields) { - const requestId = uuidv4() - - var message = { - msg: "method", - method: "createPrivateGroup", - id: requestId, - params: [ - groupName, - [username], - false, - customFields, - { - "broadcast": false, - "encrypted": false - } - ] - } - - this.ws.send({ message, requestId }); - - return new Promise((resolve, reject) => { - this.ws.registerCallback({ - type: 'Onmessage', funx: (message) => { - if (message.id == requestId) { // same request send - resolve(message) - return true - } - } - }) - }); - } - - sendStreamNotifyRoom(roomId: string, username, event: 'typing', param: any) { - - const requestId = uuidv4() - - let message = { - msg: "method", - method: "stream-notify-room", - id: requestId, - params: [ - `${roomId}/${event}`, - username, - param - ] - }; - - this.ws.send({ message, requestId }) - - return new Promise((resolve, reject) => { - this.ws.registerCallback({ - type: 'Onmessage', funx: (message) => { - if (message.id == requestId) { // same request send - resolve(message) - return true - } - } - }) - }); - - } - - - subStreamNotifyRoom(roomId: string, event: 'typing' | 'deleteMessage' | 'readMessage', param: any) { - - const requestId = uuidv4() - - let message = { - msg: "sub", - id: requestId, - name: "stream-notify-room", - params: [ - `${roomId}/${event}`, - param - ] - } - - - this.ws.send({ message, requestId }) - - return new Promise((resolve, reject) => { - this.ws.registerCallback({ - type: 'Onmessage', funx: (message) => { - if (message.id == requestId) { // same request send - resolve(message) - return true - } - - if (message.id == requestId || message?.subs?.[0] == requestId) { // same request send - resolve(message) - return true - } - } - }) - }); - - } - - - subStreamNotifyUser(param?: any) { - - const requestId = uuidv4() - - let message = { - msg: "sub", - id: requestId, - name: "stream-notify-user", - params: [ - `${SessionStore.user.ChatData.data.userId}/notification`, - param - ] - } - - - this.ws.send({ message, requestId }) - - return new Promise((resolve, reject) => { - this.ws.registerCallback({ - type: 'Onmessage', funx: (message) => { - if (message.id == requestId) { // same request send - resolve(message) - return true - } - } - }) - }); - - } - - subStreamMessageUser(param?: any) { - - const requestId = uuidv4() - try { - let message = { - msg: "sub", - id: requestId, - name: "stream-notify-user", - params: [ - `${SessionStore.user.ChatData.data.userId}/message`, - param - ] - } - - - this.ws.send({ message, requestId }) - - return new Promise((resolve, reject) => { - this.ws.registerCallback({ - type: 'Onmessage', funx: (message) => { - if (message.id == requestId) { // same request send - resolve(message) - return true - } - } - }) - }); - } catch (error) { - throw (SessionStore) - } - } - - receiveStreamNotifyRoom(funx: Function) { - - this.ws.registerCallback({ - type: 'Onmessage', - funx: (message) => { - if (message.collection == "stream-notify-room" && message.msg == 'changed') { - funx(message) - } - } - }) - } - - - getUserStatus(funx: Function) { - this.ws.registerCallback({ - type: 'Onmessage', - funx: (message) => { - if (message.msg == 'changed' && message.collection == "stream-notify-logged") { - funx(message) - } - } - }) - } - - - loadHistory(roomId, limit: number = 50) { - - const requestId = uuidv4() - - const message = { - msg: "method", - method: "loadHistory", - id: requestId, - params: [ - roomId, - null, - limit, - { - "$date": 1480377601 - } - ] - } - - this.ws.send({ message, requestId: 'loadHistory' }) - - return new Promise((resolve, reject) => { - this.ws.registerCallback({ - type: 'Onmessage', funx: (message) => { - // - if (message.id == requestId) { // same request send - resolve(message) - return true - } - } - }) - }); - } - - - loadHistoryUnread(roomId, limit: number = 50) { - - const requestId = uuidv4() - - const message = { - msg: "method", - method: "loadHistory", - id: requestId, - params: [ - roomId, - null, - limit, - { - "$date": 1480377601 - } - ] - } - - this.ws.send({ message, requestId: 'loadHistory' }) - - return new Promise((resolve, reject) => { - this.ws.registerCallback({ - type: 'Onmessage', funx: (message) => { - // - if (message.id == requestId) { // same request send - resolve(message) - return true - } - } - }) - }); - } - - setStatus(status: 'online' | 'busy' | 'away' | 'offline') { - - const requestId = uuidv4() - - const message = { - - msg: "method", - method: `UserPresence:setDefaultStatus`, - id: requestId, - params: [status] - - } - - this.ws.send({ message, requestId }) - - } - - subscribeNotifyRoom(roomId: string) { - - const requestId = uuidv4() - - var message = { - "msg": "sub", - "id": requestId, - "name": "stream-notify-room", - "params": [ - `${roomId}/event`, - false - ] - } - - this.ws.send({ message, requestId }); - - return new Promise((resolve, reject) => { - this.ws.registerCallback({ - type: 'Onmessage', funx: (message) => { - if (message.msg == 'ready' || deepFind(message, 'subs.0') == requestId) { // same request send - resolve(message) - return true - } - } - }) - }); - - } - - updateRoomEventss(roomId, collection: string, funx: Function,) { - - this.ws.registerCallback({ - type: 'Onmessage', - funx: (message) => { - // - - if (message.msg == 'changed' && message.collection == collection) { - if (message.fields.args[0].rid == roomId) { - funx(message) - } - else if (message.fields.eventName == `${roomId}/deleteMessage`) { - funx(message) - } - } - } - }) - } - - streamRoomMessages(roomId: string) { - - const requestId = "streamRoomMessages" + uuidv4() - - const message = { - "msg": "sub", - "id": requestId, - "name": "stream-room-messages", - "params": [ - `${roomId}`, - false - ] - } - - this.ws.send({ message, requestId }); - - return new Promise((resolve, reject) => { - this.ws.registerCallback({ - type: 'Onmessage', funx: (message) => { - - - if (message.id == requestId || message?.subs?.[0] == requestId) { // same request send - resolve(message) - return true - } - } - }) - }); - } - - streamNotifyLogged() { - - const requestId = uuidv4() - - const message = { - "msg": "sub", - "id": requestId, - "name": "stream-notify-logged", - "params": [ - "user-status", - false - ] - } - - this.ws.send({ message, requestId }); - - return new Promise((resolve, reject) => { - this.ws.registerCallback({ - type: 'Onmessage', funx: (message) => { - if (message.id == requestId) { // same request send - resolve(message) - return true - } - } - }) - }); - } - - streamNotifyRoom(roomId: string) { - - const requestId = uuidv4() - - let message = { - "msg": "method", - "method": "stream-notify-room", - "id": requestId, - "params": [ - `null/typing`, - "paulo.pinto", - true - ] - }; - - this.ws.send({ message, requestId }) - - return new Promise((resolve, reject) => { - this.ws.registerCallback({ - type: 'Onmessage', funx: (message) => { - if (message.id == requestId) { // same request send - resolve(message) - return true - } - } - }) - }); - - } - - streamNotifyRoomDeleteMessage(roomId: string) { - - const requestId = uuidv4() - - let message = { - "msg": "sub", - "id": requestId, - "name": "stream-notify-room", - "params": [ - `${roomId}/deleteMessage`, - true - ] - }; - - this.ws.send({ message, requestId }) - - return new Promise((resolve, reject) => { - this.ws.registerCallback({ - type: 'Onmessage', funx: (message) => { - if (message.id == requestId) { // same request send - resolve(message) - return true - } - } - }) - }); - - } - - registerCallback(data: wsCallbacksParams) { - return this.ws.registerCallback(data) - } - - // socket class ================================================================== - private socket!: WebSocket; - private wsMsgQueue: { [key: string]: msgQueue } = {} - private wsCallbacks: { [key: string]: wsCallbacksParams } = {} - private wsReconnect = 0 - - private n = 0 - - ws = { - connected: false, - registerCallback: (params: wsCallbacksParams) => { - - let id = params.requestId || params.key || uuidv4() - // - this.wsCallbacks[id] = params - this.n++ - return id - }, - connect: () => { - this.socket = new WebSocket(environment.apiWsChatUrl); - // bind function - this.socket.onopen = this.ws.onopen; - this.socket.onmessage = this.ws.onmessage; - this.socket.onclose = this.ws.onclose; - this.socket.onerror = this.ws.onerror; - - }, - onopen: async () => { - - - - this.ws.connected = true - this.backgroundservice.online(); - - setTimeout(() => { - this.ws.wsMsgQueue() - }, 10) - console.log('rec conect') - - if (this.wsReconnect >= 1) { - for (const [key, value] of Object.entries(this.wsCallbacks)) { - if (value.type == 'reConnect') { - const dontRepeat = await value.funx() - - if (dontRepeat) { - this.n-- - delete this.wsCallbacks[key] - } - - } - - } - } - - this.wsReconnect++; - }, - wsMsgQueue: () => { - - for (const [key, item] of Object.entries(this.wsMsgQueue)) { - - if (item.loginRequired == true && this.isLogin == true) { - // - this.ws.send(item); - delete this.wsMsgQueue[key] - } else if (item.loginRequired == false) { - // - this.ws.send(item); - delete this.wsMsgQueue[key] - } - } - }, - send: ({ message, requestId = uuidv4(), loginRequired = true }: send) => { - - if (this.ws.connected == false || loginRequired == true && this.isLogin == false) { // save data to send when back online - // - // - - this.wsMsgQueue[requestId] = { message, requestId, loginRequired } - } else { - let messageStr = JSON.stringify(message) - this.socket.send(messageStr) - } - return requestId - }, - - onmessage: async (event: any) => { - - this.backgroundservice.online(); - - const data = JSON.parse(event.data) - - for (const [key, value] of Object.entries(this.wsCallbacks)) { - if (value.type == 'Onmessage') { - const dontRepeat = await value.funx(data) - - if (dontRepeat) { - delete this.wsCallbacks[key] - this.n-- - } - - } - - } - - }, - - onclose: async (event: any) => { - this.ws.connected = false - this.isLogin = false - - - this.connect() - this.login() - - for (const [key, value] of Object.entries(this.wsCallbacks)) { - if (value.type == 'Offline') { - const dontRepeat = await value.funx() - - if (dontRepeat) { - delete this.wsCallbacks[key] - this.n-- - } - - } - - } - - - }, - - onerror: (event: any) => { - - }, - disconnect: () => { - - if (this.socket) { - this.socket.onopen = (event: any) => { } - this.socket.onmessage = (event: any) => { } - this.socket.onclose = (event: any) => { } - this.socket.onerror = (event: any) => { } - this.socket.close() - } - } - - } -} diff --git a/src/app/services/chat/room.service.spec.ts b/src/app/services/chat/room.service.spec.ts deleted file mode 100644 index 34729ebbf..000000000 --- a/src/app/services/chat/room.service.spec.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { TestBed } from '@angular/core/testing'; - -import { RoomService } from './room.service'; - -describe('RoomService', () => { - let service: RoomService; - - beforeEach(() => { - TestBed.configureTestingModule({}); - service = TestBed.inject(RoomService); - }); - - it('should be created', () => { - expect(service).toBeTruthy(); - }); -}); diff --git a/src/app/services/chat/room.service.ts b/src/app/services/chat/room.service.ts deleted file mode 100644 index db713cf67..000000000 --- a/src/app/services/chat/room.service.ts +++ /dev/null @@ -1,1299 +0,0 @@ -import { Injectable } from '@angular/core'; -import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service'; -import { MessageService, MessageServiceDateLabel } from 'src/app/services/chat/message.service'; -import { showDateDuration } from 'src/plugin/showDateDuration'; -import { chatHistory } from 'src/app/models/chatMethod'; -import { Storage } from '@ionic/storage'; -import { ModalController, NavController, Platform } from '@ionic/angular'; -import { SqliteService } from 'src/app/services/sqlite.service'; -import { NativeNotificationService } from 'src/app/services/native-notification.service'; -import { SessionStore } from 'src/app/store/session.service'; -import { capitalizeTxt } from 'src/plugin/text' -import { SortService } from '../functions/sort.service'; -import { chatUser } from 'src/app/models/chatMethod'; -import { environment } from 'src/environments/environment'; -import { ChatService } from 'src/app/services/chat.service'; -import { NfService } from 'src/app/services/chat/nf.service'; -import { v4 as uuidv4 } from 'uuid' -import { ChatMethodsService } from './chat-methods.service'; -import { DeleteMessageModel, MessageModel } from '../../models/beast-orm'; -import { AESEncrypt } from '../aesencrypt.service'; -import { IncomingChatMessage, ChatMessageInterface, falseTypingMethod } from 'src/app/models/message.model'; -import { AttachmentsService } from 'src/app/services/attachments.service'; -import { ConnectionStatus, NetworkServiceService } from 'src/app/services/network-service.service'; -import { ChatSystemService } from './chat-system.service'; -import { ViewedMessageService } from './viewed-message.service' -import * as FIFOProcessQueue from 'fifo-process-queue'; -import { NotificationsService } from '../notifications.service'; - -@Injectable({ - providedIn: 'root' -}) -export class RoomService { - - messages: MessageService[] = [] - storageMessage: any[] = []; - lastMessage: MessageService; - messagesBeforeOfflineAPI: MessageService[] = [] - - customFields: any; - id = '' - t = '' - name = '' - _updatedAt = {} - hasLoadHistory = false - DoneLoadingHistory = false - restoreFromOffline = false - duration = '' - isTyping = false - otherUserType = false - lastTimeType = null - message = '' - lastMessageTxt = '' - userThatIsTyping = '' - messagesLocalReference: string[] = [] - members: chatUser[] = [] - membersExcludeMe: chatUser[] = [] - u - sessionStore = SessionStore - countDownTime = '' - chatOpen = false - messageUnread = false - - status = { - receive: { - message: false, - typing: false, - readMessage: false, - deleteMessage: false - } - } - - isGroup: boolean - subscribeAttempt = false - - scrollDown = () => { } - - /** - * @description get user list from ws-chat-methods.service - * @returns chatUser[] - */ - getAllUsers = (): chatUser[] => { - return [] - } - - sortRoomList = () => { } - chatServiceDeleteRoom = (roomId) => { } - - constructor( - public RochetChatConnectorService: RochetChatConnectorService, - private MessageService: MessageService, - private storage: Storage, - private platform: Platform, - private sqlservice: SqliteService, - private NativeNotificationService: NativeNotificationService, - private sortService: SortService, - private chatService: ChatService, - private NfService: NfService, - private ChatMethodsService: ChatMethodsService, - private AESEncrypt: AESEncrypt, - private AttachmentsService: AttachmentsService, - private NetworkServiceService: NetworkServiceService, - private ChatSystemService: ChatSystemService, - private ViewedMessageService: ViewedMessageService, - private notificationService: NotificationsService, - private modalController: ModalController, - private navController: NavController - ) { - /* this.NativeNotificationService.askForPermission() */ - - this.RochetChatConnectorService.getUserStatus((d) => { - - const userId = d.fields.args[0][0] - const statusNum = d.fields.args[0][2] - const statusText = this.statusNumberToText(statusNum) - - this.ViewedMessageService.request(this, userId, statusNum, statusText) - - }) - - this.RochetChatConnectorService.registerCallback({ - type: 'Offline', - funx: () => { - /** - * @description when the phone is in the background for a long time it could disconnects from the socket then the socket reconnects automatically, - * when the connection is lost the subscribe is also lost, so we have to subscribe again when reconnection is establish. - */ - this.resetStatus(); - this.hasLoadHistory = false - this.subscribeAttempt = false - } - }); - - } - - /** - * @description convert rocketchat statues num to readable string - * @param text - * @returns - */ - statusNumberToText(text) { - if (text == '0') { - return "offline" - } - else if (text == '1') { - return "online" - } - else if (text == '2') { - return "away" - } - else if (text == '3') { - return "busy" - } - } - - - resetStatus() { - this.status = { - receive: { - message: false, - typing: false, - readMessage: false, - deleteMessage: false - } - } - } - - setDataOnce = false - setData({ membersExcludeMe, members, u, customFields = {}, id, name, t, lastMessage = new MessageService(this.NfService, this.RochetChatConnectorService, this.ChatMethodsService, this.AESEncrypt, this.AttachmentsService, this.NetworkServiceService, this.ChatSystemService, this.notificationService), _updatedAt }) { - this.customFields = customFields - this.id = id - this.name = name - this.t = t - this.lastMessage = lastMessage - this._updatedAt = _updatedAt - this.u = u - this.calDateDuration(); - - - if (this.customFields?.countDownDate) { - this.countDownDate(this.customFields.countDownDate); - } - - if (this.setDataOnce == false) { - this.setDataOnce = true - this.updateContacts() - } - - } - - updateInfo() { - // this.chatService.getRoomInfo(this.id).toPromise(); - - } - - get online() { - - if (!this.isGroup) { - for (let user of this.ChatSystemService.users) { - - for (const members of this.membersExcludeMe) { - if (members._id == user._id) { - return user.status - } - } - - } - } - - return 'offline' - } - - countDownDate(date) { - let difference = new Date(date).getTime() - new Date().getTime(); - let c_day = Math.floor(difference / (1000 * 60 * 60 * 24)); - let c_hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); - let c_minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60)); - let c_seconds = Math.floor((difference % (1000 * 60)) / 1000); - - this.countDownTime = this.addZero(c_day) + " : " + this.addZero(c_hours) + " : " + this.addZero(c_minutes) + " : " + this.addZero(c_seconds); - - if (difference < 0) { - - this.deleteRoom(); - if(this.chatOpen && window.location.pathname.includes('chat')) { - this.closeModal() - } - - } else { - setTimeout(() => { - this.countDownDate(date) - }, 1000) - } - } - - addZero(i) { - if (i < 10) { - i = "0" + i; - } - return i; - } - - deleteRoom() { - this.countDownTime = "Expired"; - let body = { "roomId": this.id } - - // this.chatService.getRoomInfo(this.id).subscribe( room =>{}); - - if (this.t === 'p') { - this.chatService.deleteGroup(body).subscribe(res => { - this.ChatSystemService.deleteRoom(this.id); - this.ChatSystemService.getAllRooms(); - this.chatServiceDeleteRoom(this.id); - }, (error)=> { - if(error.status != 0) { - this.ChatSystemService.deleteRoom(this.id); - this.ChatSystemService.getAllRooms(); - this.chatServiceDeleteRoom(this.id); - } - }); - } - else { - this.chatService.deleteChannel(body).subscribe(res => { - this.ChatSystemService.deleteRoom(this.id); - this.ChatSystemService.getAllRooms(); - this.chatServiceDeleteRoom(this.id); - }, (error)=> { - if(error.status != 0) { - this.ChatSystemService.deleteRoom(this.id); - this.ChatSystemService.getAllRooms(); - this.chatServiceDeleteRoom(this.id); - } - }); - } - } - - - isSenderIsNotMe(ChatMessage) { - return SessionStore.user.UserName != ChatMessage.u.username - } - - senderId(ChatMessage) { - return ChatMessage.u._id - } - - receiveMessage() { - - this.RochetChatConnectorService.updateRoomEventss( - this.id, - "stream-room-messages", - async (IncomingChatMessage: IncomingChatMessage) => { - - this.appendReceiveMessage.push(IncomingChatMessage) - - } - ) - - this.RochetChatConnectorService.receiveStreamNotifyRoom((message) => { - - if (message.fields.eventName == this.id + '/' + 'typing') { - - const args = message.fields.args - - if (typeof args[1] != 'object') { - this.userThatIsTyping = this.usernameToDisplayName(args[0]) - - const user = args[0] - if (SessionStore.user.UserName != user) { - this.readAllMessage() - this.isTyping = args[1] - this.otherUserType = args[1] - } - - } else if (args[0]?.method == 'viewMessage' || args[1]?.method == 'viewMessage') { - const user = args[0] - - if (SessionStore.user.UserName != user) { - this.readAllMessage() - } - - } else if (args[0]?.method == 'deleteMessage' || args[1]?.method == 'deleteMessage') { - - this.deleteMessage(args[1]?.method?._id) - - } else { - - } - - } else if (message.fields.eventName == this.id + '/' + 'deleteMessage') { } - - }) - } - - appendReceiveMessage = FIFOProcessQueue(async (IncomingChatMessage: IncomingChatMessage, done) => { - - let IncomingChatMessageArgs = IncomingChatMessage.fields.args[0] - let ChatMessage: ChatMessageInterface = this.fix_updatedAt(IncomingChatMessageArgs) - - - let found = this.findMessageBy_id(ChatMessage._id) || - this.findMessageBy_localReference(ChatMessage?.localReference) - // || await this.findMessageInDBByData({_id:ChatMessage._id, localReference:ChatMessage.localReference }) - - if (!found) { - - ChatMessage.origin = 'stream' - const message = await this.prepareCreate({ message: ChatMessage, save: false }); - this.registerSendMessage(message) - - message.from = 'stream' - message.loadHistory = this.DoneLoadingHistory - - this.lastMessage = message; - - try { - this.calDateDuration(ChatMessage._updatedAt); - } catch (error) { - console.log(error) - } - - - if (message.t == 'r') { - this.name = message.msg; - } - - //if (this.isSenderIsNotMe(ChatMessage)) { - /* this.NativeNotificationService.sendNotificationChat({ - message: message.msg, - title: this.name - }); */ - //} - - if (this.hasLoadHistory == true) { - this.messages.push(message) - message.addMessageDB() - } else { - this.messagesBeforeOfflineAPI.push(message) - } - - this.messageUnread = true - setTimeout(() => { - this.scrollDown() - }, 50) - - } - - if (ChatMessage?.t == "au" || ChatMessage?.t == "ru" || ChatMessage?.t == "ul") { - this.updateContacts() - } else if (ChatMessage?.t == "r") { - this.name = ChatMessage.msg - } - - this.sortRoomList() - // this.changeDetector() - setTimeout(() => { - done() - }, 5) - }) - - - async info() { - - // set unread messages - // const response: any = await this.chatService.GetSubscriptionRoomUnreadM(this.id).toPromise() - - // if(response?.subscription?.unread >= 1) { - // this.messageUnread = true - // } - } - - getUsersByStatus(status: 'offline' | 'online') { - - // return this.getAllUsers().filter((user => { - // for (const member of this.membersExcludeMe) { - // if (user._id == member._id && user.status == status) { - // return true - // } - // } - // })) - - } - - getRoomMembersIds(): string[] { - try { - return this.membersExcludeMe.map((user) => user._id) - } catch (error) { - return [] - } - - } - - getAllMemberThatIsNotOffline(): string[] { - - // const membersIds = this.getRoomMembersIds() - // const allChatUsers = this.getAllUsers() - - // const AllMemberThatIsNotOffline = [] - - // for (let user of allChatUsers) { - // if (membersIds.includes(user._id)) { - - // if (user.status != 'offline') { - // AllMemberThatIsNotOffline.push(user._id) - // } - // } - // } - - return [] - } - - getAllMemberThatIsOffline(): string[] { - - // const membersIds = this.getRoomMembersIds() - // const allChatUsers = this.getAllUsers() - - // const AllMemberThatIsNotOffline = [] - - // for (let user of allChatUsers) { - // if (membersIds.includes(user._id)) { - - // if (user.status == 'offline') { - // AllMemberThatIsNotOffline.push(user._id) - // } - // } - // } - - return [] - } - - - async deleteMessageToReceive(userId) { - - const allDeleteMessages = await DeleteMessageModel.filter({ rid: this.id }).execute() - - for (let message_ of allDeleteMessages) { - - if (message_.needToReceiveBy.includes(userId)) { - - message_.needToReceiveBy = message_.needToReceiveBy.filter((e) => e != userId) - this.sendFalseTypingReadMessage('deleteMessage', { _id: message_.messageId }) - - if (message_.needToReceiveBy.length == 0) { - - const deleteMessage = await DeleteMessageModel.get({ messageId: message_.messageId }) - await deleteMessage.delete() - - } else { - await DeleteMessageModel.update(message_) - } - - } - - } - - } - - async receiveMessageDelete() { - - this.RochetChatConnectorService.updateRoomEventss( - this.id, - "stream-notify-room", - async (ChatMessage) => { - const DeletedMessageId = ChatMessage.fields.args[0]._id; - - const message = this.messages.find((e) => e._id == DeletedMessageId) - - if (message) { - if (message.delate == false) { - this.deleteMessage(DeletedMessageId) - } - } else { - const message = await MessageModel.get({ _id: DeletedMessageId }) - if (message) { - (message as MessageModel).delete() - - DeleteMessageModel.create({ - messageId: DeletedMessageId, - rid: this.id, - ts: "", - u: {}, - needToReceiveBy: [] - }) - - } - } - - - } - ) - } - - /** - * @description delete message in the view - * @param id message ID - */ - async deleteMessage(_id) { - - const id = _id - - for (let i = 0; i <= this.messages.length; i++) { - - if (this.messages[i]?._id == id) { - - - if (SessionStore.user.UserName == this.messages[i]?.u?.username) { - const allMemberThatIsOffline = this.getAllMemberThatIsOffline() - - DeleteMessageModel.create({ - messageId: this.messages[i]._id, - rid: this.messages[i].rid, - ts: this.messages[i].ts, - u: this.messages[i].u, - needToReceiveBy: allMemberThatIsOffline - }) - } - - this.messages[i]?.delateDB() - this.messages.splice(i, 1) - - //Get previous last message from room - const previousLastMessage = this.messages.slice(-1)[0]; - - if (previousLastMessage.dateLabel == false) { - if (previousLastMessage) { - this.lastMessage = previousLastMessage; - this.calDateDuration(previousLastMessage._updatedAt) - this.sortRoomList() - } - } else { - const previousLastMessage = this.messages.slice(-2)[0]; - - if (previousLastMessage) { - this.lastMessage = previousLastMessage; - this.calDateDuration(previousLastMessage._updatedAt) - this.sortRoomList() - } - - } - - - - return true - - } else { - // - } - } - - } - - - /** - * @description delete message in the view - * @param id message ID - */ - async deleteMessageFromArray(_id) { - - const id = _id - - for (let i = 0; i <= this.messages.length; i++) { - - if (this.messages[i]?._id == id) { - - this.messages.splice(i, 1) - - return true - - } else { - // - } - } - - } - - - deleteAll() { - this.messages.forEach((message) => { - if (message?._id) { - this.sendDeleteRequest(message._id) - } - }) - } - - async delateMessageToSendToOthers(userId) { - - const deleteMessage = await DeleteMessageModel.all(); - - const toSend = deleteMessage.filter((DeleteMessage: string[]) => !DeleteMessage.includes(userId)) - - } - - - async sendDeleteRequest(msgId) { - - const message = this.messages.find((e) => e._id == msgId) - await message.delateStatusFalse() - - if (this.NetworkServiceService.getCurrentNetworkStatus() == ConnectionStatus.Online) { - - this.RochetChatConnectorService.deleteMessage(msgId).then(async () => { - message.delateRequest = true - await message.saveChanges(); - this.deleteMessage(msgId); - }) - - } else { - this.RochetChatConnectorService.registerCallback({ - type: 'reConnect', - funx: async () => { - - this.sendDeleteRequest(msgId) - return true - } - }) - } - - } - - - /** - * @description sen text message - */ - async send({ file = null, attachments = null, temporaryData = {}, attachmentsModelData = {} }) { - - this.message = this.message.replace(/(\n$)/, '') - - if (file && this.message) { - this.send({}) - } - - const localReference = uuidv4(); - - let offlineChatMessage = { - rid: this.id, - msg: this.message, - attachments, - file, - temporaryData, - localReference, - origin: 'local', - attachmentsModelData - } - - - //console.log('offlineChatMessage', offlineChatMessage) - - this.message = '' - - this.hojeLabel({ ...offlineChatMessage }) - - const message: MessageService = await this.prepareCreate({ message: offlineChatMessage, save: environment.chatOffline }) - this.registerSendMessage(message) - - if (this.hasLoadHistory == true) { - await message.addMessageDB() - } - - message.send() - message.from = 'send' - message.loadHistory = this.hasLoadHistory - - if (environment.chatOffline) { - - setTimeout(() => { - this.scrollDown() - }, 150) - - this.lastMessage = message - this.calDateDuration(message._updatedAt) - this.sortRoomList() - } - } - - - /** - * Register all send message so that - * the incoming message wont be confuse to - * other user the localReference is the identifier - */ - registerSendMessage(message: MessageService) { - this.messagesLocalReference.push(message.localReference) - } - - - localReferenceExist(message: MessageService) { - for (const localReference of this.messagesLocalReference) { - if (localReference == message?.localReference) { - return true - } - } - return false - } - - sendTyping(text: string = this.message) { - - if (this.lastMessageTxt == text) { return false } - this.lastTimeType = new Date().getTime() - - const lastIsTyping = this.isTyping - if (text.length >= 1) { - this.isTyping = true - } else { - this.isTyping = false - } - - if (lastIsTyping != this.isTyping) { - this.RochetChatConnectorService.sendStreamNotifyRoom(this.id, SessionStore.user.UserName, 'typing', this.isTyping).catch((error) => console.error(error)); - } - - this.lastMessageTxt = this.message - this.typingWatch() - } - - sendFalseTypingReadMessage(method, param: object) { - this.RochetChatConnectorService.sendStreamNotifyRoom(this.id, SessionStore.user.UserName, 'typing', { method: method, params: param } as falseTypingMethod).catch((error) => console.error(error)) - this.setTypingOff() - } - - private typingWatch() { - setTimeout(() => { - const now = new Date().getTime() - - if ((now - this.lastTimeType) >= 2888) { - - if (this.isTyping == true) { - this.isTyping = false - this.RochetChatConnectorService.sendStreamNotifyRoom(this.id, SessionStore.user.UserName, 'typing', this.isTyping).catch((error) => console.error(error)) - } - } - - }, 3000) - } - - private setTypingOff() { - this.sendTyping('') - } - - roomLeave() { - this.setTypingOff() - this.chatOpen = false - } - - open() { - // this.typing(this.message) - this.chatOpen = true - this.messageUnread = false - this.sendReadMessage() - } - - - leave(rid?) { - this.RochetChatConnectorService.leaveRoom(this.id).catch((error) => console.error(error)) - } - - isJson(str) { - try { - JSON.parse(str); - } catch (e) { - return ""; - } - return JSON.parse(str); - } - - formatDateToDDMMYYYY(dateStamp) { - const date = new Date(dateStamp); - - const day = date.getDate().toString().padStart(2, '0'); - const month = (date.getMonth() + 1).toString().padStart(2, '0'); // Month is zero-based - const year = date.getFullYear(); - - return `${day}-${month}-${year}`; - } - - sortArrayISODate(messages: any): any[] { - - return messages.sort((a, b) => - new Date(b._updatedAt).getTime() - - - new Date(a._updatedAt).getTime()) - } - - restoreOnce = false - labelDates = [] - - - goshPush(ChatMessage) { - let currentDateMessage = new Date(ChatMessage._updatedAt).toLocaleDateString() - - if (currentDateMessage) { - if (!this.labelDates.find(e => e == currentDateMessage)) { - this.labelDates.push(currentDateMessage) - - const newMessage = this.fix_updatedAt({ ...ChatMessage }) - newMessage.msg = currentDateMessage - const cloneMessage = new MessageServiceDateLabel() - - cloneMessage.ChatSystemService = this.ChatSystemService - cloneMessage.setData({ ...newMessage } as any) - // - cloneMessage._id = "" - cloneMessage._updatedAt = "" - cloneMessage.duration = "" - cloneMessage.msg = currentDateMessage - cloneMessage.dateLabel = true - cloneMessage.delate = false - cloneMessage.file = undefined - cloneMessage.attachments = undefined - - if (new Date().toLocaleDateString() == currentDateMessage) { - - cloneMessage.msg = "hoje" - } else { - cloneMessage.msg = currentDateMessage - } - - this.messages.push(cloneMessage as any) - - // console.log(currentDateMessage) - } - } - } - - async deleteMessageDate(MessageService: MessageService) { - - let currentDateMessageToDelete = new Date(MessageService._updatedAt).toLocaleDateString() - - for (let i = 0; i <= this.messages.length; i++) { - - let currentDateMessage = new Date(this.messages[i]._updatedAt).toLocaleDateString() - - if (currentDateMessageToDelete == currentDateMessage) { - return - } - } - - for (let i = 0; i <= this.messages.length; i++) { - if (this.messages[i].dateLabel) { - if (this.messages[i].msg == currentDateMessageToDelete) { - this.messages.splice(i, 1) - } - } - } - - } - - - hojeLabel(offlineChatMessage: any) { - let currentDateMessage = new Date().toLocaleDateString() - if (!this.labelDates.find(e => e == currentDateMessage)) { - - this.labelDates.push(currentDateMessage) - - const cloneMessage = new MessageServiceDateLabel() - - cloneMessage.ChatSystemService = this.ChatSystemService - cloneMessage.setData({ ...offlineChatMessage } as any) - - cloneMessage.msg = "hoje" - cloneMessage._id = "" - cloneMessage._updatedAt = "" - cloneMessage.duration = "" - cloneMessage.dateLabel = true - cloneMessage.delate = false - cloneMessage.attachments = undefined - cloneMessage.file = undefined - - this.messages.push(cloneMessage as any) - } - } - - async restoreMessageFromDB() { - if (environment.chatOffline && this.restoreOnce == false) { - this.restoreOnce = true - - const messages = this.sortArrayISODate(await MessageModel.filter({ rid: this.id }).execute()).reverse() - - for (let ChatMessage of messages) { - - - this.goshPush(ChatMessage) - - - const wewMessage = await this.simplePrepareMessage(ChatMessage) - - wewMessage.from = 'Offline' - wewMessage.loadHistory = this.hasLoadHistory - wewMessage.messageModelInstance = ChatMessage - - if (wewMessage.offline == false) { - - const message = await this.prepareCreate({ message: ChatMessage }) - - - message.from = 'Offline' - message.loadHistory = this.hasLoadHistory - wewMessage.messageModelInstance = ChatMessage - message?.decryptMessage() - - } else { - - const offlineMessage = await this.prepareCreate({ message: ChatMessage }) - - offlineMessage.from = 'Offline' - offlineMessage.loadHistory = this.hasLoadHistory - wewMessage.messageModelInstance = ChatMessage - this.registerSendMessage(offlineMessage) - offlineMessage?.decryptMessage() - offlineMessage.send() - - } - - if (wewMessage.delate && !wewMessage.offline && !wewMessage.delateRequest) { - this.sendDeleteRequest(wewMessage._id) - } - } - - if (!this.lastMessage) { - this.lastMessage = messages.pop(); - } - - - setTimeout(() => { - this.scrollDown() - }, 50) - } - } - - // runs onces only - loadHistoryCount = 0 - localMessages = [] - async loadHistory({ limit = 1000, forceUpdate = false }) { - - if (forceUpdate == false) { - if (this.hasLoadHistory) { - return false - } - } - - this.hasLoadHistory = true - - await this.restoreMessageFromDB() - const chatHistory: chatHistory = await this.RochetChatConnectorService.loadHistory(this.id, limit) - - this.localMessages = this.messages.map(e => e._id) - - if (Array.isArray(chatHistory?.result?.messages)) { - - const users = this.getUsersByStatus('online') - - if(chatHistory.result.unreadNotLoaded >= 1) { - this.messageUnread = true - } - - for (let message of chatHistory.result.messages.reverse()) { - - message.origin = 'history' - message.from = 'History' - const messagesToSave = await this.prepareMessageCreateIfNotExist({ message: message }); - if (messagesToSave != null) { - - // messagesToSave.received = users.map((user) => user._id) - messagesToSave.addMessageDB() - } - - } - - - for (const message of this.messagesBeforeOfflineAPI) { - const messagesToSave = await this.prepareMessageCreateIfNotExist({ message: message }); - if (messagesToSave != null) { - - // messagesToSave.received = users.map((user) => user._id) - - this.addMessageDB.push(messagesToSave) - } - } - this.messagesBeforeOfflineAPI = [] - - setTimeout(() => { - this.scrollDown() - }, 50) - - } - - this.DoneLoadingHistory = true - - if (chatHistory?.result?.messages) { - - if (!this.lastMessage) { - this.lastMessage = chatHistory?.result?.messages.pop() as any - } - } - - this.deletedMessages(chatHistory) - } - - - deletedMessages(chatHistory: chatHistory) { - - const messagesToDelete = this.localMessages.filter(id => { - const found = chatHistory.result.messages.find(e => { - return e._id == id - }) - if (!found) { - return true - } - - return false - }) - - - for (const id of messagesToDelete) { - if (id != '') { - this.deleteMessage(id) - } - } - } - - addMessageDB = FIFOProcessQueue(async ({ messagesToSave }, callback) => { - - await messagesToSave.addMessageDB() - callback() - }) - - async readAllMessage() { - - this.ViewedMessageService.requestReadAll(this) - - } - - - - async ChatMessageIsPresentInTheView(ChatMessage: ChatMessageInterface) { - let foundIndex; - - const found = this.messages.find((MessageService, index) => { - if (MessageService._id == ChatMessage._id) { - foundIndex = index - return true - } else { - return false - } - }) - - if (foundIndex) { - return { found, foundIndex } - } else { - return false - } - } - - - - - async prepareCreate({ message, save = true }): Promise { - message = this.fix_updatedAt(message) - - const wewMessage = new MessageService(this.NfService, this.RochetChatConnectorService, this.ChatMethodsService, this.AESEncrypt, this.AttachmentsService, this.NetworkServiceService, this.ChatSystemService, this.notificationService) - wewMessage.setData(message) - wewMessage.loadHistory = this.hasLoadHistory - - if (save) { - this.messages.push(wewMessage) - } - - return wewMessage - } - - - simplePrepareMessage(message) { - message = this.fix_updatedAt(message) - const wewMessage = new MessageService(this.NfService, this.RochetChatConnectorService, this.ChatMethodsService, this.AESEncrypt, this.AttachmentsService, this.NetworkServiceService, this.ChatSystemService, this.notificationService) - wewMessage.setData(message) - wewMessage.loadHistory = this.hasLoadHistory - - return wewMessage - } - - - private findMessageBy_id(id) { - for (let m of this.messages) { - if (m?._id == id) { - return true - } - } - - return false - } - - private findMessageBy_localReference(localReference) { - for (let m of this.messages) { - if (m?.localReference == localReference) { - return true - } - } - - return false - } - - private async findMessageInDBByLocalReference({ localReference }) { - const a = await MessageModel.get({ localReference: localReference }) - - return typeof a.id == 'number' - } - - private async findMessageInDBByLocalId({ _id }) { - const a = await MessageModel.get({ _id: _id }) - return typeof a.id == 'number' - } - - private async findMessageInDBByData({ localReference, _id }) { - - const a = await MessageModel.filter({ localReference: localReference }).execute() - if (a.length >= 1) { - - return true - } - - const c = await MessageModel.filter({ _id: _id }).execute() - if (c.length >= 1) { - - return true - } - - - return false - } - - async prepareMessageCreateIfNotExist({ message }) { - message = this.fix_updatedAt(message) - - let found = await this.findMessageBy_id(message._id) || await this.findMessageBy_localReference(message.localReference) - // || await this.findMessageInDBByData({_id:message._id, localReference:message.localReference }) - - if (!found) { - const wewMessage = this.simplePrepareMessage(message) - this.goshPush(wewMessage) - this.messages.push(wewMessage) - return wewMessage - } else { - return null - } - } - - private calDateDuration(date = null) { - this.duration = showDateDuration(date || this._updatedAt); - this._updatedAt = date || this._updatedAt - } - - private fix_updatedAt(message): ChatMessageInterface { - if (message?.result) { - message.result._updatedAt = message.result._updatedAt['$date'] - } else if (message?._updatedAt) { - if (message._updatedAt.hasOwnProperty('$date')) { - message._updatedAt = message._updatedAt['$date'] - } - } - return message - } - - usernameToDisplayName(username) { - - try { - const firstName = capitalizeTxt(username.split('.')[0]) - const lastName = capitalizeTxt(username.split('.')[1]) - return firstName + ' ' + lastName - } catch (error) { - return username - } - - } - - sendReadMessage() { - this.RochetChatConnectorService.readMessage(this.id).catch((error) => { - console.error(error) - }) - this.sendFalseTypingReadMessage('viewMessage', {}) - this.messageUnread = false - } - - async addContacts(userId: any) { - - let body = { - "roomId": this.id, - "userId": userId, - } - - await this.chatService.addUserToGroup(body).toPromise(); - this.ChatSystemService.getGroupRoom(this.id).updateContacts() - } - - - async updateContacts() { - - // let res - // let error = false - - // if (this.t == 'd') { - - // try { - // res = await this.chatService.getMembers(this.id).toPromise(); - // } catch (e) { - // await this.chatService.refreshtoken(); - // error = true - // } - - // if (error) { - // res = await this.chatService.getMembers(this.id).toPromise(); - // } - - // } else { - // if (this.t === 'p') { - - // try { - // res = await this.chatService.getGroupMembers(this.id).toPromise() - // } catch (e) { - // await this.chatService.refreshtoken(); - // error = true - // } - - // if (error) { - // res = await this.chatService.getGroupMembers(this.id).toPromise() - // } - - - // setTimeout(() => { - // // console.log("getGroupMembers", this.membersExcludeMe) - // }, 500) - - // } - // else { - - // try { - // res = await this.chatService.getChannelMembers(this.id).toPromise() - - // } catch (e) { - // await this.chatService.refreshtoken(); - // error = true - // } - - // if (error) { - // res = await this.chatService.getChannelMembers(this.id).toPromise() - // } - - // setTimeout(() => { - // console.log("getChannelMembers", this.membersExcludeMe) - // }, 500) - // } - // } - - // const members = res['members']; - // const users = members.filter(data => data.username != this.sessionStore.user.UserName); - // this.members = members - // this.membersExcludeMe = users - } - - async closeModal() { - await this.modalController.dismiss(); - } -} diff --git a/src/app/services/chat/viewed-message.service.spec.ts b/src/app/services/chat/viewed-message.service.spec.ts deleted file mode 100644 index 1b74bcccf..000000000 --- a/src/app/services/chat/viewed-message.service.spec.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { TestBed } from '@angular/core/testing'; - -import { ViewedMessageService } from './viewed-message.service'; - -describe('ViewedMessageService', () => { - let service: ViewedMessageService; - - beforeEach(() => { - TestBed.configureTestingModule({}); - service = TestBed.inject(ViewedMessageService); - }); - - it('should be created', () => { - expect(service).toBeTruthy(); - }); -}); diff --git a/src/app/services/chat/viewed-message.service.ts b/src/app/services/chat/viewed-message.service.ts deleted file mode 100644 index 9411d766d..000000000 --- a/src/app/services/chat/viewed-message.service.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { Injectable } from '@angular/core'; -import * as FIFOProcessQueue from 'fifo-process-queue'; -import { RoomService } from './room.service'; - -@Injectable({ - providedIn: 'root' -}) -export class ViewedMessageService { - - constructor() { - } - - viewQueue = FIFOProcessQueue(async ({room, userId, statusNum, statusText}, callback) => { - - if(room.membersExcludeMe?.map) { - const membersIds = room.membersExcludeMe.map((user)=> user._id) - - if(membersIds.includes(userId)) { - - if(statusText != 'offline') { - room.deleteMessageToReceive(userId) - } - - let n = 0 - for (const message of room.messages) { - if(message.online) { - for(let id of membersIds) { - if(message.addReceived(id)) { - n++ - // setTimeout(async() => { - await message.saveChanges() - // }, 100 * n) - } - } - } - } - - setTimeout(function () { - callback(); - }, 100); - } - } - - }) - - - viewReadQueue = FIFOProcessQueue(async ({room}, callback) => { - - const membersIds: string[] = room.membersExcludeMe.map((user)=> user._id) - - let n = 0 - for (const message of room.messages) { - if(message.online) { - for(let id of membersIds) { - - if(message.addViewed(id)) { - message.addReceived(id) - n++ - // setTimeout(async() => { - await message.saveChanges() - // }, 100 * n) - - } - } - } - } - - setTimeout(() => { - callback() - },100) - - }) - - request(room:RoomService, userId, statusNum, statusText) { - this.viewQueue.push({room, userId, statusNum, statusText}) - } - - requestReadAll(room:RoomService) { - this.viewReadQueue.push({room}) - } -} diff --git a/src/app/services/functions/file.service.ts b/src/app/services/functions/file.service.ts index d7295d49e..3c0952420 100644 --- a/src/app/services/functions/file.service.ts +++ b/src/app/services/functions/file.service.ts @@ -78,12 +78,12 @@ export class FileService { path: IMAGE_DIR, directory: Directory.Data, }).then(result => { - + let lastphoto = result.files[result.files.length - 1] resolve(lastphoto) }, async (err) => { - + reject('ERROR FILE DOSENT EXIST') // Folder does not yet exists! await Filesystem.mkdir({ @@ -127,7 +127,7 @@ export class FileService { //new method 4 async loadFileData(fileName: string) { - + // for (let f of fileNames) { const filePath = `${IMAGE_DIR}/${fileName}`; @@ -139,7 +139,7 @@ export class FileService { data: `data:image/jpeg;base64,${readFile.data}`, }; - + const capturedImage = image.data @@ -150,9 +150,7 @@ export class FileService { } - - - getFileFromDevice(types: typeof FileType[]) { + getFileFromDevice(types: typeof FileType[]): Promise { const input = this.fileLoaderService.createInput({ accept: types }) @@ -168,9 +166,6 @@ export class FileService { } - - - getFileFromDeviceBase64(types: typeof FileType[]) { const input = this.fileLoaderService.createInput({ accept: types @@ -199,7 +194,7 @@ export class FileService { }) } - + viewDocumentByUrl(url) { const browser = this.iab.create(url,"_parent"); @@ -254,8 +249,8 @@ export class FileService { dataURLtoFile(dataurl, filename) { var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], - bstr = atob(arr[arr.length - 1]), - n = bstr.length, + bstr = atob(arr[arr.length - 1]), + n = bstr.length, u8arr = new Uint8Array(n); while(n--){ u8arr[n] = bstr.charCodeAt(n); @@ -267,11 +262,11 @@ export class FileService { contentType = contentType || ''; const byteCharacters = atob(base64Data); const byteArray = new Uint8Array(byteCharacters.length); - + for (let i = 0; i < byteCharacters.length; i++) { byteArray[i] = byteCharacters.charCodeAt(i); } - + return new Blob([byteArray], { type: contentType }); } diff --git a/src/app/services/functions/time.service.ts b/src/app/services/functions/time.service.ts index ce2ae0fb0..114b13b42 100644 --- a/src/app/services/functions/time.service.ts +++ b/src/app/services/functions/time.service.ts @@ -1,6 +1,6 @@ import { Injectable } from '@angular/core'; import { ChatService } from '../chat.service'; -import { ChatSystemService } from '../chat/chat-system.service'; +// import { ChatSystemService } from '../chat/chat-system.service'; @Injectable({ providedIn: 'root' @@ -9,8 +9,10 @@ export class TimeService { countDownTime: any; room: any; - constructor(private chatService: ChatService, - public ChatSystemService: ChatSystemService,) { } + constructor( + //private chatService: ChatService, + //public ChatSystemService: ChatSystemService, + ) { } showDateDuration(start:any) { let end; @@ -42,7 +44,7 @@ export class TimeService { } countDownDate(date:any, roomId:string){ - + let difference = new Date(date).getTime() - new Date().getTime(); let c_day = Math.floor(difference/(1000*60*60*24)); let c_hours = Math.floor((difference % (1000*60*60*24)) / (1000*60*60)); @@ -55,22 +57,22 @@ export class TimeService { this.countDownTime = "Expired"; let body = { "roomId":roomId, } - this.chatService.getRoomInfo(roomId).subscribe(room=>{ - this.room = room['room']; + // this.chatService.getRoomInfo(roomId).subscribe(room=>{ + // this.room = room['room']; - if(this.room.t === 'p'){ - this.chatService.deleteGroup(body).subscribe(res=>{ - - }); - } - else{ - this.chatService.deleteChannel(body).subscribe(res=>{ - - }); - } - }); + // if(this.room.t === 'p'){ + // this.chatService.deleteGroup(body).subscribe(res=>{ + + // }); + // } + // else{ + // this.chatService.deleteChannel(body).subscribe(res=>{ + + // }); + // } + // }); } - + return this.countDownTime; } @@ -97,7 +99,7 @@ export class TimeService { // }); // } // else{ - + // this.chatService.deleteChannel(body).subscribe(res=>{ // this.ChatSystemService.deleteRoom(roomId) // }); diff --git a/src/app/services/monitoring/opentelemetry/opentelemetry.ts b/src/app/services/monitoring/opentelemetry/opentelemetry.ts index eab85fd4d..aa94ed3d5 100644 --- a/src/app/services/monitoring/opentelemetry/opentelemetry.ts +++ b/src/app/services/monitoring/opentelemetry/opentelemetry.ts @@ -8,7 +8,6 @@ import { context, trace, propagation } from '@opentelemetry/api'; import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'; // const { OTLPTraceExporter: OTLPTraceExporterProto } = require("@opentelemetry/exporter-trace-otlp-proto"); - function createProvider(serviceName) { const provider = new WebTracerProvider({ resource: new Resource({ diff --git a/src/app/services/new-chat/new-chat-system.service.spec.ts b/src/app/services/new-chat/new-chat-system.service.spec.ts deleted file mode 100644 index 867114338..000000000 --- a/src/app/services/new-chat/new-chat-system.service.spec.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { TestBed } from '@angular/core/testing'; - -import { NewChatSystemService } from './new-chat-system.service'; - -describe('NewChatSystemService', () => { - let service: NewChatSystemService; - - beforeEach(() => { - TestBed.configureTestingModule({}); - service = TestBed.inject(NewChatSystemService); - }); - - it('should be created', () => { - expect(service).toBeTruthy(); - }); -}); diff --git a/src/app/services/new-chat/new-chat-system.service.ts b/src/app/services/new-chat/new-chat-system.service.ts deleted file mode 100644 index e344cb606..000000000 --- a/src/app/services/new-chat/new-chat-system.service.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { Injectable } from '@angular/core'; - -@Injectable({ - providedIn: 'root' -}) -export class NewChatSystemService { - - constructor( - - ) { } -} diff --git a/src/app/services/notifications.service.ts b/src/app/services/notifications.service.ts index 8a26feedf..ef75f94e7 100644 --- a/src/app/services/notifications.service.ts +++ b/src/app/services/notifications.service.ts @@ -16,8 +16,7 @@ import { AngularFireMessaging } from '@angular/fire/messaging'; import { NotificationHolderService } from 'src/app/store/notification-holder.service'; import { ChatService } from 'src/app/services/chat.service'; import { FCM } from '@capacitor-community/fcm'; -import { ChatSystemService } from './chat/chat-system.service'; -import {ChatController} from 'src/app/controller/chat' +// import { ChatSystemService } from './chat/chat-system.service'; @Injectable({ providedIn: 'root' @@ -43,8 +42,6 @@ export class NotificationsService { notificationReceived: EventEmitter = new EventEmitter(); token = '' - ChatController = ChatController - constructor( private http: HttpClient, private storageService: StorageService, diff --git a/src/app/services/processes.service.ts b/src/app/services/processes.service.ts index 46fb847fc..8e24f511b 100644 --- a/src/app/services/processes.service.ts +++ b/src/app/services/processes.service.ts @@ -10,7 +10,6 @@ import { GetTasksListType } from '../models/GetTasksListType'; import { fullTaskList } from '../models/dailyworktask.model'; import { ChangeProfileService } from './change-profile.service'; import { SessionStore } from '../store/session.service'; -import { CPSession } from '../store/documentManagement'; @Injectable({ providedIn: 'root' }) diff --git a/src/app/services/webnotifications.service.spec.ts b/src/app/services/webnotifications.service.spec.ts deleted file mode 100644 index 5af6818b3..000000000 --- a/src/app/services/webnotifications.service.spec.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { TestBed } from '@angular/core/testing'; - -import { WebNotificationsService } from './webnotifications.service'; - -describe('WebNotificationsService', () => { - let service: WebNotificationsService; - - beforeEach(() => { - TestBed.configureTestingModule({}); - service = TestBed.inject(WebNotificationsService); - }); - - it('should be created', () => { - expect(service).toBeTruthy(); - }); -}); diff --git a/src/app/services/webnotifications.service.ts b/src/app/services/webnotifications.service.ts deleted file mode 100644 index 6aa22b8d0..000000000 --- a/src/app/services/webnotifications.service.ts +++ /dev/null @@ -1,213 +0,0 @@ -import { Injectable, NgZone } from '@angular/core'; -import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; -import { environment } from 'src/environments/environment'; -import { StorageService } from 'src/app/services/storage.service'; -import { AuthConnstants } from 'src/app/config/auth-constants'; -import { Tokenn } from '../models/token.model'; -import { ModalController, AlertController, AnimationController, Platform } from '@ionic/angular'; -import { NavigationExtras, Router } from '@angular/router'; -import { ToastService } from './toast.service'; - -@Injectable({ - providedIn: 'root' -}) -export class WebNotificationsService { - - adding: "intervenient" | "CC" = "intervenient"; - folderId: string; - - constructor( - private http: HttpClient, - private storageService: StorageService, - private modalController: ModalController, - public modalCtrl: AlertController, - private animationController: AnimationController, - private platform: Platform, - private router: Router, - private toastService: ToastService) { } - - - webconnection() { - - var inicializeObj = { - appId: "com.gpr.gabinetedigital", - mfpContextRoot: "/mfp", - /* serverUrl: "http://gpr-dev-10.gabinetedigital.local:9080", - safariWebsitePushId: "http://gpr-dev-10.gabinetedigital.local:9080", */ - } - - - - /* MFPPush.initialize({ - appId: "com.gpr.gabinetedigital", - mfpContextRoot: "/mfp", - }); */ - - /* MFPPush.registerDevice() - .then((res) => { - - - setTimeout(()=>{ - MFPPush.registerDevice() - .then((res) => { - - }) - .catch((err) => { - - }); - }, 1000) - - - }) - .catch((err) => { - - }); */ - } - - /* getTokenByUserIdAndId(user, userID) { - const geturl = environment.apiURL + 'notifications/user/' + userID; - - return this.http.get(`${geturl}`); - } */ - - /* getAndpostToken(username) { - if (this.platform.is('desktop') || this.platform.is('mobileweb')) { - - } else { - - const geturl = environment.apiURL + 'notifications/token'; */ - /* - window['WLAuthorizationManager'].obtainAccessToken("push.mobileclient").then( - (token) => { - - - MFPPush.initialize( - function (successResponse) { - - }, - function (failureResponse) { - - } - ); - - MFPPush.registerDevice(null, (successResponse) => { - - - this.storageService.store(username, successResponse.deviceId); - this.storageService.get(username).then(value => { - - this.storageService.get(AuthConnstants.USER).then(res => { - - const headers = { 'Authorization': 'Basic cGF1bG8ucGludG9AZ2FiaW5ldGVkaWdpdGFsLmxvY2FsOnRhYnRlc3RlQDAwNg==' }; - const body = { - UserId: res.UserId, - TokenId: successResponse.deviceId, - Status: 1, - Service: 1 - }; - this.http.post(`${geturl}`, body, { headers }).subscribe(data => { - - }) - }); - - }); - }, - function (failureResponse) { - - } - ); - }, (error) => { - - - } - ); - } - - } */ - /* - async onReceviNotification() { - window['WLAuthorizationManager'].obtainAccessToken("push.mobileclient").then( - (token) => { - - - MFPPush.initialize( - function (successResponse) { - - MFPPush.registerNotificationsCallback(notificationReceived); - }, - function (failureResponse) { - - } - ); - var notificationReceived = (message) => { - - var data = JSON.parse(message.payload); - - - - - if(message.actionName){ - this.notificatinsRoutes(data); - } else { - this.toastService.notificationMessage(message.alert,this.notificatinsRoutes, data); - } - - } - }, (error) => { - - - } - ); - } */ - - /* notificatinsRoutes = (data) => { - if (data.Service === "agenda") { - this.zone.run(() => this.router.navigate(['/home/agenda', data.IdObject, 'agenda'])); - } - else if (data.Service === "gabinete-digital" && data.Object === "expediente") { - this.zone.run(() => this.router.navigate(['/home/gabinete-digital/expediente',data.IdObject,'gabinete-digital'])); - } - else if (data.Service === "gabinete-digital" && data.Object === "event-list") { - this.zone.run(() => this.router.navigate(['/home/gabinete-digital/event-list/approve-event',data.IdObject, 'gabinete-digital'])); - }else if (data.Service === "gabinete-digital" && data.Object === "despachos") { - let navigationExtras: NavigationExtras = { - queryParams: { - "serialNumber": data.IdObject, - } - }; - this.zone.run(() => this.router.navigate(['/home/gabinete-digital/despachos/despacho'], navigationExtras)); - } - else if (data.Service === "gabinete-digital" && data.Object === "parecer") { - let navigationExtras: NavigationExtras = { - queryParams: { - enterAnimation: "", - serialNumber: data.IdObject, - } - }; - this.zone.run(() => this.router.navigate(['/home/gabinete-digital/pedidos/pedido'], navigationExtras)); - } - else if (data.Service === "gabinete-digital" && data.Object === "deferimento") { - let navigationExtras: NavigationExtras = { - queryParams: { - enterAnimation: "", - serialNumber: data.IdObject, - } - }; - this.zone.run(() => this.router.navigate(['/home/gabinete-digital/pedidos/pedido'], navigationExtras)); - } - else if (data.Service === "accoes" && data.Object === "accao") { - this.zone.run(() => this.router.navigate(['/home/publications',data.IdObject])); - } - else if (data.Service === "accoes" && data.Object === "publicacao") { - this.zone.run(() => this.router.navigate(['/home/publications/view-publications',data.FolderId,data.IdObject])); - } - } - - platformVerify() { - - if (this.platform.is('cordova')) { - } else { - } - } */ - -} diff --git a/src/app/shared/agenda/new-event/new-event.page.ts b/src/app/shared/agenda/new-event/new-event.page.ts index e96390614..24f383652 100644 --- a/src/app/shared/agenda/new-event/new-event.page.ts +++ b/src/app/shared/agenda/new-event/new-event.page.ts @@ -24,7 +24,7 @@ import { ViewChild } from '@angular/core'; import { FormGroup, Validators } from '@angular/forms'; import { NGX_MAT_DATE_FORMATS } from '@angular-material-components/datetime-picker'; import { ThemeService } from 'src/app/services/theme.service' -import { ChatMethodsService } from 'src/app/services/chat/chat-methods.service'; +//import { ChatMethodsService } from 'src/app/services/chat/chat-methods.service'; import { SessionStore } from 'src/app/store/session.service'; import { HttpErrorHandle } from 'src/app/services/http-error-handle.service'; import { environment } from 'src/environments/environment'; @@ -142,7 +142,7 @@ export class NewEventPage implements OnInit { private toastService: ToastService, private dateAdapter: DateAdapter, public ThemeService: ThemeService, - private chatMethodService: ChatMethodsService, + // private chatMethodService: ChatMethodsService, private hhtpErrorHandle: HttpErrorHandle, private processeService: ProcessesService, public TaskService: TaskService, @@ -579,9 +579,9 @@ export class NewEventPage implements OnInit { "calendarId": CalendarId } - if (this.roomId) { - this.chatMethodService.sendMessage(this.roomId, data); - } + // if (this.roomId) { + // this.chatMethodService.sendMessage(this.roomId, data); + // } }, error => { @@ -637,9 +637,9 @@ export class NewEventPage implements OnInit { "id": id, "calendarId": CalendarId } - if (this.roomId) { - this.chatMethodService.sendMessage(this.roomId, data); - } + // if (this.roomId) { + // this.chatMethodService.sendMessage(this.roomId, data); + // } }, (error) => { //const connectionToServer = this.ServerConnectionService.BaseAPI() @@ -812,9 +812,9 @@ export class NewEventPage implements OnInit { "id": id, "calendarId": CalendarId } - if (this.roomId) { - this.chatMethodService.sendMessage(this.roomId, data); - } + // if (this.roomId) { + // this.chatMethodService.sendMessage(this.roomId, data); + // } }, (error) => { loader.remove() @@ -878,9 +878,9 @@ export class NewEventPage implements OnInit { "id": id, "calendarId": CalendarId } - if (this.roomId) { - this.chatMethodService.sendMessage(this.roomId, data); - } + // if (this.roomId) { + // this.chatMethodService.sendMessage(this.roomId, data); + // } }, (error) => { loader.remove() diff --git a/src/app/shared/chat/group-messages/group-contacts/group-contacts.page.ts b/src/app/shared/chat/group-messages/group-contacts/group-contacts.page.ts index 6b5b2f960..401da6820 100644 --- a/src/app/shared/chat/group-messages/group-contacts/group-contacts.page.ts +++ b/src/app/shared/chat/group-messages/group-contacts/group-contacts.page.ts @@ -1,6 +1,6 @@ import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { ThemeService } from 'src/app/services/theme.service' -import { ChatSystemService } from 'src/app/services/chat/chat-system.service'; +// import { ChatSystemService } from 'src/app/services/chat/chat-system.service'; import { ContactRepositoryService } from 'src/app/services/Repositorys/contacts/repository/contacts-repository.service'; import { UserContacts } from 'src/app/services/Repositorys/contacts/data-source/contacts-data-source.service'; import { RoomRepositoryService } from 'src/app/module/chat/data/repository/room-repository.service' @@ -36,7 +36,7 @@ export class GroupContactsPage implements OnInit { constructor( public ThemeService: ThemeService, - public ChatSystemService: ChatSystemService, + // public ChatSystemService: ChatSystemService, private contactsRepositoryService: ContactRepositoryService, private RoomRepositoryService: RoomRepositoryService, private httpErrorHandle: HttpErrorHandle, diff --git a/src/app/shared/chat/group-messages/group-messages.page.ts b/src/app/shared/chat/group-messages/group-messages.page.ts index d84c01f6d..f5588dc49 100644 --- a/src/app/shared/chat/group-messages/group-messages.page.ts +++ b/src/app/shared/chat/group-messages/group-messages.page.ts @@ -14,8 +14,8 @@ import { ViewDocumentPage } from 'src/app/modals/view-document/view-document.pag import { ThemeService } from 'src/app/services/theme.service' import { ViewEventPage } from 'src/app/modals/view-event/view-event.page'; import { Storage } from '@ionic/storage'; -import { ChatSystemService } from 'src/app/services/chat/chat-system.service'; -import { MessageService } from 'src/app/services/chat/message.service'; +// import { ChatSystemService } from 'src/app/services/chat/chat-system.service'; +// simport { MessageService } from 'src/app/services/chat/message.service'; import { CameraService } from 'src/app/services/camera.service'; import { FileType } from 'src/app/models/fileType'; @@ -84,7 +84,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe groupNameFormart = ""; constructor( - public ChatSystemService: ChatSystemService, + // public ChatSystemService: ChatSystemService, private modalController: ModalController, public popoverController: PopoverController, private chatService: ChatService, @@ -104,7 +104,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe private FileValidatorService: FileValidatorService ) { - this.ChatSystemService.getUser() + // this.ChatSystemService.getUser() this.loggedUserChat = SessionStore.user.ChatData['data']; this.isGroupCreated = true; @@ -113,11 +113,11 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe ngOnChanges(changes: SimpleChanges): void { this.getRoomInfo(); - this.ChatSystemService.getGroupRoom(this.roomId).loadHistory({}); - // - this.ChatSystemService.openRoom(this.roomId) - this.ChatSystemService.getGroupRoom(this.roomId).scrollDown = this.scrollToBottomClicked - this.groupNameFormart = this.ChatSystemService.getGroupRoom(this.roomId).name.split('-').join(' ') + // this.ChatSystemService.getGroupRoom(this.roomId).loadHistory({}); + // // + // this.ChatSystemService.openRoom(this.roomId) + // this.ChatSystemService.getGroupRoom(this.roomId).scrollDown = this.scrollToBottomClicked + // this.groupNameFormart = this.ChatSystemService.getGroupRoom(this.roomId).name.split('-').join(' ') this.showAvatar = false setTimeout(() => { @@ -128,11 +128,11 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe this.deleteRecording(); - if (SessionStore.user.ChatData.data.userId == this.ChatSystemService.getGroupRoom(this.roomId).u._id) { - this.isAdmin = true - } else { - this.isAdmin = false - } + // if (SessionStore.user.ChatData.data.userId == this.ChatSystemService.getGroupRoom(this.roomId).u._id) { + // this.isAdmin = true + // } else { + // this.isAdmin = false + // } } @@ -340,9 +340,9 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe // }); - if(this.ChatSystemService.users.length == 0) { - this.ChatSystemService.getUser() - } + // if(this.ChatSystemService.users.length == 0) { + // this.ChatSystemService.getUser() + // } } @@ -375,9 +375,9 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe async getRoomInfo() { - if(this.ChatSystemService.getGroupRoom(this.roomId)) { - this.ChatSystemService.getGroupRoom(this.roomId).loadHistory({}); - } + // if(this.ChatSystemService.getGroupRoom(this.roomId)) { + // this.ChatSystemService.getGroupRoom(this.roomId).loadHistory({}); + // } this.getGroupContacts(this.room); } @@ -401,11 +401,11 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe // }); // } - this.members = this.ChatSystemService.getGroupRoom(this.roomId).members + // this.members = this.ChatSystemService.getGroupRoom(this.roomId).members } sendMessage() { - this.ChatSystemService.getGroupRoom(this.roomId).send({}) + // this.ChatSystemService.getGroupRoom(this.roomId).send({}) } @@ -429,30 +429,30 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe const formData = new FormData(); formData.append("blobFile", blob); - this.ChatSystemService.getGroupRoom(roomId).send({ - file: { - "type": "application/audio", - "msDuration": audioFile.value.msDuration, - "mimeType": audioFile.value.mimeType, - }, - attachments: [{ - "title": fileName, - "title_link_download": true, - "type": "audio" - }], - temporaryData: formData, - attachmentsModelData: { - fileBase64: encodedData, - } - }) + // this.ChatSystemService.getGroupRoom(roomId).send({ + // file: { + // "type": "application/audio", + // "msDuration": audioFile.value.msDuration, + // "mimeType": audioFile.value.mimeType, + // }, + // attachments: [{ + // "title": fileName, + // "title_link_download": true, + // "type": "audio" + // }], + // temporaryData: formData, + // attachmentsModelData: { + // fileBase64: encodedData, + // } + // }) }); this.deleteRecording(); } deleteMessage(msgId: string) { - const room = this.ChatSystemService.getGroupRoom(this.roomId) - this.alertService.confirmDeleteMessage(msgId, room); + // const room = this.ChatSystemService.getGroupRoom(this.roomId) + // this.alertService.confirmDeleteMessage(msgId, room); } async openGroupMessagesOptions() { @@ -497,7 +497,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe this.getRoomInfo(); this.closeAllDesktopComponents.emit(); this.showEmptyContainer.emit(); - this.ChatSystemService.hidingRoom(this.roomId).catch((error) => console.error(error)); + // this.ChatSystemService.hidingRoom(this.roomId).catch((error) => console.error(error)); } else if (res.data == 'delete') { this.closeAllDesktopComponents.emit(); @@ -711,22 +711,22 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe const formData = new FormData(); formData.append("blobFile", blob); - this.ChatSystemService.getGroupRoom(roomId).send({ - file: { - "type": "application/img", - "guid": '', - }, - temporaryData: formData, - attachments: [{ - "title": file.path, - "image_url": 'data:image/jpeg;base64,' + file.base64String, - "text": "description", - "title_link_download": false, - }], - attachmentsModelData: { - fileBase64: base64, - } - }) + // this.ChatSystemService.getGroupRoom(roomId).send({ + // file: { + // "type": "application/img", + // "guid": '', + // }, + // temporaryData: formData, + // attachments: [{ + // "title": file.path, + // "image_url": 'data:image/jpeg;base64,' + file.base64String, + // "text": "description", + // "title_link_download": false, + // }], + // attachmentsModelData: { + // fileBase64: base64, + // } + // }) } @@ -760,21 +760,21 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe const formData = new FormData(); formData.append("blobFile", blob); - this.ChatSystemService.getGroupRoom(roomId).send({ - file: { - "type": "application/img", - "guid": '' - }, - attachments: [{ - "title": 'file.jpg', - "text": "description", - "title_link_download": false, - }], - temporaryData: formData, - attachmentsModelData: { - fileBase64: imageBase64, - } - }) + // this.ChatSystemService.getGroupRoom(roomId).send({ + // file: { + // "type": "application/img", + // "guid": '' + // }, + // attachments: [{ + // "title": 'file.jpg', + // "text": "description", + // "title_link_download": false, + // }], + // temporaryData: formData, + // attachmentsModelData: { + // fileBase64: imageBase64, + // } + // }) } @@ -804,28 +804,28 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe if (data.selected) { - this.ChatSystemService.getGroupRoom(roomId).send({ - file: { - "name": res.data.selected.Assunto, - "type": "application/webtrix", - "ApplicationId": res.data.selected.ApplicationType, - "DocId": res.data.selected.Id, - "Assunto": res.data.selected.Assunto, - }, - attachments: [{ - "title": res.data.selected.Assunto, - "description": res.data.selected.DocTypeDesc, - // "title_link": url_no_options, - "title_link_download": true, - //"thumb_url": "assets/images/webtrix-logo.png", - // "message_link": url_no_options, - "type": "webtrix", - //"thumb_url": "assets/images/webtrix-logo.png", - "text": res.data.selected.DocTypeDesc, - "thumb_url": "https://static.ichimura.ed.jp/uploads/2017/10/pdf-icon.png", - }], - temporaryData: res - }) + // this.ChatSystemService.getGroupRoom(roomId).send({ + // file: { + // "name": res.data.selected.Assunto, + // "type": "application/webtrix", + // "ApplicationId": res.data.selected.ApplicationType, + // "DocId": res.data.selected.Id, + // "Assunto": res.data.selected.Assunto, + // }, + // attachments: [{ + // "title": res.data.selected.Assunto, + // "description": res.data.selected.DocTypeDesc, + // // "title_link": url_no_options, + // "title_link_download": true, + // //"thumb_url": "assets/images/webtrix-logo.png", + // // "message_link": url_no_options, + // "type": "webtrix", + // //"thumb_url": "assets/images/webtrix-logo.png", + // "text": res.data.selected.DocTypeDesc, + // "thumb_url": "https://static.ichimura.ed.jp/uploads/2017/10/pdf-icon.png", + // }], + // temporaryData: res + // }) } @@ -851,22 +851,22 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe const formData = new FormData(); formData.append("blobFile", blob); - this.ChatSystemService.getGroupRoom(roomId).send({ - file: { - "type": "application/img", - "guid": '' - }, - temporaryData: formData, - attachments: [{ - "title": file.path, - "image_url": 'data:image/jpeg;base64,' + file.base64String, - "text": "description", - "title_link_download": false, - }], - attachmentsModelData: { - fileBase64: imageBase64, - } - }) + // this.ChatSystemService.getGroupRoom(roomId).send({ + // file: { + // "type": "application/img", + // "guid": '' + // }, + // temporaryData: formData, + // attachments: [{ + // "title": file.path, + // "image_url": 'data:image/jpeg;base64,' + file.base64String, + // "text": "description", + // "title_link_download": false, + // }], + // attachmentsModelData: { + // fileBase64: imageBase64, + // } + // }) } @@ -907,23 +907,23 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe formData.append('blobFile', file); } - this.ChatSystemService.getGroupRoom(roomId).send({ - file: { - "type": file.type, - "guid": '', - }, - attachments: [{ - "title": file.name, - "name": file.name, - //"image_url": res, - // "text": "description", - "title_link_download": false, - }], - temporaryData: formData, - attachmentsModelData: { - fileBase64: fileBase64, - } - }) + // this.ChatSystemService.getGroupRoom(roomId).send({ + // file: { + // "type": file.type, + // "guid": '', + // }, + // attachments: [{ + // "title": file.name, + // "name": file.name, + // //"image_url": res, + // // "text": "description", + // "title_link_download": false, + // }], + // temporaryData: formData, + // attachmentsModelData: { + // fileBase64: fileBase64, + // } + // }) } else { this.toastService._badRequest("Ficheiro inválido") } @@ -1033,7 +1033,7 @@ export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDe } - downloadFileMsg(msg: MessageService) { + downloadFileMsg(msg: any) { msg.downloadFileMsg() } diff --git a/src/app/shared/chat/messages/contacts/contacts.page.ts b/src/app/shared/chat/messages/contacts/contacts.page.ts index 5a47c7711..85da91fef 100644 --- a/src/app/shared/chat/messages/contacts/contacts.page.ts +++ b/src/app/shared/chat/messages/contacts/contacts.page.ts @@ -3,7 +3,7 @@ import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { ModalController } from '@ionic/angular'; import { MessagesPage } from '../messages.page'; import { ThemeService } from 'src/app/services/theme.service' -import { ChatSystemService } from 'src/app/services/chat/chat-system.service' +// import { ChatSystemService } from 'src/app/services/chat/chat-system.service' import { SessionStore } from 'src/app/store/session.service'; import { ContactRepositoryService } from 'src/app/services/Repositorys/contacts/repository/contacts-repository.service'; import { UserContacts } from 'src/app/services/Repositorys/contacts/data-source/contacts-data-source.service'; @@ -46,7 +46,7 @@ export class ContactsPage implements OnInit { constructor( private modalController: ModalController, public ThemeService: ThemeService, - public ChatSystemService: ChatSystemService, + // public ChatSystemService: ChatSystemService, private contactsRepositoryService: ContactRepositoryService, private roomRepositoryService: RoomRepositoryService, private httpErrorHandle: HttpErrorHandle, diff --git a/src/app/shared/chat/messages/messages.page.ts b/src/app/shared/chat/messages/messages.page.ts index 9d52945eb..f6e61f2da 100644 --- a/src/app/shared/chat/messages/messages.page.ts +++ b/src/app/shared/chat/messages/messages.page.ts @@ -13,8 +13,8 @@ import { ViewDocumentPage } from 'src/app/modals/view-document/view-document.pag import { ThemeService } from 'src/app/services/theme.service'; import { ViewEventPage } from 'src/app/modals/view-event/view-event.page'; import { Storage } from '@ionic/storage'; -import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service' -import { MessageService } from 'src/app/services/chat/message.service'; +// import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service' +// simport { MessageService } from 'src/app/services/chat/message.service'; import { FileType } from 'src/app/models/fileType'; import { SearchPage } from 'src/app/pages/search/search.page'; import { Camera, CameraResultType, CameraSource } from '@capacitor/camera'; @@ -46,6 +46,8 @@ import { tap } from 'rxjs/operators'; import { MessageEntity } from 'src/app/module/chat/domain/entity/message'; import { MemberTable } from 'src/app/module/chat/infra/database/dexie/schema/members'; import { TypingTable } from 'src/app/module/chat/infra/database/dexie/schema/typing'; +import { MessageAttachmentFileType, MessageAttachmentSource } from 'src/app/module/chat/data/dto/message/messageOutputDTO'; +import { JSFileToBase64 } from 'src/app/utils/ToBase64'; const IMAGE_DIR = 'stored-images'; @@ -92,7 +94,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy longPressActive = false; frameUrl: any; downloadFile: string; - massages: MessageService[] = [] + massages = [] showAvatar = true; @@ -145,7 +147,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy private gestureController: GestureController, public ThemeService: ThemeService, private storage: Storage, - public RochetChatConnectorService: RochetChatConnectorService, + // public RochetChatConnectorService: RochetChatConnectorService, private sanitiser: DomSanitizer, private file: File, private platform: Platform, @@ -155,7 +157,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy private roomRepositoryService: RoomRepositoryService, private messageRepositoryService: MessageRepositoryService, private userTypingServiceRepository: UserTypingServiceRepository, - private chatServiceService: ChatServiceService + private chatServiceService: ChatServiceService, ) { // update this.checkAudioPermission() @@ -201,7 +203,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy } - toggleEmojiPicker(message: any) { + toggleEmojiPicker(message: MessageEntity) { if (this.selectedMessage === message) { this.selectedMessage = null; // Close the picker if it's already open } else { @@ -209,7 +211,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy } } - addReaction(message: any, emoji: string) { + addReaction(message: MessageEntity, emoji: string) { // Logic to add reaction to the message console.log(`Reacting to message ${message.id} with emoji ${emoji.codePointAt(0).toString(16)}`); this.selectedMessage = null; // Close the picker after adding reaction @@ -235,7 +237,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy this.userTypingServiceRepository.addUserTyping(this.roomId) } - async editMessage(message: any) { + async editMessage(message: MessageEntity) { const modal = await this.modalController.create({ component: EditMessagePage, @@ -888,7 +890,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy } async addFile() { - this.addFileToChat(['.doc', '.docx', '.pdf']) + this.addFileToChat(['.doc', '.docx', '.pdf'], MessageAttachmentFileType.Doc) } async addFileWebtrix() { @@ -991,20 +993,17 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy } - messageDelete({messageId}) { + messageDelete(message: MessageEntity) { // this.messageRepositoryService.sendMessageDelete() this.chatServiceService.messageDelete({ - messageId: messageId, + messageId: message.id, roomId: this.roomId, }) } - async addFileToChat(types: typeof FileType[]) { + async addFileToChat(types: typeof FileType[], attachmentFileType:MessageAttachmentFileType) { - - const roomId = this.roomId - - const file: any = await this.fileService.getFileFromDevice(types); + const file = await this.fileService.getFileFromDevice(types); if (file.type == 'application/pdf' || file.type == 'application/doc' || file.type == 'application/docx' || file.type == 'application/xls' || file.type == 'application/xlsx' || file.type == 'application/ppt' || @@ -1014,56 +1013,33 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy const fileName = file.name - const validation = this.FileValidatorService.fileNameValidation(fileName) + const FilenameValidation = this.FileValidatorService.fileNameValidation(fileName) - if (validation.isOk) { + if (FilenameValidation.isOk) { + let fileBase64 = await JSFileToBase64(file); - const encodedData = btoa(JSON.stringify(await this.getBase64(file).catch((error) => { - console.error(error); - }))); + if(fileBase64.isOk()) { - let blob; - let formData - let fileBase64 - if (this.platform.is("tablet")) { + const message = new MessageEntity(); + message.roomId = this.roomId - blob = this.fileService.base64toBlob(encodedData, file.type) - console.log('BLOB BLOB', blob) + message.sender = { + userPhoto: '', + wxeMail: SessionStore.user.Email, + wxFullName: SessionStore.user.FullName, + wxUserId: SessionStore.user.UserId + } - formData = new FormData(); - formData.append('blobFile', file); - /* console.log('add file', fileBase64) */ + message.attachments = [{ + file: fileBase64.value, + fileName: file.name, + source: MessageAttachmentSource.Device, + fileType: MessageAttachmentFileType.Doc + }] - } else { - console.log('encode data', encodedData) - blob = this.fileService.base64toBlob(encodedData, file.type) - - fileBase64 = await this._getBase64(file) - - formData = new FormData(); - formData.append('blobFile', file); + this.chatServiceService.sendMessage(message) } - - - - // this.ChatSystemService.getDmRoom(roomId).send({ - // file: { - // "type": file.type, - // "guid": '', - // }, - // attachments: [{ - // "title": file.name, - // "name": file.name, - // //"image_url": res, - // // "text": "description", - // "title_link_download": false, - // }], - // temporaryData: formData, - // attachmentsModelData: { - // fileBase64: fileBase64, - // } - // }) } else { this.toastService._badRequest("Ficheiro inválido") } @@ -1197,11 +1173,6 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy - - downloadFileMsg(msg: MessageService) { - msg.downloadFileMsg() - } - pdfPreview() { const options: DocumentViewerOptions = { title: 'My App' @@ -1212,7 +1183,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy async audioPreview(msg) { if (!msg.attachments[0].title_link || msg.attachments[0].title_link === null || msg.attachments[0].title_link === '') { - this.downloadFileMsg(msg) + // this.downloadFileMsg(msg) } else { } } @@ -1294,7 +1265,7 @@ export class MessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy } else { if (!msg.attachments[0].image_url || msg.attachments[0].image_url === null || msg.attachments[0].image_url === '') { - this.downloadFileMsg(msg) + // this.downloadFileMsg(msg) } else { diff --git a/src/app/shared/chat/new-group/contacts/contacts.page.html b/src/app/shared/chat/new-group/contacts/contacts.page.html index e6b2258b9..310e292cc 100644 --- a/src/app/shared/chat/new-group/contacts/contacts.page.html +++ b/src/app/shared/chat/new-group/contacts/contacts.page.html @@ -36,7 +36,7 @@ --> - + diff --git a/src/app/shared/chat/new-group/contacts/contacts.page.ts b/src/app/shared/chat/new-group/contacts/contacts.page.ts index 01218ebe9..52d4cf1a7 100644 --- a/src/app/shared/chat/new-group/contacts/contacts.page.ts +++ b/src/app/shared/chat/new-group/contacts/contacts.page.ts @@ -2,7 +2,7 @@ import { Component, OnInit } from '@angular/core'; import { ModalController } from '@ionic/angular'; import { GroupMessagesPage } from '../../group-messages/group-messages.page'; import { ThemeService } from 'src/app/services/theme.service' -import { ChatSystemService } from 'src/app/services/chat/chat-system.service' +// import { ChatSystemService } from 'src/app/services/chat/chat-system.service' @Component({ selector: 'app-contacts', @@ -15,9 +15,9 @@ export class ContactsPage implements OnInit { constructor( private modalController: ModalController, public ThemeService: ThemeService, - public ChatSystemService: ChatSystemService - ) - { + // public ChatSystemService: ChatSystemService + ) + { } @@ -27,7 +27,7 @@ export class ContactsPage implements OnInit { } loadUsers(){ - this.ChatSystemService.getUser() + // sthis.ChatSystemService.getUser() } separateLetter(record, recordIndex, records){ @@ -55,13 +55,13 @@ export class ContactsPage implements OnInit { } clicked(){ - - + + } async groupMessages(){ const modal = await this.modalController.create({ component: GroupMessagesPage, - componentProps: {}, + componentProps: {}, cssClass: 'contacts', backdropDismiss: false }); diff --git a/src/app/shared/chat/new-group/new-group.page.ts b/src/app/shared/chat/new-group/new-group.page.ts index 303548589..721d0c534 100644 --- a/src/app/shared/chat/new-group/new-group.page.ts +++ b/src/app/shared/chat/new-group/new-group.page.ts @@ -1,6 +1,6 @@ import { Component, EventEmitter, Input, OnInit, Output,ViewContainerRef } from '@angular/core'; import { PickerController, PopoverController } from '@ionic/angular'; -import { ChatSystemService } from 'src/app/services/chat/chat-system.service'; +// import { ChatSystemService } from 'src/app/services/chat/chat-system.service'; import { DataService } from 'src/app/services/data.service'; import { GroupDurationPage } from 'src/app/shared/popover/group-duration/group-duration.page'; import { SessionStore } from 'src/app/store/session.service'; @@ -46,7 +46,7 @@ export class NewGroupPage implements OnInit{ private pickerController: PickerController, private popoverController: PopoverController, private dataService:DataService, - public ChatSystemService: ChatSystemService, + // public ChatSystemService: ChatSystemService, public ThemeService: ThemeService, private RouteService: RouteService, private viewContainerRef: ViewContainerRef, @@ -136,13 +136,13 @@ export class NewGroupPage implements OnInit{ } createGroupWithAttachmentsCath(res: any) { - if(!this.ChatSystemService.getGroupRoom(res.result.rid)) { - setTimeout(() => { - this.createGroupWithAttachmentsCath(res) - }, 1500) - } else { - this.createGroupWithAttachments(res) - } + // if(!this.ChatSystemService.getGroupRoom(res.result.rid)) { + // setTimeout(() => { + // this.createGroupWithAttachmentsCath(res) + // }, 1500) + // } else { + // this.createGroupWithAttachments(res) + // } } createGroupWithAttachments(res: any) { diff --git a/src/app/shared/popover/chat-debugging/chat-debugging.page.html b/src/app/shared/popover/chat-debugging/chat-debugging.page.html index 2ec64ebdc..d3c05e42c 100644 --- a/src/app/shared/popover/chat-debugging/chat-debugging.page.html +++ b/src/app/shared/popover/chat-debugging/chat-debugging.page.html @@ -1,4 +1,4 @@ - + diff --git a/src/app/shared/popover/chat-debugging/chat-debugging.page.ts b/src/app/shared/popover/chat-debugging/chat-debugging.page.ts index 5f7f81a04..bac830151 100644 --- a/src/app/shared/popover/chat-debugging/chat-debugging.page.ts +++ b/src/app/shared/popover/chat-debugging/chat-debugging.page.ts @@ -1,5 +1,5 @@ import { Component, OnInit } from '@angular/core'; -import { ChatSystemService } from 'src/app/services/chat/chat-system.service'; +// import { ChatSystemService } from 'src/app/services/chat/chat-system.service'; @Component({ selector: 'app-chat-debugging', @@ -9,7 +9,7 @@ import { ChatSystemService } from 'src/app/services/chat/chat-system.service'; export class ChatDebuggingPage implements OnInit { constructor( - public ChatSystemService: ChatSystemService + // public ChatSystemService: ChatSystemService ) { } ngOnInit() {} diff --git a/src/app/shared/popover/chat-message-debugging/chat-message-debugging.page.ts b/src/app/shared/popover/chat-message-debugging/chat-message-debugging.page.ts index 64c46c02e..1fac0421f 100644 --- a/src/app/shared/popover/chat-message-debugging/chat-message-debugging.page.ts +++ b/src/app/shared/popover/chat-message-debugging/chat-message-debugging.page.ts @@ -1,6 +1,6 @@ import { Component, OnInit } from '@angular/core'; import { NavParams } from '@ionic/angular'; -import { ChatSystemService } from 'src/app/services/chat/chat-system.service'; +// import { ChatSystemService } from 'src/app/services/chat/chat-system.service'; @Component({ selector: 'app-chat-message-debugging', @@ -12,18 +12,18 @@ export class ChatMessageDebuggingPage implements OnInit { roomId: string constructor( - public ChatSystemService: ChatSystemService, + // public ChatSystemService: ChatSystemService, private navParams: NavParams ) { } ngOnInit() { this.roomId = this.navParams.get('roomId') - + } loadHistory() { - this.ChatSystemService.getDmRoom(this.roomId).loadHistory({}); + // this.ChatSystemService.getDmRoom(this.roomId).loadHistory({}); } } diff --git a/src/app/store/documentManagement.ts b/src/app/store/documentManagement.ts index f7737e42d..e69de29bb 100644 --- a/src/app/store/documentManagement.ts +++ b/src/app/store/documentManagement.ts @@ -1,33 +0,0 @@ -import { models } from 'src/plugin/src'; -import { DELETE, GET, SAVE } from '../models/beast-orm-function'; -const { rewriteSave, rewriteGet, rewriteDelete } = models.core.localStorage.rewrite; - -export class CPSession extends models.LocalStorage { - static UserId: number = models.preset() - static Email: string = models.preset() - static UserName: string = models.preset() - static FullName: string = models.preset() - static RoleID: number = models.preset() - static RoleDescription: string = models.preset() - static OrganicEntityID: number = models.preset() - static OrganicEntityName: string = models.preset() - static Status: string = models.preset() - static Authorization: string = models.preset() - static AuthorizationJwt: string = models.preset() -} - -// content production -models.migrate({ - databaseName:'content-production', - type: 'localStorage', - version: 1, - models: [CPSession], -}) -// rewrite -rewriteGet.connect(GET, [CPSession]) -rewriteSave.connect(SAVE, [CPSession]) -rewriteDelete.connect(DELETE, [CPSession]) -// get function - -console.log('get') -CPSession.get() \ No newline at end of file diff --git a/src/app/utils/ToBase64.ts b/src/app/utils/ToBase64.ts new file mode 100644 index 000000000..b3ed42c50 --- /dev/null +++ b/src/app/utils/ToBase64.ts @@ -0,0 +1,30 @@ +import { err, ok, Result } from "neverthrow"; + +/** + * Retrieves a `FileReader` instance, accounting for potential Zone.js modifications. + * @returns {FileReader} The original `FileReader` instance or a modified one if applicable. + */ +function getFileReader(): FileReader { + const fileReader = new FileReader(); + const zoneOriginalInstance = (fileReader as any)["__zone_symbol__originalInstance"]; + return zoneOriginalInstance || fileReader; +} + +/** + * Converts a `File` object to a Base64 encoded string. + * @param {File} file - The file to be converted. + * @returns {Promise>} A promise that resolves with a `Result` object containing either the Base64 encoded string or an error. + */ +export function JSFileToBase64(file: File): Promise> { + return new Promise((resolve, reject) => { + var reader = getFileReader(); + reader.readAsDataURL(file); + reader.onload = function () { + resolve(ok(reader.result as string)); + }; + reader.onerror = function (error) { + console.log('Error: ', error); + resolve(err(error)); + }; + }); +}