Skip to content

Commit

Permalink
Merge pull request #404 from the-draupnir-project/gnuxie/ban-command-…
Browse files Browse the repository at this point in the history
…fixes

Fix ban and unban command bugs

Fixes #401
Fixes #385
  • Loading branch information
Gnuxie authored May 6, 2024
2 parents be37475 + 269a3ed commit 603ac6a
Show file tree
Hide file tree
Showing 9 changed files with 98 additions and 19 deletions.
4 changes: 2 additions & 2 deletions src/commands/Unban.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,12 @@ limitations under the License.

import { DraupnirContext } from "./CommandHandler";
import { findPresentationType, KeywordsDescription, parameters, ParsedKeywords, union } from "./interface-manager/ParameterParsing";
import { UserID, MatrixGlob, LogLevel } from "matrix-bot-sdk";
import { MatrixGlob, LogLevel } from "matrix-bot-sdk";
import { defineInterfaceCommand, findTableCommand } from "./interface-manager/InterfaceCommand";
import { defineMatrixInterfaceAdaptor } from "./interface-manager/MatrixInterfaceAdaptor";
import { tickCrossRenderer } from "./interface-manager/MatrixHelpRenderer";
import { Draupnir } from "../Draupnir";
import { ActionResult, isError, isStringUserID, MatrixRoomReference, Ok, PolicyRuleType } from "matrix-protection-suite";
import { ActionResult, isError, isStringUserID, MatrixRoomReference, Ok, PolicyRuleType, UserID } from "matrix-protection-suite";
import { resolveRoomReferenceSafe } from "matrix-protection-suite-for-matrix-bot-sdk";
import { findPolicyRoomIDFromShortcode } from "./CreateBanListCommand";

Expand Down
19 changes: 18 additions & 1 deletion src/commands/interface-manager/DeadDocumentPresentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
* All rights reserved.
*/

import { MatrixRoomAlias, MatrixRoomID } from "matrix-protection-suite";
import { DocumentNode } from "./DeadDocument"
import { PresentationType } from "./ParameterParsing";
import { PresentationType, findPresentationType, presentationTypeOf } from "./ParameterParsing";

type PresentationRenderer = (presentation: unknown) => DocumentNode;

Expand All @@ -26,3 +27,19 @@ export function findPresentationRenderer(presentationType: PresentationType): Pr
}
return entry;
}

export const DeadDocumentPresentationMirror = Object.freeze({
present(object: unknown): DocumentNode {
if (object instanceof MatrixRoomID || object instanceof MatrixRoomAlias) {
return findPresentationRenderer(findPresentationType('MatrixRoomReference'))(object)
} else {
const presentationType = presentationTypeOf(object);
if (presentationType !== undefined) {
const renderer = findPresentationRenderer(presentationType);
return renderer(object);
} else {
throw new TypeError(`Unable to present: ${object}`);
}
}
}
})
11 changes: 2 additions & 9 deletions src/commands/interface-manager/JSXFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
*/

import { DocumentNode, LeafNode, makeDocumentNode, makeLeafNode, NodeTag, TextNode } from "./DeadDocument";
import { findPresentationRenderer } from "./DeadDocumentPresentation";
import { presentationTypeOf } from "./ParameterParsing";
import { DeadDocumentPresentationMirror } from "./DeadDocumentPresentation";

type rawJSX = DocumentNode|LeafNode|string|number|Array<rawJSX>;

