You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
session-desktop/ts/interactions/message.ts

263 lines
9.1 KiB
TypeScript

import _ from 'lodash';
import { getV2OpenGroupRoom } from '../data/opengroups';
import { ConversationModel, ConversationTypeEnum } from '../models/conversation';
import { OpenGroup } from '../opengroup/opengroupV1/OpenGroup';
import { ApiV2 } from '../opengroup/opengroupV2';
import { joinOpenGroupV2WithUIEvents } from '../opengroup/opengroupV2/JoinOpenGroupV2';
import { isOpenGroupV2, openGroupV2CompleteURLRegex } from '../opengroup/utils/OpenGroupUtils';
import { ConversationController } from '../session/conversations';
import { PubKey } from '../session/types';
import { ToastUtils } from '../session/utils';
import { openConversationExternal } from '../state/ducks/conversations';
export function banUser(userToBan: string, conversation?: ConversationModel) {
let pubKeyToBan: PubKey;
try {
pubKeyToBan = PubKey.cast(userToBan);
} catch (e) {
window.log.warn(e);
ToastUtils.pushUserBanFailure();
return;
}
window.confirmationDialog({
title: window.i18n('banUser'),
message: window.i18n('banUserConfirm'),
resolve: async () => {
if (!conversation) {
window.log.info('cannot ban user, the corresponding conversation was not found.');
return;
}
let success = false;
if (isOpenGroupV2(conversation.id)) {
const roomInfos = await getV2OpenGroupRoom(conversation.id);
if (!roomInfos) {
window.log.warn('banUser room not found');
} else {
success = await ApiV2.banUser(pubKeyToBan, _.pick(roomInfos, 'serverUrl', 'roomId'));
}
} else {
const channelAPI = await conversation.getPublicSendData();
if (!channelAPI) {
window.log.info('cannot ban user, the corresponding channelAPI was not found.');
return;
}
success = await channelAPI.banUser(userToBan);
}
if (success) {
ToastUtils.pushUserBanSuccess();
} else {
ToastUtils.pushUserBanFailure();
}
},
});
}
/**
* There is no way to unban on an opengroupv1 server.
* This function only works for opengroupv2 server
*/
export function unbanUser(userToUnBan: string, conversation?: ConversationModel) {
let pubKeyToUnban: PubKey;
try {
pubKeyToUnban = PubKey.cast(userToUnBan);
} catch (e) {
window.log.warn(e);
ToastUtils.pushUserBanFailure();
return;
}
if (!isOpenGroupV2(conversation?.id || '')) {
window.log.warn('no way to unban on a opengroupv1');
ToastUtils.pushUserBanFailure();
return;
}
window.confirmationDialog({
title: window.i18n('unbanUser'),
message: window.i18n('unbanUserConfirm'),
resolve: async () => {
if (!conversation) {
// double check here. the convo might have been removed since the dialog was opened
window.log.info('cannot unban user, the corresponding conversation was not found.');
return;
}
let success = false;
if (isOpenGroupV2(conversation.id)) {
const roomInfos = await getV2OpenGroupRoom(conversation.id);
if (!roomInfos) {
window.log.warn('unbanUser room not found');
} else {
success = await ApiV2.unbanUser(pubKeyToUnban, _.pick(roomInfos, 'serverUrl', 'roomId'));
}
}
if (success) {
ToastUtils.pushUserUnbanSuccess();
} else {
ToastUtils.pushUserUnbanFailure();
}
},
});
}
export function copyBodyToClipboard(body?: string) {
window.clipboard.writeText(body);
ToastUtils.pushCopiedToClipBoard();
}
export function copyPubKey(sender: string) {
// this.getSource return out pubkey if this is an outgoing message, or the sender pubkey
window.clipboard.writeText();
ToastUtils.pushCopiedToClipBoard();
}
export async function removeSenderFromModerator(sender: string, convoId: string) {
try {
const pubKeyToRemove = PubKey.cast(sender);
const convo = ConversationController.getInstance().getOrThrow(convoId);
if (convo.isOpenGroupV1()) {
const channelAPI = await convo.getPublicSendData();
if (!channelAPI) {
throw new Error('No channelAPI');
}
const res = await channelAPI.serverAPI.removeModerators([pubKeyToRemove.key]);
if (!res) {
window.log.warn('failed to remove moderators:', res);
ToastUtils.pushErrorHappenedWhileRemovingModerator();
} else {
// refresh the moderator list. Will trigger a refresh
const modPubKeys = await channelAPI.getModerators();
await convo.updateGroupAdmins(modPubKeys);
window.log.info(`${pubKeyToRemove.key} removed from moderators...`);
ToastUtils.pushUserRemovedFromModerators();
}
} else if (convo.isOpenGroupV2()) {
// FXIME audric removeModerator not working serverside
const roomInfo = convo.toOpenGroupV2();
const res = await ApiV2.removeModerator(pubKeyToRemove, roomInfo);
if (!res) {
window.log.warn('failed to remove moderator:', res);
ToastUtils.pushErrorHappenedWhileRemovingModerator();
} else {
window.log.info(`${pubKeyToRemove.key} removed from moderators...`);
ToastUtils.pushUserRemovedFromModerators();
}
}
} catch (e) {
window.log.error('Got error while removing moderator:', e);
}
}
export async function addSenderAsModerator(sender: string, convoId: string) {
try {
const pubKeyToRemove = PubKey.cast(sender);
const convo = ConversationController.getInstance().getOrThrow(convoId);
if (convo.isOpenGroupV1()) {
const channelAPI = await convo.getPublicSendData();
if (!channelAPI) {
throw new Error('No channelAPI');
}
if (!channelAPI.serverAPI) {
throw new Error('No serverAPI');
}
const res = await channelAPI.serverAPI.addModerator([pubKeyToRemove.key]);
if (!res) {
window.log.warn('failed to add moderators:', res);
ToastUtils.pushUserNeedsToHaveJoined();
} else {
window.log.info(`${pubKeyToRemove.key} added as moderator...`);
// refresh the moderator list. Will trigger a refresh
const modPubKeys = await channelAPI.getModerators();
await convo.updateGroupAdmins(modPubKeys);
ToastUtils.pushUserAddedToModerators();
}
} else if (convo.isOpenGroupV2()) {
// FXIME audric addModerator not working serverside
const roomInfo = convo.toOpenGroupV2();
const res = await ApiV2.addModerator(pubKeyToRemove, roomInfo);
if (!res) {
window.log.warn('failed to add moderator:', res);
ToastUtils.pushUserNeedsToHaveJoined();
} else {
window.log.info(`${pubKeyToRemove.key} removed from moderators...`);
ToastUtils.pushUserAddedToModerators();
}
}
} catch (e) {
window.log.error('Got error while adding moderator:', e);
}
}
async function acceptOpenGroupInvitationV1(serverAddress: string) {
try {
if (serverAddress.length === 0 || !OpenGroup.validate(serverAddress)) {
ToastUtils.pushToastError('connectToServer', window.i18n('invalidOpenGroupUrl'));
return;
}
// Already connected?
if (OpenGroup.getConversation(serverAddress)) {
ToastUtils.pushToastError('publicChatExists', window.i18n('publicChatExists'));
return;
}
// To some degree this has been copy-pasted from LeftPaneMessageSection
const rawServerUrl = serverAddress.replace(/^https?:\/\//i, '').replace(/[/\\]+$/i, '');
const sslServerUrl = `https://${rawServerUrl}`;
const conversationId = `publicChat:1@${rawServerUrl}`;
const conversationExists = ConversationController.getInstance().get(conversationId);
if (conversationExists) {
window.log.warn('We are already a member of this public chat');
ToastUtils.pushAlreadyMemberOpenGroup();
return;
}
const conversation = await ConversationController.getInstance().getOrCreateAndWait(
conversationId,
ConversationTypeEnum.GROUP
);
await conversation.setPublicSource(sslServerUrl, 1);
const channelAPI = await window.lokiPublicChatAPI.findOrCreateChannel(
sslServerUrl,
1,
conversationId
);
if (!channelAPI) {
window.log.warn(`Could not connect to ${serverAddress}`);
return;
}
openConversationExternal(conversationId);
} catch (e) {
window.log.warn('failed to join opengroupv1 from invitation', e);
ToastUtils.pushToastError('connectToServerFail', window.i18n('connectToServerFail'));
}
}
Session v1.6.2 (#1639) * padd Message buffer for all outgoing messages (even opengroupv2) * pad and unpad message everywhere attachment not padded for opengroup only * lint * enable fileserver v2 sending side * removed all en unused local strings * remove all unused keys for other locales * update displayname even if we dont have avatar on incoming profile * redesign group invitation message type * ask confirmation before joining opengroup invitation * remove the channelId from groupInvitation * fallback to envelope timestamp if dataMessage.timestamp is 0 * match group invitation design with ios * speed up first load of room message by prefetching token * create convo for members if they don't exist also, removing a private convo does not remove it entirely as we need the convo to be able to remove members * fix avatar download on restore when linking device Fixes #1601 * make sure the left member convo exist in rendering GroupUpdate * Reply attachments (#1591) * First attachment showing in reply composition. * WIP: Adding thumbnail to quote response composition component. * Added icon for voice recording attachment * Updated formatting. * Formatting. * removed duplicate styling. * WIP: Converting quote component to functional components. * Fix bug where thumbnails for attachment replies wasn't showing. * yarn Formatting. * Removed old quote component. * Add type to contentTypeSupported method. * Moved quote subcomponents out of Quote component. * yarn format * Add export to quote subcomponents. * Fixing linting errors. * remove commented line. * Addressing PR comments. * Allow pasting images into composition box as attachments (#1616) * Allow pasting images into composition box as attachments * Fix linter errors * Fix typo * Get snode from snode (#1614) * force deleteAccount after 10sec timeout waiting for configMessage * move some constants to file where they are used * add a way to fetch snodes from snodes * remove a snode from a pubkey's swarm if we get 421 without valid content * remove getVersion from snodes * hide groupMembers in right panel for non-group convo * Fix fonts sans serif (#1619) * force deleteAccount after 10sec timeout waiting for configMessage * move some constants to file where they are used * add a way to fetch snodes from snodes * remove a snode from a pubkey's swarm if we get 421 without valid content * remove getVersion from snodes * hide groupMembers in right panel for non-group convo * fix font sans serif by using roboto instead Fixes #1617 * WIP: User nicknames (#1618) * WIP Adding change nickname dialog. * WIP adding nickname change dialog. * WIP nickname dialog. * WIP: Able to set conversation nicknames. Next step cleaning and adding to conversation list menu. * Fix message capitilisations. * Add change nickname to conversation list menu. * Enable clear nickname menu item. * Added messages for changing nicknames. * Clearing nicknames working from header and message list. * Adding modal styling to nickname modal. * Reorder nickname menu item positions. * Add group based conditional nickname menu options to conversation header menu. * minor tidying. * Remove unused error causing el option. * Formatting. * Linting fixes. * Made PR fixes * Prioritise displaying nicknames for inviting new closed group members and updating closed group members. * Fix app image start for non-debian based distribs (#1622) Fixes #1620 * fixup nickname dialog for enter key pressed event (#1623) also add some type for it and remove unused props * Fix attachment extension vnd (#1628) * allow openoffice document extension and don't use * allow opendocument to be shared with the extension rather than mimetype Fixes #1593 * allow message without padding * add test for odt files * More Japanese translations (#1632) * Translate some untranslated strings into Japanese * Tweak some Japanese translations * Add new Japanese translations * WIP: Closed group reliability (#1630) * WIP: added non-durable messaging function. * WIP: Non-durable sending * WIP: adding dialog box. * Creating dialog if group invite message promises don't return true. * removed console log * applied PR changes, linting and formatting. * WIP: allowing resend invite to failures. * using lookup. * WIP: recursively opening dialog. * WIP: debugging reject triggering on confirmation modal. * register events fix. * Closed group invite retry dialog working. * Added english text to messages. * Prevent saving of hexkey pair if it already exists. * Fixed nickname edit input trimming end letter. * Don't show closed group invite dialog unless it has failed at least once. * Fix linting error. * Fix plurality. * Ensure admin members are included in all invite reattempts, mixed plurality. * test fixing windows build * Revert "test fixing windows build" This reverts commit 8ed2e0891d160a774de452e8373aea179502e221. Co-authored-by: Warrick <wcor690@aucklanduni.ac.nz> Co-authored-by: shellhazard <unva1idated@protonmail.com> Co-authored-by: beantaco <64012487+beantaco@users.noreply.github.com>
4 years ago
const acceptOpenGroupInvitationV2 = (completeUrl: string, roomName?: string) => {
window.confirmationDialog({
title: window.i18n('joinOpenGroupAfterInvitationConfirmationTitle', roomName),
message: window.i18n('joinOpenGroupAfterInvitationConfirmationDesc', roomName),
resolve: () => joinOpenGroupV2WithUIEvents(completeUrl, true),
});
// this function does not throw, and will showToasts if anything happens
};
/**
* Accepts a v1 (channelid defaults to 1) url or a v2 url (with pubkey)
*/
Session v1.6.2 (#1639) * padd Message buffer for all outgoing messages (even opengroupv2) * pad and unpad message everywhere attachment not padded for opengroup only * lint * enable fileserver v2 sending side * removed all en unused local strings * remove all unused keys for other locales * update displayname even if we dont have avatar on incoming profile * redesign group invitation message type * ask confirmation before joining opengroup invitation * remove the channelId from groupInvitation * fallback to envelope timestamp if dataMessage.timestamp is 0 * match group invitation design with ios * speed up first load of room message by prefetching token * create convo for members if they don't exist also, removing a private convo does not remove it entirely as we need the convo to be able to remove members * fix avatar download on restore when linking device Fixes #1601 * make sure the left member convo exist in rendering GroupUpdate * Reply attachments (#1591) * First attachment showing in reply composition. * WIP: Adding thumbnail to quote response composition component. * Added icon for voice recording attachment * Updated formatting. * Formatting. * removed duplicate styling. * WIP: Converting quote component to functional components. * Fix bug where thumbnails for attachment replies wasn't showing. * yarn Formatting. * Removed old quote component. * Add type to contentTypeSupported method. * Moved quote subcomponents out of Quote component. * yarn format * Add export to quote subcomponents. * Fixing linting errors. * remove commented line. * Addressing PR comments. * Allow pasting images into composition box as attachments (#1616) * Allow pasting images into composition box as attachments * Fix linter errors * Fix typo * Get snode from snode (#1614) * force deleteAccount after 10sec timeout waiting for configMessage * move some constants to file where they are used * add a way to fetch snodes from snodes * remove a snode from a pubkey's swarm if we get 421 without valid content * remove getVersion from snodes * hide groupMembers in right panel for non-group convo * Fix fonts sans serif (#1619) * force deleteAccount after 10sec timeout waiting for configMessage * move some constants to file where they are used * add a way to fetch snodes from snodes * remove a snode from a pubkey's swarm if we get 421 without valid content * remove getVersion from snodes * hide groupMembers in right panel for non-group convo * fix font sans serif by using roboto instead Fixes #1617 * WIP: User nicknames (#1618) * WIP Adding change nickname dialog. * WIP adding nickname change dialog. * WIP nickname dialog. * WIP: Able to set conversation nicknames. Next step cleaning and adding to conversation list menu. * Fix message capitilisations. * Add change nickname to conversation list menu. * Enable clear nickname menu item. * Added messages for changing nicknames. * Clearing nicknames working from header and message list. * Adding modal styling to nickname modal. * Reorder nickname menu item positions. * Add group based conditional nickname menu options to conversation header menu. * minor tidying. * Remove unused error causing el option. * Formatting. * Linting fixes. * Made PR fixes * Prioritise displaying nicknames for inviting new closed group members and updating closed group members. * Fix app image start for non-debian based distribs (#1622) Fixes #1620 * fixup nickname dialog for enter key pressed event (#1623) also add some type for it and remove unused props * Fix attachment extension vnd (#1628) * allow openoffice document extension and don't use * allow opendocument to be shared with the extension rather than mimetype Fixes #1593 * allow message without padding * add test for odt files * More Japanese translations (#1632) * Translate some untranslated strings into Japanese * Tweak some Japanese translations * Add new Japanese translations * WIP: Closed group reliability (#1630) * WIP: added non-durable messaging function. * WIP: Non-durable sending * WIP: adding dialog box. * Creating dialog if group invite message promises don't return true. * removed console log * applied PR changes, linting and formatting. * WIP: allowing resend invite to failures. * using lookup. * WIP: recursively opening dialog. * WIP: debugging reject triggering on confirmation modal. * register events fix. * Closed group invite retry dialog working. * Added english text to messages. * Prevent saving of hexkey pair if it already exists. * Fixed nickname edit input trimming end letter. * Don't show closed group invite dialog unless it has failed at least once. * Fix linting error. * Fix plurality. * Ensure admin members are included in all invite reattempts, mixed plurality. * test fixing windows build * Revert "test fixing windows build" This reverts commit 8ed2e0891d160a774de452e8373aea179502e221. Co-authored-by: Warrick <wcor690@aucklanduni.ac.nz> Co-authored-by: shellhazard <unva1idated@protonmail.com> Co-authored-by: beantaco <64012487+beantaco@users.noreply.github.com>
4 years ago
export const acceptOpenGroupInvitation = async (completeUrl: string, roomName?: string) => {
if (completeUrl.match(openGroupV2CompleteURLRegex)) {
Session v1.6.2 (#1639) * padd Message buffer for all outgoing messages (even opengroupv2) * pad and unpad message everywhere attachment not padded for opengroup only * lint * enable fileserver v2 sending side * removed all en unused local strings * remove all unused keys for other locales * update displayname even if we dont have avatar on incoming profile * redesign group invitation message type * ask confirmation before joining opengroup invitation * remove the channelId from groupInvitation * fallback to envelope timestamp if dataMessage.timestamp is 0 * match group invitation design with ios * speed up first load of room message by prefetching token * create convo for members if they don't exist also, removing a private convo does not remove it entirely as we need the convo to be able to remove members * fix avatar download on restore when linking device Fixes #1601 * make sure the left member convo exist in rendering GroupUpdate * Reply attachments (#1591) * First attachment showing in reply composition. * WIP: Adding thumbnail to quote response composition component. * Added icon for voice recording attachment * Updated formatting. * Formatting. * removed duplicate styling. * WIP: Converting quote component to functional components. * Fix bug where thumbnails for attachment replies wasn't showing. * yarn Formatting. * Removed old quote component. * Add type to contentTypeSupported method. * Moved quote subcomponents out of Quote component. * yarn format * Add export to quote subcomponents. * Fixing linting errors. * remove commented line. * Addressing PR comments. * Allow pasting images into composition box as attachments (#1616) * Allow pasting images into composition box as attachments * Fix linter errors * Fix typo * Get snode from snode (#1614) * force deleteAccount after 10sec timeout waiting for configMessage * move some constants to file where they are used * add a way to fetch snodes from snodes * remove a snode from a pubkey's swarm if we get 421 without valid content * remove getVersion from snodes * hide groupMembers in right panel for non-group convo * Fix fonts sans serif (#1619) * force deleteAccount after 10sec timeout waiting for configMessage * move some constants to file where they are used * add a way to fetch snodes from snodes * remove a snode from a pubkey's swarm if we get 421 without valid content * remove getVersion from snodes * hide groupMembers in right panel for non-group convo * fix font sans serif by using roboto instead Fixes #1617 * WIP: User nicknames (#1618) * WIP Adding change nickname dialog. * WIP adding nickname change dialog. * WIP nickname dialog. * WIP: Able to set conversation nicknames. Next step cleaning and adding to conversation list menu. * Fix message capitilisations. * Add change nickname to conversation list menu. * Enable clear nickname menu item. * Added messages for changing nicknames. * Clearing nicknames working from header and message list. * Adding modal styling to nickname modal. * Reorder nickname menu item positions. * Add group based conditional nickname menu options to conversation header menu. * minor tidying. * Remove unused error causing el option. * Formatting. * Linting fixes. * Made PR fixes * Prioritise displaying nicknames for inviting new closed group members and updating closed group members. * Fix app image start for non-debian based distribs (#1622) Fixes #1620 * fixup nickname dialog for enter key pressed event (#1623) also add some type for it and remove unused props * Fix attachment extension vnd (#1628) * allow openoffice document extension and don't use * allow opendocument to be shared with the extension rather than mimetype Fixes #1593 * allow message without padding * add test for odt files * More Japanese translations (#1632) * Translate some untranslated strings into Japanese * Tweak some Japanese translations * Add new Japanese translations * WIP: Closed group reliability (#1630) * WIP: added non-durable messaging function. * WIP: Non-durable sending * WIP: adding dialog box. * Creating dialog if group invite message promises don't return true. * removed console log * applied PR changes, linting and formatting. * WIP: allowing resend invite to failures. * using lookup. * WIP: recursively opening dialog. * WIP: debugging reject triggering on confirmation modal. * register events fix. * Closed group invite retry dialog working. * Added english text to messages. * Prevent saving of hexkey pair if it already exists. * Fixed nickname edit input trimming end letter. * Don't show closed group invite dialog unless it has failed at least once. * Fix linting error. * Fix plurality. * Ensure admin members are included in all invite reattempts, mixed plurality. * test fixing windows build * Revert "test fixing windows build" This reverts commit 8ed2e0891d160a774de452e8373aea179502e221. Co-authored-by: Warrick <wcor690@aucklanduni.ac.nz> Co-authored-by: shellhazard <unva1idated@protonmail.com> Co-authored-by: beantaco <64012487+beantaco@users.noreply.github.com>
4 years ago
acceptOpenGroupInvitationV2(completeUrl, roomName);
} else {
await acceptOpenGroupInvitationV1(completeUrl);
}
};