Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement way better matrix support #66

Draft
wants to merge 16 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions deno.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
},
"workspace": [
"./packages/lightning",
"./packages/bolt-matrix",
"./packages/lightning-plugin-telegram",
"./packages/lightning-plugin-revolt",
"./packages/lightning-plugin-guilded",
Expand Down
32 changes: 32 additions & 0 deletions packages/bolt-matrix/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# lightning-plugin-matrix

lightning-plugin-matrix is a plugin for
[lightning](https://williamhroning.eu.org/lightning) that adds support for
telegram

## example config

```ts
import type { config } from 'jsr:@jersey/lightning@0.7.3';
import { matrix_plugin } from 'jsr:@jersey/lightning-plugin-matrix@0.7.3';

export default {
redis_host: 'localhost',
redis_port: 6379,
plugins: [
matrix_plugin.new({
appservice_id: 'lightning',
appservice_token: 'your_creative_token',
homeserver_domain: 'your.domain.tld',
homeserver_localpart: 'bot.lightning',
homeserver_prefix: 'lightning-',
homeserver_url: 'https://matrix.your.domain.tld',
homeservice_token: 'your_other_creative_token',
plugin_port: 5555,
plugin_url: 'https://lightning-matrix.your.domain.tld',
registration_file: `/path/to/reg.yaml`,
store_dir: `/path/to/storage_directory`,
}),
],
} as config;
```
12 changes: 12 additions & 0 deletions packages/bolt-matrix/deno.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"name": "@jersey/lightning-plugin-matrix",
"version": "0.7.3",
"exports": "./src/mod.ts",
"imports": {
"@nodejs/buffer": "node:buffer",
"@jersey/lightning": "jsr:@jersey/lightning@0.7.3",
"@deno/gfm": "jsr:@deno/gfm@0.8.2",
"@std/fs": "jsr:@std/fs@1.0.1",
"matrix-appservice-bridge": "npm:matrix-appservice-bridge@10.1.0"
}
}
18 changes: 18 additions & 0 deletions packages/bolt-matrix/license
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
Copyright (c) William Horning and contributors

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the “Software”), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
43 changes: 43 additions & 0 deletions packages/bolt-matrix/src/matrix_events.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import type { matrix_client_event } from './matrix_types.ts';
import type { matrix_plugin } from './mod.ts';
import { to_lightning } from './to_lightning.ts';

export async function on_event(
this: matrix_plugin,
event: matrix_client_event
) {
const bot_intent = this.br.getIntent()
if (
event.type === 'm.room.member' &&
event.content.membership === 'invite' &&
event.state_key === `@${this.config.homeserver_localpart}:${this.config.homeserver_domain}`
) {
try {
await bot_intent.join(event.room_id);
} catch (e) {
console.debug(`failed joining ${event.room_id}`, e);
}
}
if (event.type === 'm.room.message' && !event.content['m.new_content']) {
this.emit(
'create_message',
await to_lightning(event, bot_intent, this.config.homeserver_url),
);
}
if (event.type === 'm.room.message' && event.content['m.new_content']) {
this.emit(
'edit_message',
await to_lightning(event, bot_intent, this.config.homeserver_url),
);
}
if (event.type === 'm.room.redaction') {
this.emit('delete_message', {
id: event.content.redacts as string,
plugin: 'bolt-matrix',
channel: event.room_id,
timestamp: Temporal.Instant.fromEpochMilliseconds(
event.origin_server_ts,
),
});
}
}
50 changes: 50 additions & 0 deletions packages/bolt-matrix/src/matrix_types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
export interface matrix_client_event {
content: Record<string, unknown>;
event_id: string;
origin_server_ts: number;
room_id: string;
sender: string;
state_key?: string;
type: string;
unsigned?: matrix_unsigned_data;
}

export interface matrix_unsigned_data {
age?: number;
membership?: string;
prev_content?: Record<string, unknown>;
redacted_because?: matrix_client_event;
transaction_id?: string;
}

export interface matrix_user {
display_name?: string;
avatar_url?: string;
avatar_mxc?: string;
}

