Quellcode durchsuchen

Initial commit

Add files from pridepack.
master
TheoryOfNekomata vor 4 Monaten
Commit
bba2381a15
24 geänderte Dateien mit 2619 neuen und 0 gelöschten Zeilen
  1. +2
    -0
      .gitignore
  2. +110
    -0
      packages/discord-bot/.gitignore
  3. +7
    -0
      packages/discord-bot/LICENSE
  4. +49
    -0
      packages/discord-bot/package.json
  5. +3
    -0
      packages/discord-bot/pridepack.json
  6. +13
    -0
      packages/discord-bot/src/client.ts
  7. +8
    -0
      packages/discord-bot/src/common.ts
  8. +9
    -0
      packages/discord-bot/src/config.ts
  9. +44
    -0
      packages/discord-bot/src/events.ts
  10. +46
    -0
      packages/discord-bot/src/index.ts
  11. +50
    -0
      packages/discord-bot/src/modules/channel.ts
  12. +26
    -0
      packages/discord-bot/src/modules/context.ts
  13. +85
    -0
      packages/discord-bot/src/modules/thread.ts
  14. +8
    -0
      packages/discord-bot/test/index.test.ts
  15. +23
    -0
      packages/discord-bot/tsconfig.json
  16. +107
    -0
      packages/server/.gitignore
  17. +7
    -0
      packages/server/LICENSE
  18. +46
    -0
      packages/server/package.json
  19. +3
    -0
      packages/server/pridepack.json
  20. +6
    -0
      packages/server/src/index.ts
  21. +8
    -0
      packages/server/test/index.test.ts
  22. +23
    -0
      packages/server/tsconfig.json
  23. +1934
    -0
      pnpm-lock.yaml
  24. +2
    -0
      pnpm-workspace.yaml

+ 2
- 0
.gitignore Datei anzeigen

@@ -0,0 +1,2 @@
.idea/
node_modules/

+ 110
- 0
packages/discord-bot/.gitignore Datei anzeigen

@@ -0,0 +1,110 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.production
.env.development

# parcel-bundler cache (https://parceljs.org/)
.cache

# Next.js build output
.next

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

.npmrc

types/
.db/

+ 7
- 0
packages/discord-bot/LICENSE Datei anzeigen

@@ -0,0 +1,7 @@
MIT License Copyright (c) 2024 TheoryOfNekomata <allan.crisostomo@outlook.com>

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 (including the next paragraph) 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.

+ 49
- 0
packages/discord-bot/package.json Datei anzeigen

@@ -0,0 +1,49 @@
{
"name": "discord-bot",
"version": "0.0.0",
"files": [
"dist",
"src"
],
"engines": {
"node": ">=16"
},
"license": "MIT",
"keywords": [
"pridepack"
],
"devDependencies": {
"@types/node": "^20.11.0",
"pridepack": "2.6.0",
"tslib": "^2.6.2",
"typescript": "^5.3.3",
"vitest": "^1.2.0"
},
"scripts": {
"prepublishOnly": "pridepack clean && pridepack build",
"build": "pridepack build",
"type-check": "pridepack check",
"clean": "pridepack clean",
"watch": "pridepack watch",
"start": "pridepack start",
"dev": "pridepack dev",
"test": "vitest"
},
"private": false,
"description": "Discord bot for Legato.",
"repository": {
"url": "",
"type": "git"
},
"homepage": "",
"bugs": {
"url": ""
},
"author": "TheoryOfNekomata <allan.crisostomo@outlook.com>",
"publishConfig": {
"access": "public"
},
"dependencies": {
"discord.js": "^14.15.2"
}
}

+ 3
- 0
packages/discord-bot/pridepack.json Datei anzeigen

@@ -0,0 +1,3 @@
{
"target": "esnext"
}

+ 13
- 0
packages/discord-bot/src/client.ts Datei anzeigen

@@ -0,0 +1,13 @@
import {Client} from 'discord.js';

interface CreateClientParams {
intents: bigint;
}

export const createClient = (params: CreateClientParams) => {
const client = new Client({
intents: params.intents.toString() as `${bigint}`,
});

return client;
};

