ref: updated tests/prettier/lint

This commit is contained in:
montaghanmy
2023-04-04 13:51:33 +01:00
parent 1458a11e7c
commit d4b054048c
31 changed files with 259 additions and 4323 deletions
@@ -1,351 +0,0 @@
import { afterAll, beforeAll, describe, expect, it } from "@jest/globals";
import { init, TestPlatform } from "../setup";
import { TestDbService } from "../utils.prepare.db";
import { Api } from "../utils.api";
import Application, {
PublicApplicationObject,
} from "../../../src/services/applications/entities/application";
import { cloneDeep } from "lodash";
import { logger as log } from "../../../src/core/platform/framework";
import { v1 as uuidv1 } from "uuid";
describe("Applications", () => {
const url = "/internal/services/applications/v1";
let platform: TestPlatform;
let testDbService: TestDbService;
let api: Api;
let appRepo;
beforeAll(async ends => {
platform = await init();
await platform.database.getConnector().drop();
testDbService = await TestDbService.getInstance(platform, true);
await testDbService.createDefault();
postPayload.company_id = platform.workspace.company_id;
api = new Api(platform);
appRepo = await testDbService.getRepository("application", Application);
ends();
});
afterAll(done => {
platform.tearDown().then(() => done());
});
const publishApp = async id => {
const entity = await appRepo.findOne({ id });
if (!entity) throw new Error(`entity ${id} not found`);
entity.publication.published = true;
await appRepo.save(entity);
};
describe("Create application", function () {
it("should 403 if creator is not a company admin", async done => {
const payload = { resource: cloneDeep(postPayload) };
const user = await testDbService.createUser([testDbService.defaultWorkspace()], {
companyRole: "member",
});
const response = await api.post(`${url}/applications`, payload, user.id);
expect(response.statusCode).toBe(403);
done();
});
it("should 200 on application create", async done => {
const payload = { resource: cloneDeep(postPayload) };
const response = await api.post(`${url}/applications`, payload);
expect(response.statusCode).toBe(200);
const r = response.resource;
expect(r.company_id).toBe(payload.resource.company_id);
expect(!!r.is_default).toBe(false);
expect(r.identity).toMatchObject(payload.resource.identity);
expect(r.access).toMatchObject(payload.resource.access);
expect(r.display).toMatchObject(payload.resource.display);
expect(r.publication).toMatchObject(payload.resource.publication);
expect(r.stats).toMatchObject({
created_at: expect.any(Number),
updated_at: expect.any(Number),
version: 0,
});
expect(r.api).toMatchObject({
hooks_url: payload.resource.api.hooks_url,
allowed_ips: payload.resource.api.allowed_ips,
private_key: expect.any(String),
});
expect(r.api.private_key).not.toBe("");
const dbData = await appRepo.findOne({ id: response.resource.id });
expect(dbData.api).toMatchObject({
allowed_ips: payload.resource.api.allowed_ips,
hooks_url: payload.resource.api.hooks_url,
private_key: expect.any(String),
});
done();
});
});
describe("Update application", function () {
let createdApp: PublicApplicationObject;
beforeAll(async done => {
const payload = { resource: cloneDeep(postPayload) };
const response = await api.post(`${url}/applications`, payload);
createdApp = response.resource;
done();
});
it("should 403 if editor is not a company admin", async done => {
if (!createdApp) throw new Error("can't find created app");
log.debug(createdApp);
const user = await testDbService.createUser([testDbService.defaultWorkspace()], {
companyRole: "member",
});
const response = await api.post(`${url}/applications/${createdApp.id}`, postPayload, user.id);
expect(response.statusCode).toBe(403);
done();
});
it("should 404 if application not found", async done => {
const response = await api.post(`${url}/applications/${uuidv1()}`, { resource: postPayload });
expect(response.statusCode).toBe(404);
done();
});
describe("Unpublished application", () => {
it("should 200 on application update", async done => {
const payload = { resource: cloneDeep(postPayload) };
payload.resource.is_default = true;
payload.resource.identity.name = "test2";
payload.resource.api.hooks_url = "123123";
payload.resource.access.read = [];
payload.resource.publication.requested = true;
const response = await api.post(`${url}/applications/${createdApp.id}`, payload);
expect(response.statusCode).toBe(200);
const r = response.resource;
expect(r.company_id).toBe(payload.resource.company_id);
expect(!!r.is_default).toBe(false);
expect(r.identity).toMatchObject(payload.resource.identity);
expect(r.access).toMatchObject(payload.resource.access);
expect(r.display).toMatchObject(payload.resource.display);
expect(r.publication).toMatchObject(payload.resource.publication);
expect(r.stats).toMatchObject({
created_at: expect.any(Number),
updated_at: expect.any(Number),
version: 1,
});
expect(r.api).toBeTruthy();
const dbData = await appRepo.findOne({ id: response.resource.id });
expect(dbData.api).toMatchObject({
allowed_ips: payload.resource.api.allowed_ips,
hooks_url: payload.resource.api.hooks_url,
private_key: expect.any(String),
});
done();
});
});
describe.skip("Published application", () => {
beforeAll(async done => {
const payload = { resource: cloneDeep(postPayload) };
const response = await api.post(`${url}/applications`, payload);
createdApp = response.resource;
await publishApp(createdApp.id);
done();
});
it("should 200 on update if allowed fields changed", async done => {
const payload = { resource: cloneDeep(createdApp) as Application };
const entity = await appRepo.findOne({ id: createdApp.id });
payload.resource.api = cloneDeep(entity.api);
payload.resource.publication.requested = true;
const response = await api.post(`${url}/applications/${createdApp.id}`, payload);
expect(response.statusCode).toBe(200);
expect(response.resource.publication).toMatchObject({
requested: true,
published: true,
});
done();
});
it("should 400 on update if not allowed fields changed", async done => {
const payload = { resource: cloneDeep(createdApp) as Application };
const entity = await appRepo.findOne({ id: createdApp.id });
payload.resource.api = cloneDeep(entity.api);
const response = await api.post(`${url}/applications/${createdApp.id}`, payload);
expect(response.statusCode).toBe(400);
done();
});
});
});
describe("Get applications", function () {
let firstApp: PublicApplicationObject;
let secondApp: PublicApplicationObject;
let thirdApp: PublicApplicationObject;
beforeAll(async done => {
const payload = { resource: cloneDeep(postPayload) };
firstApp = (await api.post(`${url}/applications`, payload)).resource;
secondApp = (await api.post(`${url}/applications`, payload)).resource;
thirdApp = (await api.post(`${url}/applications`, payload)).resource;
await publishApp(firstApp.id);
await publishApp(secondApp.id);
done();
});
it("should list published applications", async done => {
const response = await api.get(`${url}/applications`);
expect(response.statusCode).toBe(200);
const published = response.resources.filter(a => a.publication.published).length;
const unpublished = response.resources.filter(a => a.publication.unpublished).length;
expect(published).toBeGreaterThanOrEqual(2);
expect(unpublished).toEqual(0);
expect(response.resources.map(a => a.id)).toEqual(
expect.arrayContaining([firstApp.id, secondApp.id]),
);
done();
});
it("should return public object for published application to any user", async done => {
const response = await api.get(`${url}/applications/${firstApp.id}`, uuidv1());
expect(response.statusCode).toBe(200);
expect(response.resource.id).toEqual(firstApp.id);
expect(response.resource.api).toBeFalsy();
done();
});
it("should return public object for unpublished application to any user", async done => {
const response = await api.get(`${url}/applications/${thirdApp.id}`, uuidv1());
expect(response.statusCode).toBe(200);
expect(response.resource.id).toEqual(thirdApp.id);
expect(response.resource.api).toBeFalsy();
done();
});
it("should return whole object for published application to admin", async done => {
const response = await api.get(`${url}/applications/${firstApp.id}`);
expect(response.statusCode).toBe(200);
expect(response.resource.id).toEqual(firstApp.id);
expect(response.resource.api).toBeTruthy();
done();
});
it("should return whole object for unpublished application to admin", async done => {
const response = await api.get(`${url}/applications/${thirdApp.id}`);
expect(response.statusCode).toBe(200);
expect(response.resource.id).toEqual(thirdApp.id);
expect(response.resource.api).toBeTruthy();
done();
});
});
});
const postPayload = {
is_default: true,
company_id: null,
identity: {
code: "code",
name: "name",
icon: "icon",
description: "description",
website: "website",
categories: [],
compatibility: [],
},
api: {
hooks_url: "hooks_url",
allowed_ips: "allowed_ips",
},
access: {
read: ["messages"],
write: ["messages"],
delete: ["messages"],
hooks: ["messages"],
},
display: {
twake: {
version: 1,
files: {
editor: {
preview_url: "string", //Open a preview inline (iframe)
edition_url: "string", //Url to edit the file (full screen)
extensions: [], //Main extensions app can read
// if file was created by the app, then the app is able to edit with or without extension
empty_files: [
{
url: "string", // "https://[...]/empty.docx";
filename: "string", // "Untitled.docx";
name: "string", // "Word Document";
},
],
},
actions: [
//List of action that can apply on a file
{
name: "string",
id: "string",
},
],
},
//Chat plugin
chat: {
input: true,
commands: [
{
command: "string", // my_app mycommand
description: "string",
},
],
actions: [
//List of action that can apply on a message
{
name: "string",
id: "string",
},
],
},
//Allow app to appear as a bot user in direct chat
direct: false,
//Display app as a standalone application in a tab
tab: { url: "string" },
//Display app as a standalone application on the left bar
standalone: { url: "string" },
//Define where the app can be configured from
configuration: ["global", "channel"],
},
},
publication: {
requested: false, //Publication requested
},
};
@@ -1,118 +0,0 @@
import * as crypto from "crypto";
import { afterAll, beforeAll, describe, expect, it } from "@jest/globals";
import { FastifyInstance, FastifyPluginCallback, FastifyReply, FastifyRequest } from "fastify";
import { init, TestPlatform } from "../setup";
import { TestDbService } from "../utils.prepare.db";
import { Api } from "../utils.api";
import { logger as log } from "../../../src/core/platform/framework";
let signingSecret = "";
describe("Application events", () => {
const url = "/internal/services/applications/v1";
let platform: TestPlatform;
let api: Api;
let appId: string;
beforeAll(async ends => {
platform = await init(undefined, testAppHookRoute);
await platform.database.getConnector().drop();
await TestDbService.getInstance(platform, true);
api = new Api(platform);
postPayload.company_id = platform.workspace.company_id;
const createdApplication = await api.post("/internal/services/applications/v1/applications", {
resource: postPayload,
});
appId = createdApplication.resource.id;
signingSecret = createdApplication.resource.api.private_key;
ends();
afterAll(done => {
platform.tearDown().then(() => done());
});
});
it("Should 200 on sending well formed event", async done => {
const payload = {
company_id: platform.workspace.company_id,
workspace_id: platform.workspace.workspace_id,
type: "some type",
name: "name",
content: {},
};
const response = await api.post(`${url}/applications/${appId}/event`, payload);
expect(response.statusCode).toBe(200);
expect(response.resource).toMatchObject({ a: "b" });
done();
});
});
const postPayload = {
is_default: false,
company_id: null,
identity: {
code: "code",
name: "name",
icon: "icon",
description: "description",
website: "website",
categories: [],
compatibility: [],
},
api: {
hooks_url: "http://localhost:3000/test/appHook",
allowed_ips: "allowed_ips",
},
access: {
read: ["messages"],
write: ["messages"],
delete: ["messages"],
hooks: ["messages"],
},
display: {},
publication: {
requested: true,
},
};
const testAppHookRoute = (fastify: FastifyInstance) => {
const routes: FastifyPluginCallback = (fastify: FastifyInstance, options, next) => {
fastify.route({
method: "POST",
url: "/test/appHook",
handler: (request: FastifyRequest, reply: FastifyReply): Promise<any> => {
const signature = request.headers["x-twake-signature"];
if (!signature) {
reply.status(403);
reply.send({ error: "Signature is missing" });
return undefined;
}
const expectedSignature = crypto
.createHmac("sha256", signingSecret)
.update(JSON.stringify(request.body))
.digest("hex");
if (expectedSignature != signature) {
reply.status(403);
reply.send({ error: "Wrong signature" });
return undefined;
}
log.debug({ signatureMatched: expectedSignature == signature });
return Promise.resolve({ a: "b" });
},
});
next();
};
fastify.register(routes);
};
@@ -1,141 +0,0 @@
import { afterAll, beforeAll, describe, expect, it } from "@jest/globals";
import { init, TestPlatform } from "../setup";
import { TestDbService } from "../utils.prepare.db";
import { Api } from "../utils.api";
import { logger as log } from "../../../src/core/platform/framework";
import { ApplicationLoginResponse } from "../../../src/services/applicationsapi/web/types";
describe("Applications", () => {
let platform: TestPlatform;
let testDbService: TestDbService;
let api: Api;
let appId: string;
let private_key: string;
let accessToken: ApplicationLoginResponse["access_token"];
beforeAll(async ends => {
platform = await init();
await platform.database.getConnector().drop();
testDbService = await TestDbService.getInstance(platform, true);
api = new Api(platform);
postPayload.company_id = platform.workspace.company_id;
const createdApplication = await api.post("/internal/services/applications/v1/applications", {
resource: postPayload,
});
appId = createdApplication.resource.id;
private_key = createdApplication.resource.api.private_key;
ends();
});
afterAll(done => {
platform.tearDown().then(() => done());
});
describe("Login", function () {
it("Should be ok on valid token", async done => {
expect(appId).toBeTruthy();
const response = await api.post("/api/console/v1/login", {
id: appId,
secret: private_key,
});
expect(response.statusCode).toBe(200);
const resource = (await response.json()).resource as ApplicationLoginResponse;
expect(resource).toMatchObject({
access_token: {
time: expect.any(Number),
expiration: expect.any(Number),
refresh_expiration: expect.any(Number),
value: expect.any(String),
refresh: expect.any(String),
type: expect.any(String),
},
});
accessToken = resource.access_token;
done();
});
});
describe("Get myself", function () {
it("Should be 401 on invalid token", async done => {
const response = await platform.app.inject({
method: "GET",
url: "/api/console/v1/me",
headers: {
authorization: `Bearer ${accessToken.value + "!!"}`,
},
});
log.debug(response.json());
expect(response.statusCode).toBe(401);
done();
});
it("Should be 403 on auth by users (not company) token", async done => {
const userToken = await platform.auth.getJWTToken();
const response = await platform.app.inject({
method: "GET",
url: "/api/console/v1/me",
headers: {
authorization: `Bearer ${userToken}`,
},
});
log.debug(response.json());
expect(response.statusCode).toBe(403);
done();
});
it("Should be ok on valid token", async done => {
const response = await platform.app.inject({
method: "GET",
url: "/api/console/v1/me",
headers: {
authorization: `Bearer ${accessToken.value}`,
},
});
expect(response.statusCode).toBe(200);
const resource = (await response.json()).resource;
log.debug(resource);
expect(resource).toMatchObject(postPayload);
done();
});
});
});
const postPayload = {
is_default: false,
company_id: null,
identity: {
code: "code",
name: "name",
icon: "icon",
description: "description",
website: "website",
categories: [],
compatibility: [],
},
api: {
hooks_url: "hooks_url",
allowed_ips: "allowed_ips",
},
access: {
read: ["messages"],
write: ["messages"],
delete: ["messages"],
hooks: ["messages"],
},
display: {},
publication: {
requested: true,
},
};
@@ -1,165 +0,0 @@
import "reflect-metadata";
import { afterAll, beforeAll, describe, expect, it } from "@jest/globals";
import { init, TestPlatform } from "../setup";
import { createMessage, createParticipant, e2e_createThread } from "./utils";
import { MessageFile } from "../../../src/services/messages/entities/message-files";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import fs from "fs";
import formAutoContent from "form-auto-content";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import uuid from "node-uuid";
import { ChannelUtils, get as getChannelUtils } from "../channels/utils";
import gr from "../../../src/services/global-resolver";
import User from "../../../src/services/user/entities/user";
import { WorkspaceExecutionContext } from "../../../src/services/channels/types";
describe("Search files", () => {
const filesUrl = "/internal/services/files/v1";
const messagesUrl = "/internal/services/messages/v1";
let platform: TestPlatform;
let channelUtils: ChannelUtils;
beforeAll(async () => {
platform = await init({
services: ["webserver", "database", "storage", "message-queue", "files", "previews"],
});
await platform.database.getConnector().drop();
channelUtils = getChannelUtils(platform);
});
afterAll(async done => {
await platform?.tearDown();
platform = null;
done();
});
const files = [
"../files/assets/sample.png",
"../files/assets/sample.gif",
"../files/assets/sample.pdf",
"../files/assets/sample.doc",
"../files/assets/sample.zip",
].map(p => `${__dirname}/${p}`);
function getContext(user?: User): WorkspaceExecutionContext {
return {
workspace: platform.workspace,
user: user || platform.currentUser,
};
}
it("should return uploaded files", async done => {
let channel = channelUtils.getChannel();
channel = (await gr.services.channels.channels.save(channel, {}, getContext())).entity;
const channelId = channel.id;
const uploadedFiles = [];
for (const i in files) {
const file = files[i];
const form = formAutoContent({ file: fs.createReadStream(file) });
form.headers["authorization"] = `Bearer ${await platform.auth.getJWTToken()}`;
const uploadedFile = await platform.app.inject({
method: "POST",
url: `${filesUrl}/companies/${platform.workspace.company_id}/files?thumbnail_sync=1`,
...form,
});
const resource = uploadedFile.json().resource;
const messageFile: Partial<MessageFile> = {
id: uuid.v1(),
company_id: platform.workspace.company_id,
metadata: {
source: "internal",
external_id: {
company_id: platform.workspace.company_id,
id: resource.id,
},
...resource.metadata,
},
};
await e2e_createThread(
platform,
[
createParticipant(
{
type: "channel",
id: channelId,
},
platform,
),
],
createMessage({ text: "Some message", files: [messageFile] }),
);
uploadedFiles.push(uploadedFile.json().resource);
}
await new Promise(r => setTimeout(r, 2000));
let resources = await search("sample");
expect(resources.length).toEqual(5);
resources = await search("sample", { extension: "png" });
expect(resources.length).toEqual(1);
resources = await search("sample", { is_file: true });
expect(resources.length).toEqual(3);
resources = await search("sample", { is_media: true });
expect(resources.length).toEqual(2);
resources = await search("sam");
expect(resources.length).toEqual(5);
done();
});
async function search(
searchString: string,
options?: {
company_id?: string;
workspace_id?: string;
channel_id?: string;
limit?: number;
sender?: string;
is_file?: boolean;
is_media?: boolean;
extension?: string;
},
): Promise<any[]> {
const jwtToken = await platform.auth.getJWTToken();
const query: any = options || {};
const response = await platform.app.inject({
method: "GET",
url: `${messagesUrl}/companies/${platform.workspace.company_id}/files/search`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
query: {
...query,
q: searchString,
},
});
expect(response.statusCode).toBe(200);
const json = response.json();
expect(json).toMatchObject({ resources: expect.any(Array) });
const resources = json.resources;
return resources;
}
});
function getContext(platform: TestPlatform) {
return {
company: { id: platform.workspace.company_id },
user: { id: platform.currentUser.id },
};
}
@@ -1,364 +0,0 @@
import "reflect-metadata";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "@jest/globals";
import { init, TestPlatform } from "../setup";
import { ResourceUpdateResponse } from "../../../src/utils/types";
import { deserialize } from "class-transformer";
import { Thread } from "../../../src/services/messages/entities/threads";
import { createMessage, e2e_createThread } from "./utils";
import { MessageFile } from "../../../src/services/messages/entities/message-files";
import { Message } from "../../../src/services/messages/entities/messages";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import fs from "fs";
import formAutoContent from "form-auto-content";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import uuid, { v1 } from "node-uuid";
describe("The Messages Files feature", () => {
const url = "/internal/services/messages/v1";
let platform: TestPlatform;
beforeEach(async () => {
platform = await init({
services: [
"webserver",
"database",
"applications",
"search",
"storage",
"message-queue",
"user",
"search",
"files",
"websocket",
"messages",
"auth",
"realtime",
"channels",
"counter",
"statistics",
"platform-services",
],
});
});
afterEach(async () => {
await platform.tearDown();
});
describe("On user send files", () => {
it("did add the files when full information is given (external source)", async done => {
const file: MessageFile = {
cache: { channel_id: "", company_id: "", user_id: "", workspace_id: "" },
company_id: "",
created_at: 0,
id: "",
metadata: {
source: "linshare",
external_id: "1234",
name: "My LinShare File",
thumbnails: [],
},
};
const response = await e2e_createThread(
platform,
[],
createMessage({ text: "Some message", files: [file] }),
);
const result: ResourceUpdateResponse<Thread & { message: Message }> = deserialize(
ResourceUpdateResponse,
response.body,
);
expect(result.resource.message.files.length).toBe(1);
expect(result.resource.message.files[0].id).not.toBeFalsy();
expect(result.resource.message.files[0].message_id).not.toBeFalsy();
expect(result.resource.message.files[0].metadata.external_id).toBe("1234");
expect(result.resource.message.files[0].metadata.source).toBe("linshare");
done();
});
it("did not deduplicate files", async done => {
const file: MessageFile = {
cache: { channel_id: "", company_id: "", user_id: "", workspace_id: "" },
company_id: "",
created_at: 0,
id: "",
metadata: {
source: "linshare",
external_id: "1234",
name: "My LinShare File",
thumbnails: [],
},
};
const file2: MessageFile = {
cache: { channel_id: "", company_id: "", user_id: "", workspace_id: "" },
company_id: "",
created_at: 0,
id: "",
metadata: {
source: "linshare2",
external_id: "5678",
name: "My LinShare 2 File",
thumbnails: [],
},
};
const response = await e2e_createThread(
platform,
[],
createMessage({ text: "Some message", files: [file] }),
);
const result: ResourceUpdateResponse<Thread & { message: Message }> = deserialize(
ResourceUpdateResponse,
response.body,
);
const message = result.resource.message;
const firstFileId = message.files[0].id;
message.files.push(file2);
const messageUpdatedRaw = await platform.app.inject({
method: "POST",
url: `${url}/companies/${platform.workspace.company_id}/threads/${message.thread_id}/messages/${message.id}`,
headers: {
authorization: `Bearer ${await platform.auth.getJWTToken()}`,
},
payload: {
resource: message,
},
});
const messageUpdated: ResourceUpdateResponse<Message> = deserialize(
ResourceUpdateResponse,
messageUpdatedRaw.body,
);
expect(messageUpdated.resource.files.length).toBe(2);
expect(messageUpdated.resource.files.filter(f => f.id === firstFileId).length).toBe(1);
done();
});
});
});
describe("List user files", () => {
const filesUrl = "/internal/services/files/v1";
const messagesUrl = "/internal/services/messages/v1";
let platform: TestPlatform;
beforeAll(async () => {
platform = await init({
services: ["webserver", "database", "storage", "message-queue", "files", "previews"],
});
await platform.database.getConnector().drop();
});
afterAll(async done => {
await platform?.tearDown();
platform = null;
done();
});
const files = [
"../files/assets/sample.png",
"../files/assets/sample.gif",
"../files/assets/sample.pdf",
"../files/assets/sample.doc",
"../files/assets/sample.zip",
].map(p => `${__dirname}/${p}`);
it("should return uploaded files", async done => {
const jwtToken = await platform.auth.getJWTToken();
const uploadedFiles = [];
for (const i in files) {
const file = files[i];
const form = formAutoContent({ file: fs.createReadStream(file) });
form.headers["authorization"] = `Bearer ${await platform.auth.getJWTToken()}`;
const uploadedFile = await platform.app.inject({
method: "POST",
url: `${filesUrl}/companies/${platform.workspace.company_id}/files?thumbnail_sync=1`,
...form,
});
expect(uploadedFile.statusCode).toBe(200);
const resource = uploadedFile.json().resource;
const messageFile: MessageFile = {
cache: { channel_id: "", company_id: "", user_id: "", workspace_id: "" },
created_at: 0,
id: uuid.v1(),
company_id: platform.workspace.company_id,
metadata: {
source: "internal",
external_id: {
company_id: platform.workspace.company_id,
id: resource.id,
},
...resource.metadata,
},
};
await e2e_createThread(
platform,
[],
createMessage({ text: "Some message", files: [messageFile] }),
);
uploadedFiles.push(uploadedFile.json().resource);
}
function checkResource(resource) {
expect(resource).toMatchObject({
company_id: expect.any(String),
id: expect.any(String),
created_at: expect.any(Number),
metadata: expect.any(Object),
});
}
let response = await platform.app.inject({
method: "GET",
url: `${messagesUrl}/companies/${platform.workspace.company_id}/files?type=user_upload&limit=3`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
});
await new Promise(resolve => setTimeout(resolve, 1000));
expect(response.statusCode).toBe(200);
let resources = response.json().resources;
expect(resources.length).toBe(3);
resources.forEach(checkResource);
const nextPageToken = response.json().next_page_token;
response = await platform.app.inject({
method: "GET",
url: `${messagesUrl}/companies/${platform.workspace.company_id}/files?type=user_upload&page_token=${nextPageToken}limit=100`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
});
await new Promise(resolve => setTimeout(resolve, 1000));
expect(response.statusCode).toBe(200);
resources = response.json().resources;
expect(resources.length).toBe(5);
expect(response.json().resources[0]).toMatchObject({
company_id: expect.any(String),
id: expect.any(String),
created_at: expect.any(Number),
metadata: expect.any(Object),
user: expect.any(Object),
context: expect.any(Object),
});
resources.forEach(checkResource);
done();
});
it("should return downloaded files", async done => {
const jwtToken = await platform.auth.getJWTToken({ sub: v1() });
const uploadedFiles = [];
for (const i in files) {
const file = files[i];
const form = formAutoContent({ file: fs.createReadStream(file) });
form.headers["authorization"] = `Bearer ${await platform.auth.getJWTToken()}`;
const uploadedFile = await platform.app.inject({
method: "POST",
url: `${filesUrl}/companies/${platform.workspace.company_id}/files?thumbnail_sync=1`,
...form,
});
const resource = uploadedFile.json().resource;
const messageFile: MessageFile = {
cache: { channel_id: "", company_id: "", user_id: "", workspace_id: "" },
created_at: 0,
id: uuid.v1(),
company_id: platform.workspace.company_id,
metadata: {
source: "internal",
external_id: {
company_id: platform.workspace.company_id,
id: resource.id,
},
...resource.metadata,
},
};
const thread = await e2e_createThread(
platform,
[],
createMessage({ text: "Some message", files: [messageFile] }),
);
uploadedFiles.push(uploadedFile.json().resource);
await platform.app.inject({
method: "POST",
url: `${messagesUrl}/companies/${platform.workspace.company_id}/threads/${
thread.json().resource.message.thread_id
}/messages/${thread.json().resource.message.id}/download/${
thread.json().resource.message.files[0].id
}`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
});
}
await new Promise(resolve => setTimeout(resolve, 1000));
const response = await platform.app.inject({
method: "GET",
url: `${messagesUrl}/companies/${platform.workspace.company_id}/files?type=user_download`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
});
await new Promise(resolve => setTimeout(resolve, 1000));
expect(response.statusCode).toBe(200);
expect(response.json().resources.length).toBe(5);
expect(response.json().resources[0]).toMatchObject({
company_id: expect.any(String),
id: expect.any(String),
created_at: expect.any(Number),
metadata: expect.any(Object),
user: expect.any(Object),
context: expect.any(Object),
});
done();
});
});
function getContext(platform: TestPlatform) {
return {
company: { id: platform.workspace.company_id },
user: { id: platform.currentUser.id },
};
}
@@ -1,199 +0,0 @@
import "reflect-metadata";
import { afterEach, describe, expect, it } from "@jest/globals";
import { init, TestPlatform } from "../setup";
import {
ResourceListResponse,
ResourceUpdateResponse,
User,
Workspace,
} from "../../../src/utils/types";
import { deserialize } from "class-transformer";
import { ParticipantObject, Thread } from "../../../src/services/messages/entities/threads";
import {
createMessage,
createParticipant,
e2e_createChannel,
e2e_createMessage,
e2e_createThread,
} from "./utils";
import { Message } from "../../../src/services/messages/entities/messages";
import { v1 as uuidv1 } from "uuid";
import { MessageWithReplies } from "../../../src/services/messages/types";
import { TestDbService } from "../utils.prepare.db";
import gr from "../../../src/services/global-resolver";
import { ChannelVisibility, WorkspaceExecutionContext } from "../../../src/services/channels/types";
import { ChannelSaveOptions } from "../../../src/services/channels/web/types";
import { ChannelUtils, get as getChannelUtils } from "../channels/utils";
describe("The Messages feature", () => {
const url = "/internal/services/messages/v1";
let platform: TestPlatform;
let testDbService: TestDbService;
let channelUtils: ChannelUtils;
function getContext(user?: User): WorkspaceExecutionContext {
return {
workspace: platform.workspace,
user: user || platform.currentUser,
};
}
beforeAll(async () => {
platform = await init({
services: [
"webserver",
"database",
"search",
"storage",
"message-queue",
"applications",
"user",
"websocket",
"webserver",
"messages",
"files",
"auth",
"search",
"realtime",
"channels",
"counter",
"statistics",
"platform-services",
],
});
await gr.database.getConnector().drop();
channelUtils = getChannelUtils(platform);
});
afterEach(async () => {
await platform.tearDown();
});
describe("On user use messages in a thread", () => {
it("should create a message in a thread", async () => {
const response = await e2e_createThread(
platform,
[],
createMessage({ text: "Initial thread message" }),
);
const result: ResourceUpdateResponse<Thread> = deserialize(
ResourceUpdateResponse,
response.body,
);
const threadId = result.resource.id;
await e2e_createMessage(platform, threadId, createMessage({ text: "Reply 1" }));
await e2e_createMessage(platform, threadId, createMessage({ text: "Reply 2" }));
const jwtToken = await platform.auth.getJWTToken();
const listResponse = await platform.app.inject({
method: "GET",
url: `${url}/companies/${platform.workspace.company_id}/threads/${threadId}/messages`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
});
const listResult: ResourceListResponse<Thread> = deserialize(
ResourceListResponse,
listResponse.body,
);
expect(listResponse.statusCode).toBe(200);
expect(listResult.resources.length).toBe(3);
});
});
describe("Inbox", () => {
it("Should get recent user messages", async done => {
const directChannelIn = channelUtils.getDirectChannel();
const members = [platform.currentUser.id, uuidv1()];
const directWorkspace: Workspace = {
company_id: platform.workspace.company_id,
workspace_id: ChannelVisibility.DIRECT,
};
await Promise.all([
gr.services.channels.channels.save<ChannelSaveOptions>(
directChannelIn,
{
members,
},
{ ...getContext(), ...{ workspace: directWorkspace } },
),
]);
const recipient: ParticipantObject = {
created_at: 0,
created_by: "",
type: "channel",
company_id: directChannelIn.company_id,
workspace_id: "direct",
id: directChannelIn.id,
};
for (let i = 0; i < 6; i++) {
const response = await e2e_createThread(
platform,
[recipient],
createMessage({ text: `Initial thread message ${i}` }),
);
const result: ResourceUpdateResponse<Thread> = deserialize(
ResourceUpdateResponse,
response.body,
);
const threadId = result.resource.id;
const replies = [];
for (let j = 0; j < 3; j++) {
replies.push(
e2e_createMessage(
platform,
threadId,
createMessage({ text: `Reply ${j} to message ${i}` }),
),
);
}
await Promise.all(replies);
}
const jwtToken = await platform.auth.getJWTToken({ sub: members[0] });
const response = await platform.app.inject({
method: "GET",
url: `${url}/companies/${platform.workspace.company_id}/inbox?limit=5`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
});
expect(response.statusCode).toEqual(200);
const inbox: ResourceListResponse<MessageWithReplies> = deserialize(
ResourceListResponse,
response.body,
);
expect(inbox.resources.length).toEqual(5);
for (const resource of inbox.resources) {
expect(resource).toMatchObject({
id: expect.any(String),
thread_id: expect.any(String),
created_at: expect.any(Number),
updated_at: expect.any(Number),
user_id: platform.currentUser.id,
application_id: null,
text: expect.any(String),
cache: {
company_id: directChannelIn.company_id,
channel_id: directChannelIn.id,
},
});
}
done();
});
});
});
@@ -1,264 +0,0 @@
import { afterAll, beforeAll, describe, expect, it } from "@jest/globals";
import { init, TestPlatform } from "../setup";
import { TestDbService } from "../utils.prepare.db";
import { v1 as uuidv1 } from "uuid";
import { createMessage, e2e_createChannel, e2e_createMessage, e2e_createThread } from "./utils";
import { ResourceUpdateResponse } from "../../../src/utils/types";
import { ParticipantObject, Thread } from "../../../src/services/messages/entities/threads";
import { deserialize } from "class-transformer";
import { Channel } from "../../../src/services/channels/entities";
import { ChannelUtils, get as getChannelUtils } from "../channels/utils";
import { MessageFile } from "../../../src/services/messages/entities/message-files";
import gr from "../../../src/services/global-resolver";
describe("The /messages API", () => {
const url = "/internal/services/messages/v1";
let platform: TestPlatform;
let channelUtils: ChannelUtils;
beforeAll(async ends => {
platform = await init({
services: [
"database",
"search",
"message-queue",
"websocket",
"webserver",
"user",
"auth",
"applications",
"storage",
"counter",
"workspaces",
"console",
"statistics",
"platform-services",
],
});
await platform.database.getConnector().drop();
channelUtils = getChannelUtils(platform);
const testDbService = new TestDbService(platform);
await testDbService.createCompany(platform.workspace.company_id);
const workspacePk = {
id: platform.workspace.workspace_id,
company_id: platform.workspace.company_id,
};
const workspacePk2 = {
id: uuidv1(),
company_id: uuidv1(),
};
await testDbService.createWorkspace(workspacePk);
const user = await testDbService.createUser([workspacePk], {});
platform.currentUser.id = user.id;
ends();
});
afterAll(async ends => {
platform && (await platform.tearDown());
platform = null;
ends();
});
describe("The GET /messages/?search=... route", () => {
it("Should find the searched messages", async done => {
// await testDbService.createWorkspace(workspacePk2);
const channel = await createChannel();
const participant = {
type: "channel",
id: channel.id,
company_id: platform.workspace.company_id,
workspace_id: platform.workspace.workspace_id,
} as ParticipantObject;
const firstThreadId = await createThread("First thread", [participant]);
await createReply(firstThreadId, "First reply of first thread");
await createReply(firstThreadId, "Second reply of first thread");
const secondThreadId = await createThread("Another thread", [participant]);
await createReply(secondThreadId, "First reply of second thread");
await createReply(secondThreadId, "Second reply of second thread is also a message");
//Wait for indexation to happen
await new Promise(r => setTimeout(r, 3000));
let resources = await search("Reply");
expect(resources.length).toEqual(4);
resources = await search("fdfsd");
expect(resources.length).toEqual(0);
resources = await search("first");
expect(resources.length).toEqual(4);
resources = await search("second");
expect(resources.length).toEqual(3);
resources = await search("another");
expect(resources.length).toEqual(1);
resources = await search("also");
expect(resources.length).toEqual(1);
resources = await search("of");
expect(resources.length).toEqual(4);
resources = await search("a");
//sleep 1s
await new Promise(r => setTimeout(r, 2000));
expect(resources.length).toEqual(1);
done();
});
it("Filter out messages from channels we are not member of", async done => {
const anotherUserId = uuidv1();
const channel = await e2e_createChannel(platform, [platform.currentUser.id, anotherUserId]);
const anotherChannel = await e2e_createChannel(platform, [anotherUserId], anotherUserId); //Test user is not the owner
const participant = {
type: "channel",
id: channel.resource.id,
company_id: channel.resource.company_id,
workspace_id: channel.resource.workspace_id,
} as ParticipantObject;
const participant2 = {
type: "channel",
id: anotherChannel.resource.id,
company_id: anotherChannel.resource.company_id,
workspace_id: anotherChannel.resource.workspace_id,
} as ParticipantObject;
const file = new MessageFile();
file.metadata = { external_id: undefined, source: undefined, name: "test" };
const firstThreadId = await createThread("Filtered thread", [participant]);
await createReply(firstThreadId, "Filtered message 1-1");
await createReply(firstThreadId, "Filtered message 1-2");
await createReply(firstThreadId, "Filtered message 1-3");
await createReply(firstThreadId, "Filtered message 1-4", { files: [file] });
const secondThreadId = await createThread("Filtered thread 2", [participant2], anotherUserId);
await createReply(secondThreadId, "Filtered message 2-1");
await createReply(secondThreadId, "Filtered message 2-2");
await createReply(secondThreadId, "Filtered message 2-3");
await createReply(secondThreadId, "Filtered message 2-4");
const thirdThreadId = await createThread("Filtered thread 3", [participant]);
await createReply(thirdThreadId, "Filtered message 3-1");
await createReply(thirdThreadId, "Filtered message 3-2", { userId: anotherUserId });
await createReply(thirdThreadId, "Filtered message 3-3", { userId: anotherUserId });
await createReply(thirdThreadId, "Filtered message 3-4", {
userId: anotherUserId,
files: [file],
});
//Wait for indexation to happen
await new Promise(r => setTimeout(r, 3000));
// no limit
const resources0 = await search("Filtered", { limit: 10000 });
expect(resources0.length).toEqual(10);
const resources = await search("Filtered", { limit: 9 });
expect(resources.length).toEqual(9);
// check for the empty result set
const resources2 = await search("Nothing", { limit: 10 });
expect(resources2.length).toEqual(0);
// check for the user
const resources3 = await search("Filtered", { sender: anotherUserId });
expect(resources3.length).toEqual(3);
// check for the files
const resources4 = await search("Filtered", { has_files: true });
expect(resources4.length).toEqual(2);
// check for the user and files
const resources5 = await search("Filtered", { sender: anotherUserId, has_files: true });
expect(resources5.length).toEqual(1);
done();
});
});
async function createChannel(userId = platform.currentUser.id): Promise<Channel> {
const channel = channelUtils.getChannel(userId);
const creationResult = await gr.services.channels.channels.save(
channel,
{},
channelUtils.getContext({ id: userId }),
);
return creationResult.entity;
}
async function createThread(text, participants: ParticipantObject[], owner?: string) {
const response = await e2e_createThread(
platform,
participants,
createMessage({ text: text, user_id: owner }),
owner,
);
const result: ResourceUpdateResponse<Thread> = deserialize(
ResourceUpdateResponse,
response.body,
);
return result.resource.id;
}
async function createReply(threadId, text, options?: { userId?: string; files?: MessageFile[] }) {
const cr = options?.userId ? { currentUser: { id: options?.userId } } : undefined;
const message = { text, ...(options?.files ? { files: options.files } : {}) };
return e2e_createMessage(platform, threadId, createMessage(message, cr as TestPlatform));
}
async function search(
searchString: string,
options?: {
company_id?: string;
workspace_id?: string;
channel_id?: string;
limit?: number;
sender?: string;
has_files?: boolean;
},
): Promise<any[]> {
const jwtToken = await platform.auth.getJWTToken();
const query: any = options || {};
const response = await platform.app.inject({
method: "GET",
// url: `${url}/companies/${platform.workspace.company_id}/woskpaces/`,
url: `${url}/companies/${platform.workspace.company_id}/search`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
query: {
...query,
q: searchString,
},
});
expect(response.statusCode).toBe(200);
const json = response.json();
expect(json).toMatchObject({ resources: expect.any(Array) });
const resources = json.resources;
return resources;
}
});
@@ -1,249 +0,0 @@
import "reflect-metadata";
import { afterEach, beforeEach, describe, expect, it } from "@jest/globals";
import { init, TestPlatform } from "../setup";
import { ResourceUpdateResponse } from "../../../src/utils/types";
import { deserialize } from "class-transformer";
import { v1 as uuidv1, v4 as uuidv4 } from "uuid";
import { Thread } from "../../../src/services/messages/entities/threads";
import { createMessage, createParticipant, e2e_createThread } from "./utils";
import gr from "../../../src/services/global-resolver";
describe("The Messages Threads feature", () => {
const url = "/internal/services/messages/v1";
let platform: TestPlatform;
beforeEach(async () => {
platform = await init({
services: [
"webserver",
"database",
"applications",
"search",
"storage",
"message-queue",
"user",
"search",
"files",
"websocket",
"messages",
"auth",
"realtime",
"channels",
"counter",
"statistics",
"platform-services",
],
});
});
afterEach(async () => {
await platform.tearDown();
});
describe("On user manage threads", () => {
it("should create new thread", async done => {
const response = await e2e_createThread(
platform,
[
createParticipant(
{
type: "user",
id: platform.currentUser.id,
},
platform,
),
],
createMessage(
{
text: "Hello!",
},
platform,
),
);
const result: ResourceUpdateResponse<Thread> = deserialize(
ResourceUpdateResponse,
response.body,
);
expect(response.statusCode).toBe(200);
expect(result.resource?.created_by).toBe(platform.currentUser.id);
expect(result.resource.participants.length).toBe(1);
expect(result.resource.participants[0]).toMatchObject({
type: "user",
id: platform.currentUser.id,
created_by: platform.currentUser.id,
});
expect(result.resource.participants[0].created_at).toBeDefined();
done();
});
it("should enforce requester in thread participants", async done => {
const response = await e2e_createThread(
platform,
[
createParticipant(
{
type: "user",
id: uuidv1(),
},
platform,
),
],
createMessage(
{
text: "Hello!",
},
platform,
),
);
const result: ResourceUpdateResponse<Thread> = deserialize(
ResourceUpdateResponse,
response.body,
);
expect(response.statusCode).toBe(200);
expect(result.resource).toMatchObject({
created_by: platform.currentUser.id,
});
expect(result.resource.participants.length).toBe(2);
expect(
result.resource.participants.filter(p => p.id === platform.currentUser.id)[0],
).toMatchObject({
type: "user",
id: platform.currentUser.id,
});
done();
});
it("should update thread participants when add participant", async done => {
//Create thread
const thread = await gr.services.messages.threads.save(
{
id: undefined,
participants: [
{
type: "user",
id: platform.currentUser.id,
company_id: platform.workspace.company_id,
},
],
},
{
message: createMessage(
{
text: "Hello!",
},
platform,
),
},
getContext(platform),
);
const jwtToken = await platform.auth.getJWTToken();
const response = await platform.app.inject({
method: "POST",
url: `${url}/companies/${platform.workspace.company_id}/threads/${thread.entity.id}`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
payload: {
resource: {},
options: {
participants: {
add: [
{
type: "user",
id: uuidv1(),
},
],
},
},
},
});
const result: ResourceUpdateResponse<Thread> = deserialize(
ResourceUpdateResponse,
response.body,
);
expect(response.statusCode).toBe(200);
expect(result.resource.participants.length).toBe(2);
done();
});
it("should update thread participants when remove participant", async done => {
//Create thread
const thread = await gr.services.messages.threads.save(
{
id: undefined,
participants: [
{
type: "user",
id: platform.currentUser.id,
company_id: platform.workspace.company_id,
},
{
type: "channel",
id: uuidv4(),
workspace_id: platform.workspace.workspace_id,
company_id: platform.workspace.company_id,
},
],
},
{
message: createMessage(
{
text: "Hello!",
},
platform,
),
},
getContext(platform),
);
const jwtToken = await platform.auth.getJWTToken();
const response = await platform.app.inject({
method: "POST",
url: `${url}/companies/${platform.workspace.company_id}/threads/${thread.entity.id}`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
payload: {
resource: {},
options: {
participants: {
remove: [
{
type: "user",
id: platform.currentUser.id,
},
],
},
},
},
});
const result: ResourceUpdateResponse<Thread> = deserialize(
ResourceUpdateResponse,
response.body,
);
expect(response.statusCode).toBe(200);
expect(result.resource.participants.length).toBe(1);
done();
});
});
});
function getContext(platform: TestPlatform) {
return {
company: { id: platform.workspace.company_id },
user: { id: platform.currentUser.id },
};
}
@@ -1,143 +0,0 @@
import "reflect-metadata";
import { afterEach, beforeEach, describe, expect, it } from "@jest/globals";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import io from "socket.io-client";
import { init, TestPlatform } from "../setup";
import gr from "../../../src/services/global-resolver";
describe("The Bookmarks Realtime feature", () => {
const url = "/internal/services/messages/v1";
let platform: TestPlatform;
let socket: SocketIOClient.Socket;
beforeEach(async () => {
platform = await init({
services: [
"webserver",
"database",
"search",
"storage",
"message-queue",
"files",
"user",
"websocket",
"webserver",
"messages",
"applications",
"auth",
"search",
"realtime",
"channels",
"counter",
"statistics",
"platform-services",
],
});
});
afterEach(async () => {
await platform.tearDown();
platform = null;
});
function connect() {
socket = io.connect("http://localhost:3000", { path: "/socket" });
socket.connect();
}
describe("On bookmark creation", () => {
it("should notify the client", async done => {
const jwtToken = await platform.auth.getJWTToken();
const roomToken = "twake";
connect();
socket.on("connect", () => {
socket
.emit("authenticate", { token: jwtToken })
.on("authenticated", () => {
socket.on("realtime:join:error", () => done(new Error("Should not occur")));
socket.on("realtime:join:success", async () => {
await gr.services.messages.userBookmarks.save(
{
company_id: platform.workspace.company_id,
user_id: platform.currentUser.id,
name: "mybookmarksaved",
id: undefined,
},
getContext(platform),
);
});
socket.on("realtime:resource", (event: any) => {
expect(event.type).toEqual("user_message_bookmark");
expect(event.action).toEqual("saved");
expect(event.resource.name).toEqual("mybookmarksaved");
done();
});
socket.emit("realtime:join", {
name: `/companies/${platform.workspace.company_id}/messages/bookmarks`,
token: roomToken,
});
})
.on("unauthorized", () => {
done(new Error("Should not occur"));
});
});
});
});
describe("On bookmark removal", () => {
it("should notify the client", async done => {
const instance = await gr.services.messages.userBookmarks.save(
{
company_id: platform.workspace.company_id,
user_id: platform.currentUser.id,
name: "mybookmark",
id: undefined,
},
getContext(platform),
);
const jwtToken = await platform.auth.getJWTToken();
const roomToken = "twake";
connect();
socket.on("connect", () => {
socket
.emit("authenticate", { token: jwtToken })
.on("authenticated", () => {
socket.on("realtime:join:error", () => done(new Error("Should not occur")));
socket.on("realtime:join:success", async () => {
await gr.services.messages.userBookmarks.delete(
{
company_id: platform.workspace.company_id,
user_id: platform.currentUser.id,
id: instance.entity.id,
},
getContext(platform),
);
});
socket.on("realtime:resource", (event: any) => {
expect(event.type).toEqual("user_message_bookmark");
expect(event.action).toEqual("deleted");
done();
});
socket.emit("realtime:join", {
name: `/companies/${platform.workspace.company_id}/messages/bookmarks`,
token: roomToken,
});
})
.on("unauthorized", () => {
done(new Error("Should not occur"));
});
});
});
});
});
function getContext(platform: TestPlatform) {
return {
company: { id: platform.workspace.company_id },
user: { id: platform.currentUser.id },
};
}
@@ -1,217 +0,0 @@
import "reflect-metadata";
import { afterEach, beforeEach, describe, expect, it } from "@jest/globals";
import { init, TestPlatform } from "../setup";
import { UserMessageBookmark } from "../../../src/services/messages/entities/user-message-bookmarks";
import { ResourceListResponse, ResourceUpdateResponse } from "../../../src/utils/types";
import { deserialize } from "class-transformer";
import { v4 as uuidv4 } from "uuid";
import gr from "../../../src/services/global-resolver";
describe("The Messages User Bookmarks feature", () => {
const url = "/internal/services/messages/v1";
let platform: TestPlatform;
beforeEach(async () => {
platform = await init({
services: [
"webserver",
"database",
"search",
"files",
"storage",
"applications",
"message-queue",
"user",
"search",
"websocket",
"messages",
"auth",
"realtime",
"channels",
"counter",
"statistics",
"platform-services",
],
});
});
afterEach(async () => {
await platform.tearDown();
});
describe("On user manage bookmmarks", () => {
it("should create new bookmark", async done => {
const jwtToken = await platform.auth.getJWTToken();
const response = await platform.app.inject({
method: "POST",
url: `${url}/companies/${platform.workspace.company_id}/preferences/bookmarks/`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
payload: {
resource: {
name: "mybookmark",
},
},
});
const result: ResourceUpdateResponse<UserMessageBookmark> = deserialize(
ResourceUpdateResponse,
response.body,
);
expect(response.statusCode).toBe(200);
expect(result.resource).toMatchObject({
user_id: platform.currentUser.id,
name: "mybookmark",
});
const context = getContext(platform);
const list = await gr.services.messages.userBookmarks.list({
user_id: context.user.id,
company_id: context.company.id,
});
expect(list.getEntities().length).toBe(1);
done();
});
it("should prevent duplicated bookmark", async done => {
// const uuid = uuidv4();
const context = getContext(platform);
const data = await gr.services.messages.userBookmarks.save(
{
company_id: platform.workspace.company_id,
user_id: platform.currentUser.id,
name: "mybookmark",
test: "123",
},
context,
);
const uuid = data.entity.id;
const jwtToken = await platform.auth.getJWTToken();
const response = await platform.app.inject({
method: "POST",
url: `${url}/companies/${platform.workspace.company_id}/preferences/bookmarks/`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
payload: {
resource: {
name: "mybookmark",
},
},
});
const result: ResourceUpdateResponse<UserMessageBookmark> = deserialize(
ResourceUpdateResponse,
response.body,
);
expect(response.statusCode).toBe(200);
expect(result.resource).toMatchObject({
id: uuid,
user_id: platform.currentUser.id,
name: "mybookmark",
});
const list = await gr.services.messages.userBookmarks.list({
user_id: context.user.id,
company_id: context.company.id,
});
expect(list.getEntities().length).toBe(1);
done();
});
it("should remove bookmark", async done => {
const id = uuidv4();
const context = getContext(platform);
await gr.services.messages.userBookmarks.save(
{
id,
company_id: platform.workspace.company_id,
user_id: platform.currentUser.id,
name: "mybookmark",
},
context,
);
let list = await gr.services.messages.userBookmarks.list({
user_id: context.user.id,
company_id: context.company.id,
});
expect(list.getEntities().length).toBe(1);
const jwtToken = await platform.auth.getJWTToken();
const response = await platform.app.inject({
method: "DELETE",
url: `${url}/companies/${platform.workspace.company_id}/preferences/bookmarks/${id}`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
});
expect(response.statusCode).toBe(200);
list = await gr.services.messages.userBookmarks.list({
user_id: context.user.id,
company_id: context.company.id,
});
expect(list.getEntities().length).toBe(0);
done();
});
it("should list bookmarks", async done => {
const context = getContext(platform);
await gr.services.messages.userBookmarks.save(
{
id: uuidv4(),
company_id: platform.workspace.company_id,
user_id: platform.currentUser.id,
name: "mybookmark",
},
context,
);
const list = await gr.services.messages.userBookmarks.list({
user_id: context.user.id,
company_id: context.company.id,
});
expect(list.getEntities().length).toBe(1);
const jwtToken = await platform.auth.getJWTToken();
const response = await platform.app.inject({
method: "GET",
url: `${url}/companies/${platform.workspace.company_id}/preferences/bookmarks`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
});
const result: ResourceListResponse<UserMessageBookmark> = deserialize(
ResourceListResponse,
response.body,
);
expect(response.statusCode).toBe(200);
expect(result.resources.length).toBe(1);
expect(result.resources[0].name).toBe("mybookmark");
done();
});
});
});
function getContext(platform: TestPlatform) {
return {
company: { id: platform.workspace.company_id },
user: { id: platform.currentUser.id },
};
}
@@ -1,144 +0,0 @@
import "reflect-metadata";
import { afterEach, beforeEach, describe, expect, it } from "@jest/globals";
import { init, TestPlatform } from "../setup";
import { ResourceListResponse, ResourceUpdateResponse } from "../../../src/utils/types";
import { deserialize } from "class-transformer";
import { v4 as uuidv4 } from "uuid";
import { Thread } from "../../../src/services/messages/entities/threads";
import {
createMessage,
createParticipant,
e2e_createChannel,
e2e_createMessage,
e2e_createThread,
} from "./utils";
import { MessageWithReplies } from "../../../src/services/messages/types";
describe("The Messages feature", () => {
const url = "/internal/services/messages/v1";
let platform: TestPlatform;
beforeEach(async () => {
platform = await init({
services: [
"webserver",
"database",
"search",
"storage",
"files",
"applications",
"message-queue",
"user",
"websocket",
"messages",
"auth",
"search",
"realtime",
"channels",
"counter",
"statistics",
"platform-services",
],
});
});
afterEach(async () => {
await platform.tearDown();
});
describe("On user use messages in channel view", () => {
it("should create a message and retrieve it in channel view", async () => {
const channel = await e2e_createChannel(platform, [platform.currentUser.id]);
const response = await e2e_createThread(
platform,
[
createParticipant(
{
type: "channel",
id: channel.resource.id,
workspace_id: channel.resource.workspace_id,
company_id: channel.resource.company_id,
},
platform,
),
],
createMessage({ text: "Initial thread 1 message" }),
);
const result: ResourceUpdateResponse<Thread> = deserialize(
ResourceUpdateResponse,
response.body,
);
const threadId = result.resource.id;
await e2e_createMessage(platform, threadId, createMessage({ text: "Reply 1" }));
await e2e_createMessage(platform, threadId, createMessage({ text: "Reply 2" }));
await e2e_createThread(
platform,
[
createParticipant(
{
type: "channel",
id: channel.resource.id,
workspace_id: channel.resource.workspace_id,
company_id: channel.resource.company_id,
},
platform,
),
],
createMessage({ text: "Initial thread 2 message" }),
);
await e2e_createMessage(platform, threadId, createMessage({ text: "Reply 3" }));
await e2e_createThread(
platform,
[
createParticipant(
{
type: "channel",
id: channel.resource.id,
workspace_id: channel.resource.workspace_id,
company_id: channel.resource.company_id,
},
platform,
),
],
createMessage({ text: "Initial thread 3 message" }),
);
const jwtToken = await platform.auth.getJWTToken();
const listResponse = await platform.app.inject({
method: "GET",
url: `${url}/companies/${channel.resource.company_id}/workspaces/${channel.resource.workspace_id}/channels/${channel.resource.id}/feed?replies_per_thread=3&include_users=1`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
});
const listResult: ResourceListResponse<MessageWithReplies> = deserialize(
ResourceListResponse,
listResponse.body,
);
await new Promise(resolve => setTimeout(resolve, 5000));
expect(listResponse.statusCode).toBe(200);
expect(listResult.resources.length).toBe(3);
expect(listResult.resources[0].text).toBe("Initial thread 2 message");
expect(listResult.resources[1].text).toBe("Initial thread 1 message");
expect(listResult.resources[2].text).toBe("Initial thread 3 message");
expect(listResult.resources[0].stats.replies).toBe(1);
expect(listResult.resources[1].stats.replies).toBe(4); //Thread initial message + 3 replies
expect(listResult.resources[2].stats.replies).toBe(1);
expect(listResult.resources[1].last_replies.length).toBe(3); //We requested 3 replies per posts
expect(listResult.resources[1].last_replies[0].text).toBe("Reply 1"); //Check order is OK
expect(listResult.resources[1].last_replies[2].text).toBe("Reply 3");
});
});
});
@@ -1,114 +0,0 @@
import { deserialize } from "class-transformer";
import {
getInstance as getMessageInstance,
Message,
} from "../../../src/services/messages/entities/messages";
import { ParticipantObject } from "../../../src/services/messages/entities/threads";
import { Channel, ResourceCreateResponse } from "../../../src/utils/types";
import { TestPlatform } from "../setup";
const url = "/internal/services/messages/v1";
export const e2e_createChannel = async (
platform: TestPlatform,
members: string[],
owner?: string,
) => {
const jwtToken = await platform.auth.getJWTToken({ sub: owner || platform.currentUser.id });
const response = await platform.app.inject({
method: "POST",
url: `/internal/services/channels/v1/companies/${platform.workspace.company_id}/workspaces/direct/channels`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
payload: {
options: {
members,
},
resource: {
description: "A direct channel description",
visibility: "direct",
},
},
});
const channelCreateResult: ResourceCreateResponse<Channel> = deserialize(
ResourceCreateResponse,
response.body,
);
return channelCreateResult;
};
export const e2e_createThread = async (
platform: TestPlatform,
participants: ParticipantObject[],
message: Message,
owner?: string,
) => {
const jwtToken = await platform.auth.getJWTToken({ sub: owner || platform.currentUser.id });
const res = await platform.app.inject({
method: "POST",
url: `${url}/companies/${platform.workspace.company_id}/threads`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
payload: {
resource: {
participants: participants || [],
},
options: {
message: message,
},
},
});
await new Promise(resolve => setTimeout(resolve, 200));
return res;
};
export const e2e_createMessage = async (
platform: TestPlatform,
threadId: string,
message: Message,
) => {
const jwtToken = await platform.auth.getJWTToken(
message.user_id ? { sub: message.user_id } : undefined,
);
const res = await platform.app.inject({
method: "POST",
url: `${url}/companies/${platform.workspace.company_id}/threads/${threadId}/messages`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
payload: {
resource: message,
},
});
await new Promise(resolve => setTimeout(resolve, 200));
return res;
};
export const createMessage = (message: Partial<Message>, platform?: TestPlatform): Message => {
return getMessageInstance({
//Default values
created_at: new Date().getTime(),
user_id: platform?.currentUser.id || undefined,
...message,
});
};
export const createParticipant = (
participant: Partial<ParticipantObject>,
platform?: TestPlatform,
): ParticipantObject => {
return {
//Default values:
created_at: new Date().getTime(),
created_by: platform?.currentUser.id || "",
company_id: platform?.workspace.company_id || "",
workspace_id: platform?.workspace.workspace_id || "",
id: platform?.currentUser.id || "",
type: "user",
...participant,
};
};