diff --git a/src/controllers/ConversationsController.ts b/src/controllers/ConversationsController.ts index 6f0141b..6a3b035 100644 --- a/src/controllers/ConversationsController.ts +++ b/src/controllers/ConversationsController.ts @@ -121,6 +121,38 @@ export class ConversationsController { h.success("Conversation information successfully updated!"); } + /** + * Find, optionally create and return the ID of a privat conversation + * + * @param h Request handler + */ + public static async FindPrivate(h: RequestHandler) { + const otherUser = await h.postUserId("otherUser"); + const allowCreate = h.postBool("allowCreate", false); + + // Query the database + const list = await ConversationsHelper.FindPrivate(h.getUserId(), otherUser); + + if(list.length == 0) { + + if(!allowCreate) + h.error(404, "Not any private conversation was found. The server was not allowed to create a new one..."); + + // Create the conversation + const convID = await ConversationsHelper.Create({ + ownerID: h.getUserId(), + name: "", + following: true, + members: new Set([h.getUserId(), otherUser]) + }); + + list.push(convID); + } + + + h.send({"conversationsID": list}); + } + /** * Refresh current user conversations * diff --git a/src/controllers/Routes.ts b/src/controllers/Routes.ts index dd68007..b7a26c6 100644 --- a/src/controllers/Routes.ts +++ b/src/controllers/Routes.ts @@ -57,6 +57,8 @@ export const Routes : Route[] = [ {path: "/conversations/updateSettings", cb: (h) => ConversationsController.UpdateSettings(h)}, + {path: "/conversations/getPrivate", cb: (h) => ConversationsController.FindPrivate(h)}, + {path: "/conversations/refresh", cb: (h) => ConversationsController.RefreshList(h)}, {path: "/conversations/refresh_single", cb: (h) => ConversationsController.RefreshSingleConversation(h)}, diff --git a/src/helpers/ConversationsHelper.ts b/src/helpers/ConversationsHelper.ts index 83b06cc..9d642f1 100644 --- a/src/helpers/ConversationsHelper.ts +++ b/src/helpers/ConversationsHelper.ts @@ -342,6 +342,35 @@ export class ConversationsHelper { } + /** + * Search for private conversations between two users + * + * @param user1 The first user + * @param user2 The second user + * @returns The entire list of found conversations + */ + public static async FindPrivate(user1: number, user2: number) : Promise> { + const result = await DatabaseHelper.Query({ + table: USERS_TABLE, + tableAlias: "t1", + joins: [ + { + table: USERS_TABLE, + tableAlias: "t2", + condition: "t1.conv_id = t2.conv_id" + } + ], + where: { + "t1.user_id": user1, + "t2.user_id": user2 + }, + customWhere: "(SELECT COUNT(*) FROM " + USERS_TABLE + " WHERE conv_id = t1.conv_id) = 2", + fields: ["t1.conv_id AS conv_id"] + }); + + return result.map(r => r.conv_id); + } + /** * Get the list of members of a conversation *