+ 8
- 0
packages/discord-bot/src/common.ts Datei anzeigen

@@ -0,0 +1,8 @@
import {Channel, ClientEvents, ForumChannel} from 'discord.js';

export interface BotContext {
channel?: ForumChannel;
onMessageCreate: (listener: (...args: ClientEvents['messageCreate']) => void) => any;
onThreadCreate: (listener: (...args: ClientEvents['threadCreate']) => void) => any;
fetchChannel: (threadId: string) => Promise<Channel | null>;
}

+ 9
- 0
packages/discord-bot/src/config.ts Datei anzeigen

@@ -0,0 +1,9 @@
import { GatewayIntentBits } from 'discord.js';

export namespace meta {
//export const clientId = process.env.DISCORD_CLIENT_ID as string;
export const intentsInteger = BigInt(
GatewayIntentBits.Guilds | GatewayIntentBits.GuildMessages | GatewayIntentBits.MessageContent
);
export const token = process.env.DISCORD_BOT_TOKEN as string;
}

+ 44
- 0
packages/discord-bot/src/events.ts Datei anzeigen

@@ -0,0 +1,44 @@
import {ThreadChannel} from 'discord.js';
import {addThread, addThreadMessage} from './modules/thread';
import {BotContext} from './common';
import {setMetadata} from './modules/channel';
import {isThreadInSelectedForumChannel} from './modules/context';

export const addMessageEventsListener = (context: BotContext) => {
context.onThreadCreate(async (thread) => {
if (typeof context.channel?.id === 'undefined') {
return;
}

const isDescendant = await isThreadInSelectedForumChannel(context, thread);
if (!isDescendant) {
return;
}

await addThread(context.channel, thread);
await setMetadata(context.channel);
});

context.onMessageCreate(async (message) => {
if (typeof context.channel?.id === 'undefined') {
return;
}

const thread = await context.fetchChannel(message.channelId);
if (!thread) {
return;
}

if (!(thread instanceof ThreadChannel)) {
return;
}

const isDescendant = await isThreadInSelectedForumChannel(context, thread)
if (!isDescendant) {
return;
}

await addThreadMessage(context.channel, thread, message);
await setMetadata(context.channel);
});
};

+ 46
- 0
packages/discord-bot/src/index.ts Datei anzeigen

@@ -0,0 +1,46 @@
import {createClient} from './client';
import * as config from './config';
import {addMessageEventsListener} from './events';
import {ForumChannel} from 'discord.js';
import {setupThreads} from './modules/thread';
import {BotContext} from './common';

const main = async (channelId: string) => {
const client = createClient({
intents: config.meta.intentsInteger,
});

const context: BotContext = {
channel: undefined,
onMessageCreate: (fn) => {
client.on('messageCreate', fn);
},
onThreadCreate: (fn) => {
client.on('threadCreate', fn);
},
fetchChannel: (channelId: string) => client.channels.fetch(channelId),
};

client.on('ready', async () => {
if (!client.user) {
console.error('Not logged in!');
return;
}
console.log(`Logged in as ${client.user.tag}`);

const channel = await client.channels.fetch(channelId);
if (!(channel instanceof ForumChannel)) {
console.error(`Channel ${channelId} is not a forum!`);
return;
}

context.channel = channel;
await setupThreads(context);
});

addMessageEventsListener(context);
await client.login(config.meta.token);
}

// TODO load channelId from config
void main('1244285168580300904');

+ 50
- 0
packages/discord-bot/src/modules/channel.ts Datei anzeigen

@@ -0,0 +1,50 @@
import {ForumChannel} from 'discord.js';
import {mkdir, readFile, rm, stat, writeFile} from 'fs/promises';

export const getChannelIdPath = (channel: ForumChannel) => `.db/${channel.id}`;

const getMetadataPath = (channel: ForumChannel) => `${getChannelIdPath(channel)}/.metadata.json`;

export const ensureChannelContent = async (channel: ForumChannel) => {
try {
await mkdir(getChannelIdPath(channel), {recursive: true});
} catch {
// noop
}
};