/** config for the matrix plugin */
export interface matrix_config {
/** token used to authenticate to the homeserver */
appservice_token: string;
/** token used to authenticate to the plugin */
homeservice_token: string;
/** id used to identify the appservice on the homeserver */
appservice_id: string;
/** the username of the bot on the homeserver */
homeserver_localpart: string;
/** the url the plugin's server is accessable from */
plugin_url: string;
/** the port the plugin listens on */
plugin_port: number;
/** the prefix for bridged users (such as `lightning-`) */
homeserver_prefix: string;
/** the path to store the registration file */
registration_file: string;
/** the path to store the user store */
store_dir: string;
/** the url where the homeserver is at */
homeserver_url: string;
/** the domain users on the homeservers are associated with */
homeserver_domain: string;
}
143 changes: 143 additions & 0 deletions packages/bolt-matrix/src/mod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
import {
type lightning,
type message_options,
plugin,
type process_result,
} from '@jersey/lightning';
import { Buffer } from '@nodejs/buffer';
import {
Bridge,
MatrixUser,
type UserBridgeStore,
} from 'matrix-appservice-bridge';
import { on_event } from './matrix_events.ts';
import type { matrix_config, matrix_user } from './matrix_types.ts';
import { setup_registration } from './setup_registration.ts';
import { to_matrix } from './to_matrix.ts';

export type { matrix_config }

/** the plugin to use */
export class matrix_plugin extends plugin<matrix_config> {
name = 'bolt-matrix';
store: Map<string, matrix_user> = new Map();
br: Bridge;
st: UserBridgeStore;

constructor(l: lightning, config: matrix_config) {
super(l, config);
setup_registration(config);
this.br = new Bridge({
controller: {
onEvent: (request) => {
console.log(request.getData());
on_event.bind(this)(request.getData());
},
},
domain: config.homeserver_domain,
homeserverUrl: config.homeserver_url,
registration: config.registration_file,
userStore: `${config.store_dir}/user.db`,
roomStore: `${config.store_dir}/room.db`,
userActivityStore: `${config.store_dir}/activity.db`,
});
this.st = this.br.getUserStore()!;
this.br.run(this.config.plugin_port, undefined, '0.0.0.0');
}

/** create a bridge */
create_bridge(channelId: string): string {
return channelId;
}

/** processes a message */
async process_message(opts: message_options): Promise<process_result> {
try {
const bot_intent = this.br.getIntent();

if (opts.action === 'delete') {
for (const message of opts.edit_id) {
await bot_intent.botSdkIntent.underlyingClient.redactEvent(
opts.channel.id,
message,
);
}

return {
channel: opts.channel,
id: opts.edit_id,
plugin: 'bolt-matrix',
};
} else {
const messages = await to_matrix(
opts.message,
bot_intent.uploadContent,
opts.reply_id,
'edit_id' in opts ? opts.edit_id : undefined,
);

const msg_ids = [];

const mxid =
`@${this.config.homeserver_prefix}${opts.message.author.id}:${this.config.homeserver_domain}`;

let matrix_user = await this.st.getMatrixUser(mxid);

if (!matrix_user) {
matrix_user = new MatrixUser(mxid);
await this.br.provisionUser(matrix_user);
}

const intent = this.br.getIntent(mxid);

if (
opts.message.author.profile &&
matrix_user.get('avatar_url') !==
opts.message.author.profile
) {
const mxc = await bot_intent.uploadContent(
Buffer.from(
await (await fetch(opts.message.author.profile))
.arrayBuffer(),
),
);

await intent.setAvatarUrl(mxc);

matrix_user.set('avatar_url', opts.message.author.profile);
}

if (
matrix_user.getDisplayName() !==
opts.message.author.username
) {
await intent.setDisplayName(opts.message.author.username);

matrix_user.setDisplayName(opts.message.author.username);
}

await this.st.setMatrixUser(matrix_user);

for (const message of messages) {
msg_ids.push(
(await intent.sendMessage(opts.channel.id, message))
.event_id,
);
}

return {
channel: opts.channel,
id: msg_ids,
plugin: 'bolt-matrix',
};
}
} catch (e) {
return {
error: e,
channel: opts.channel,
disable: false,
plugin: 'bolt-matrix',
};
}
}
}
19 changes: 19 additions & 0 deletions packages/bolt-matrix/src/setup_registration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { existsSync } from '@std/fs';
import type { matrix_config } from './matrix_types.ts';

export function setup_registration(cfg: matrix_config) {
if (!existsSync(cfg.registration_file)) {
const registration = `
as_token: ${cfg.appservice_token}
hs_token: ${cfg.homeservice_token}
id: ${cfg.appservice_id}
namespaces:
users:
- regex: '@${cfg.homeserver_prefix}-.*'
exclusive: true
sender_localpart: ${cfg.homeserver_localpart}
rate_limited: false
url: ${cfg.plugin_url}`;
Deno.writeTextFileSync(cfg.registration_file, registration);
}
}
Loading