Expand All @@ -31,13 +30,7 @@ export function JSXFactory(tag: NodeTag, properties: unknown, ...rawChildren: (D
node.addChild(rawChild);
}
} else {
const presentationType = presentationTypeOf(rawChild);
if (presentationType !== undefined) {
const renderer = findPresentationRenderer(presentationType);
node.addChild(renderer(rawChild));
} else {
throw new TypeError(`Unexpected raw child ${JSON.stringify(rawChild)}`);
}
node.addChild(DeadDocumentPresentationMirror.present(rawChild));
}
}
rawChildren.forEach(ensureChild);
Expand Down
1 change: 1 addition & 0 deletions src/commands/interface-manager/MatrixInterfaceAdaptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ export class MatrixInterfaceAdaptor<C extends MatrixContext, ExecutorType extend
} else {
await promptSuggestions.call(matrixContext, parameter, this.interfaceCommand, promptOptions.suggestions, args);
}
return;
} else {
this.reportValidationError(matrixContext.client, matrixContext.roomID, matrixContext.event, executorResult.error);
return;
Expand Down
6 changes: 5 additions & 1 deletion src/commands/interface-manager/MatrixPresentations.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { findPresentationType, makePresentationType, simpleTypeValidator } from
import { definePresentationRenderer } from "./DeadDocumentPresentation";
import { JSXFactory } from "./JSXFactory";
import { DocumentNode } from "./DeadDocument";
import { MatrixEventViaAlias, MatrixEventViaRoomID, MatrixRoomAlias, MatrixRoomID, UserID } from "matrix-protection-suite";
import { MatrixEventViaAlias, MatrixEventViaRoomID, MatrixRoomAlias, MatrixRoomID, MatrixRoomReference, UserID } from "matrix-protection-suite";


makePresentationType({
Expand All @@ -21,6 +21,10 @@ makePresentationType({
validator: simpleTypeValidator('MatrixRoomReference', (item: ReadItem) => item instanceof MatrixRoomID || item instanceof MatrixRoomAlias),
})

definePresentationRenderer(findPresentationType('MatrixRoomReference'), function(presentation: MatrixRoomReference): DocumentNode {
return <a href={presentation.toPermalink()}>{presentation.toRoomIDOrAlias()}</a>
})

makePresentationType({
name: 'MatrixRoomID',
validator: simpleTypeValidator('MatrixRoomID', (item: ReadItem) => item instanceof MatrixRoomID)
Expand Down
9 changes: 5 additions & 4 deletions src/commands/interface-manager/MatrixPromptForAccept.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { MatrixSendClient } from "matrix-protection-suite-for-matrix-bot-sdk";
import { MatrixReactionHandler, ReactionListener } from "./MatrixReactionHandler";
import { StaticDecode, Type } from "@sinclair/typebox";
import { ReadItem, readCommand } from "./CommandReader";
import { printReadably } from "./PrintReadably";

const log = new Logger('MatrixPromptForAccept');

Expand Down Expand Up @@ -150,8 +151,8 @@ export async function promptDefault<PresentationType extends ReadItem>(
reactionMap,
{
command_designator: command.designator,
read_items: existingArguments.map(item => item.toString()),
default: defaultPrompt.toString()
read_items: existingArguments.map(printReadably),
default: printReadably(defaultPrompt)
}
)
);
Expand All @@ -173,7 +174,7 @@ export async function promptSuggestions(
existingArguments: ReadItem[],
): Promise<void> {
const reactionMap = MatrixReactionHandler.createItemizedReactionMap(
suggestions.map(item => item.toString())
suggestions.map(printReadably)
);
const events = await renderMatrixAndSend(
<root>Please select one of the following options to provide as an argument for the parameter <code>{parameter.name}</code>:
Expand All @@ -190,7 +191,7 @@ export async function promptSuggestions(
ARGUMENT_PROMPT_LISTENER,
reactionMap,
{
read_items: existingArguments,
read_items: existingArguments.map(printReadably),
command_designator: command.designator
}
)
Expand Down
18 changes: 18 additions & 0 deletions src/commands/interface-manager/PrintReadably.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// SPDX-FileCopyrightText: 2024 Gnuxie <[email protected]>
//
// SPDX-License-Identifier: AFL-3.0

import { MatrixEventViaAlias, MatrixEventViaRoomID, MatrixRoomAlias, MatrixRoomID, Permalinks, UserID } from "matrix-protection-suite";
import { ReadItem } from "./CommandReader";

export function printReadably(item: ReadItem): string {
if (item instanceof MatrixRoomID || item instanceof MatrixRoomAlias) {
return item.toPermalink();
} else if (item instanceof UserID) {
return item.toString();
} else if (item instanceof MatrixEventViaAlias || item instanceof MatrixEventViaRoomID) {
return Permalinks.forEvent(item.reference.toRoomIDOrAlias(), item.eventID, item.reference.getViaServers());
} else {
return item.toString()
}
}
11 changes: 9 additions & 2 deletions test/commands/CommandReaderTest.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import expect from "expect";
import { Keyword, readCommand } from "../../src/commands/interface-manager/CommandReader";
import { MatrixRoomAlias, MatrixRoomID } from "matrix-protection-suite";
import { MatrixRoomAlias, MatrixRoomID, UserID } from "matrix-protection-suite";

describe("Can read", function() {
it("Can read a simple command with only strings", function() {
Expand Down Expand Up @@ -43,5 +43,12 @@ describe("Can read", function() {
}
checkMalformedRoomReference("#singasongaboutlife");
checkMalformedRoomReference("!mjolnir");
})
});
it("Can parse userID's", function() {
const command = "@spam:example.com";
const readItems = readCommand(command);
expect(readItems.at(0)).toBeInstanceOf(UserID);
const user = readItems.at(0) as UserID;
expect(user.localpart).toBe('spam');
});
})
38 changes: 38 additions & 0 deletions test/commands/ParseTest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { Ok, isError } from "matrix-protection-suite";
import { defineCommandTable, defineInterfaceCommand, findTableCommand } from "../../src/commands/interface-manager/InterfaceCommand";
import { ArgumentStream, findPresentationType, parameters, union } from "../../src/commands/interface-manager/ParameterParsing";
import { readCommand } from "../../src/commands/interface-manager/CommandReader";
import "../../src/commands/interface-manager/MatrixPresentations";

it('A command that fookin parses mxids', async function() {
const tableName = Symbol("ParseTest");
defineCommandTable(tableName);
defineInterfaceCommand({
designator: ["unban"],
table: tableName,
parameters: parameters([
{
name: "entity",
acceptor: union(
findPresentationType("UserID"),
findPresentationType("MatrixRoomReference"),
findPresentationType("string")
)
}
],
undefined,
),
command: async function() {
return Ok(undefined);
},
summary: "Mimicks the unban command"
});
const command = findTableCommand(tableName, "unban");
if (command === undefined) {
throw new TypeError(`Command table has gone missing this asin't good guys`);
}
const result = await command.parseThenInvoke(undefined, new ArgumentStream(readCommand("@spam:example.com")));
if (isError(result)) {
throw new TypeError(`Not supposed to be error mate`);
}
})

0 comments on commit 603ac6a

Please sign in to comment.