export const getMetadata = async (channel: ForumChannel) => {
const filePath = getMetadataPath(channel);
let metadata;
try {
const s = await stat(filePath);
if (s.isFile()) {
const metadataJson = await readFile(filePath, 'utf-8');
metadata = JSON.parse(metadataJson);

// todo use valibot?
if ('lastSyncedAt' in metadata) {
return metadata;
}
}
} catch {
// noop
}

metadata = {
lastSyncedAt: undefined,
};

await ensureChannelContent(channel);
await rm(filePath, { recursive: true, force: true });
await writeFile(filePath, JSON.stringify(metadata));
return metadata;
};

export const setMetadata = async (channel: ForumChannel) => {
const filePath = getMetadataPath(channel);
await ensureChannelContent(channel);
await writeFile(filePath, JSON.stringify({
lastSyncedAt: Date.now(),
}));
};

+ 26
- 0
packages/discord-bot/src/modules/context.ts Datei anzeigen

@@ -0,0 +1,26 @@
import {BotContext} from '../common';
import {Channel} from 'discord.js';

export const isThreadInSelectedForumChannel = async (context: BotContext, currentChannel?: Channel): Promise<boolean> => {
if (!currentChannel) {
return false;
}
const parentChannel = context.channel;
if (typeof parentChannel === 'undefined') {
return false;
}
if (currentChannel.id === parentChannel.id) {
return true;
}
if (!('parentId' in currentChannel)) {
return false;
}
if (!currentChannel.parentId) {
return false;
}
const parent = await context.fetchChannel(currentChannel.parentId);
if (!parent) {
return false;
}
return await isThreadInSelectedForumChannel(context, parent);
};

+ 85
- 0
packages/discord-bot/src/modules/thread.ts Datei anzeigen

@@ -0,0 +1,85 @@
import {AnyThreadChannel, ForumChannel, Message} from 'discord.js';
import {writeFile} from 'fs/promises';
import {BotContext} from '../common';
import {
ensureChannelContent,
getChannelIdPath,
getMetadata,
setMetadata,
} from './channel';

const getChannelThreadIdPath = (channel: ForumChannel, thread: AnyThreadChannel) => `${getChannelIdPath(channel)}/${thread.id}`;

const serializeMessage = (message: Message) => {
const messageContent = [
message.content,
...Array.from(message.attachments.values()).map((a) => (
a.contentType?.startsWith('image/') ? `[![${a.name}](${a.url})](${a.url})` : `[${a.name}](${a.url})`
))
];
return (
`\n${message.id} ${message.createdTimestamp} ${message.author.id} ${JSON.stringify(messageContent.join(' ').trim())}`
);
}

const serializeThreadMetadata = (thread: AnyThreadChannel) => (
`${thread.id} ${thread.createdTimestamp} ${thread.client.user?.id} ${JSON.stringify(thread.name)}`
);

export const addThreadMessage = async (channel: ForumChannel, thread: AnyThreadChannel, message: Message) => {
try {
await writeFile(
getChannelThreadIdPath(channel, thread),
serializeMessage(message),
{ flag: 'a+' },
);
} catch {
// noop
}
};

export const addThread = async (channel: ForumChannel, thread: AnyThreadChannel) => {
await ensureChannelContent(channel);

try {
await writeFile(
getChannelThreadIdPath(channel, thread),
serializeThreadMetadata(thread),
);
} catch {
// noop
}

try {
// todo how to fetch unrecorded messages
const messages = await thread.messages.fetch();
const collection = messages.sorted((a, b) => a.createdTimestamp - b.createdTimestamp);
const collectionArray = Array.from(collection.values());
await collectionArray.reduce(
async (promise, message) => {
await promise;
return addThreadMessage(channel, thread, message);
},
Promise.resolve(),
);
} catch {
// noop
}
};

export const setupThreads = async (context: BotContext) => {
if (typeof context.channel === 'undefined') {
return;
}
const channel = context.channel;
const metadata = await getMetadata(channel);
// todo how to fetch unrecorded threads
const threads = await channel.threads.fetch();
for (const [, thread] of threads.threads) {
if (typeof metadata.lastSyncedAt !== 'undefined' && (thread.createdTimestamp ?? Infinity) <= metadata.lastSyncedAt) {
continue;
}
await addThread(channel, thread);
}
await setMetadata(channel);
};

+ 8
- 0
packages/discord-bot/test/index.test.ts Datei anzeigen

@@ -0,0 +1,8 @@
import { describe, it, expect } from 'vitest';
import add from '../src';

describe('blah', () => {
it('works', () => {
expect(add(1, 1)).toEqual(2);
});
});

+ 23
- 0
packages/discord-bot/tsconfig.json Datei anzeigen

@@ -0,0 +1,23 @@
{
"exclude": ["node_modules"],
"include": ["src", "types"],
"compilerOptions": {
"module": "ESNext",
"lib": ["ESNext"],
"importHelpers": true,
"declaration": true,
"sourceMap": true,
"rootDir": "./src",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"moduleResolution": "bundler",
"jsx": "react",
"esModuleInterop": true,
"target": "es2018",
"useDefineForClassFields": false,
"declarationMap": true
}
}

+ 107
- 0
packages/server/.gitignore Datei anzeigen

@@ -0,0 +1,107 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.production
.env.development

# parcel-bundler cache (https://parceljs.org/)
.cache

# Next.js build output
.next

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

.npmrc

+ 7
- 0
packages/server/LICENSE Datei anzeigen

@@ -0,0 +1,7 @@
MIT License Copyright (c) 2024 TheoryOfNekomata <allan.crisostomo@outlook.com>

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 (including the next paragraph) 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.

+ 46
- 0
packages/server/package.json Datei anzeigen

@@ -0,0 +1,46 @@
{
"name": "server",
"version": "0.0.0",
"files": [
"dist",
"src"
],
"engines": {
"node": ">=16"
},
"license": "MIT",
"keywords": [
"pridepack"
],
"devDependencies": {
"@types/node": "^20.11.0",
"pridepack": "2.6.0",
"tslib": "^2.6.2",
"typescript": "^5.3.3",
"vitest": "^1.2.0"
},
"scripts": {
"prepublishOnly": "pridepack clean && pridepack build",
"build": "pridepack build",
"type-check": "pridepack check",
"clean": "pridepack clean",
"watch": "pridepack watch",
"start": "pridepack start",
"dev": "pridepack dev",
"test": "vitest"
},
"private": false,
"description": "Data server for Superproxy.",
"repository": {
"url": "",
"type": "git"
},
"homepage": "",
"bugs": {
"url": ""
},
"author": "TheoryOfNekomata <allan.crisostomo@outlook.com>",
"publishConfig": {
"access": "public"
}
}

+ 3
- 0
packages/server/pridepack.json Datei anzeigen

@@ -0,0 +1,3 @@
{
"target": "es2018"
}

+ 6
- 0
packages/server/src/index.ts Datei anzeigen

@@ -0,0 +1,6 @@
export default function add(a: number, b: number): number {
if (process.env.NODE_ENV !== 'production') {
console.log('This code would not appear on production builds');
}
return a + b;
}

+ 8
- 0
packages/server/test/index.test.ts Datei anzeigen

@@ -0,0 +1,8 @@
import { describe, it, expect } from 'vitest';
import add from '../src';

describe('blah', () => {
it('works', () => {
expect(add(1, 1)).toEqual(2);
});
});

+ 23
- 0
packages/server/tsconfig.json Datei anzeigen

@@ -0,0 +1,23 @@
{
"exclude": ["node_modules"],
"include": ["src", "types"],
"compilerOptions": {
"module": "ESNext",
"lib": ["ESNext"],
"importHelpers": true,
"declaration": true,
"sourceMap": true,
"rootDir": "./src",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"moduleResolution": "bundler",
"jsx": "react",
"esModuleInterop": true,
"target": "es2018",
"useDefineForClassFields": false,
"declarationMap": true
}
}

+ 1934
- 0
pnpm-lock.yaml
Datei-Diff unterdrückt, da er zu groß ist
Datei anzeigen


+ 2
- 0
pnpm-workspace.yaml Datei anzeigen

@@ -0,0 +1,2 @@
packages:
- 'packages/**'

Laden…
Abbrechen
Speichern