mirror of
https://github.com/PreMiD/PreMiD.git
synced 2026-04-06 04:41:58 +02:00
Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c44bc69d9f | ||
|
|
7d93ee3a7d | ||
|
|
79e1984940 | ||
|
|
e6526a3666 | ||
|
|
f9a976ef1d |
@@ -1 +0,0 @@
|
||||
FROM mcr.microsoft.com/devcontainers/base:bullseye
|
||||
@@ -1,24 +0,0 @@
|
||||
// For format details, see https://aka.ms/devcontainer.json. For config options, see the
|
||||
// README at: https://github.com/devcontainers/templates/tree/main/src/docker-existing-docker-compose
|
||||
{
|
||||
"name": "PreMiD",
|
||||
"dockerComposeFile": ["docker-compose.yml"],
|
||||
"service": "app",
|
||||
"workspaceFolder": "/workspaces",
|
||||
"features": {
|
||||
"ghcr.io/devcontainers/features/node:1": {
|
||||
"version": "lts",
|
||||
"nvmVersion": "latest"
|
||||
},
|
||||
"ghcr.io/joshuanianji/devcontainer-features/mount-pnpm-store:1": {},
|
||||
"ghcr.io/dhoeric/features/act:1": {}
|
||||
},
|
||||
"overrideFeatureInstallOrder": ["ghcr.io/devcontainers/features/node:1", "ghcr.io/joshuanianji/devcontainer-features/mount-pnpm-store:1"],
|
||||
"postCreateCommand": "pnpm i --frozen-lockfile",
|
||||
"customizations": {
|
||||
"vscode": {
|
||||
"extensions": ["Gruntfuggly.todo-tree", "YoavBls.pretty-ts-errors", "EditorConfig.EditorConfig", "DeepScan.vscode-deepscan", "esbenp.prettier-vscode"]
|
||||
}
|
||||
},
|
||||
"shutdownAction": "stopCompose"
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
version: "3.8"
|
||||
services:
|
||||
# Update this to the name of the service you want to work with in your docker-compose.yml file
|
||||
app:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
# Uncomment if you want to override the service's Dockerfile to one in the .devcontainer
|
||||
# folder. Note that the path of the Dockerfile and context is relative to the *primary*
|
||||
# docker-compose.yml file (the first in the devcontainer.json "dockerComposeFile"
|
||||
# array). The sample below assumes your primary file is in the root of your project.
|
||||
#
|
||||
# build:
|
||||
# context: .
|
||||
# dockerfile: .devcontainer/Dockerfile
|
||||
|
||||
volumes:
|
||||
# Update this to wherever you want VS Code to mount the folder of your project
|
||||
- ..:/workspaces:cached
|
||||
|
||||
# Uncomment the next four lines if you will use a ptrace-based debugger like C++, Go, and Rust.
|
||||
# cap_add:
|
||||
# - SYS_PTRACE
|
||||
# security_opt:
|
||||
# - seccomp:unconfined
|
||||
|
||||
# Overrides default command so things don't shut down after the process ends.
|
||||
command: /bin/sh -c "while sleep 1000; do :; done"
|
||||
redis:
|
||||
image: redis
|
||||
ports:
|
||||
- "6379:6379"
|
||||
6
.github/workflows/cd.yaml
vendored
6
.github/workflows/cd.yaml
vendored
@@ -2,7 +2,7 @@ name: CD
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- monorepo
|
||||
- main
|
||||
tags:
|
||||
- "*"
|
||||
permissions:
|
||||
@@ -17,10 +17,6 @@ jobs:
|
||||
target:
|
||||
- pd
|
||||
- schema-server
|
||||
- website
|
||||
- api-worker
|
||||
- api-master
|
||||
- discord-bot
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
6
.github/workflows/ci.yaml
vendored
6
.github/workflows/ci.yaml
vendored
@@ -2,7 +2,7 @@ name: Build, Lint and Test
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- monorepo
|
||||
- main
|
||||
pull_request:
|
||||
jobs:
|
||||
build:
|
||||
@@ -45,10 +45,6 @@ jobs:
|
||||
target:
|
||||
- pd
|
||||
- schema-server
|
||||
- api-worker
|
||||
- api-master
|
||||
- website
|
||||
- discord-bot
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
45
README.md
45
README.md
@@ -1,35 +1,44 @@
|
||||
<img src="https://cdn.rcd.gg/PreMiD.png" width="150px" />
|
||||
<img width="1280" height="800" alt="Chrome Global Screenshots" src="https://github.com/user-attachments/assets/1ea21f91-7499-43de-8b9a-3344d1c0fe48" />
|
||||
|
||||
# PreMiD
|
||||
# <img src="https://cdn.rcd.gg/PreMiD.png" height="40px" /> PreMiD
|
||||
|
||||
[](https://vscode.dev/redirect?url=vscode://ms-vscode-remote.remote-containers/cloneInVolume?url=https://github.com/PreMiD/PreMiD)
|
||||
[](https://crowdin.com/project/premid)
|
||||
|
||||
This is the monorepo for PreMiD. PreMiD is a simple, configurable utility that allows you to show what you're watching/listening to on your Discord profile.
|
||||
PreMiD is a simple, configurable utility that lets you show what you're doing on the web in your Discord profile. Whether you're watching videos, listening to music, browsing your favorite sites, or playing browser games, PreMiD helps you share your online activities with your friends through Discord's Rich Presence feature.
|
||||
|
||||
## Getting Started
|
||||
|
||||
**If you are a user looking to install PreMiD, please visit the [official website](https://premid.app).**
|
||||
**Looking to use PreMiD?** Head over to our [official website](https://premid.app) to add the browser extension!
|
||||
|
||||
If you are a developer looking to contribute to PreMiD, read along.
|
||||
**Want to create your own Activity?** All of our community-created activities are open source and available at [github.com/PreMiD/Activities](https://github.com/PreMiD/Activities). We'd love to see what you create!
|
||||
|
||||
## Table of Contents
|
||||
## Features
|
||||
|
||||
- [Packages](#packages)
|
||||
- [License](#license)
|
||||
- 🎵 Show what you're listening to on YouTube and more (Spotify has native Discord support)
|
||||
- 📺 Display what you're watching on Netflix, Disney+, Twitch, and hundreds of other sites
|
||||
- 🎮 Share your browser game activity with friends
|
||||
- ✨ Fully customizable with thousands of user-created Activities
|
||||
- 🌍 Available in multiple languages thanks to our amazing community translators
|
||||
|
||||
## Packages
|
||||
## Community
|
||||
|
||||
This monorepo is split into multiple packages / projects. Here's a list of them:
|
||||
PreMiD is built by the community, for the community. Join us and help make PreMiD even better!
|
||||
|
||||
- [apps/api](apps/api) - The API for PreMiD.
|
||||
- [apps/website](apps/website) - The website for PreMiD.
|
||||
- [apps/docs](apps/docs) - The official documentation for PreMiD.
|
||||
- [apps/pd](apps/pd/README.md) - A simple url shortener service to shorten urls longer than 256 characters.
|
||||
- [apps/schema-server](apps/schema-server) - Simple Schema server for the Presence manifest.
|
||||
- [packages/db](packages/db) - Database schema for PreMiD.
|
||||
- **Activities Repository**: [github.com/PreMiD/Activities](https://github.com/PreMiD/Activities)
|
||||
- **Documentation**: [docs.premid.app](https://docs.premid.app)
|
||||
- **Discord Server**: [discord.premid.app](https://discord.premid.app)
|
||||
- **Feedback & Bug Reports**: [feedback.premid.app](https://feedback.premid.app)
|
||||
|
||||
## Development
|
||||
## Contributing
|
||||
|
||||
We love community contributions! While **PreMiD's Activities are fully open source** (the code that makes websites show up on your profile), the PreMiD extension is not currently open source. This decision allows our small team to move fast and iterate quickly to deliver the best experience possible.
|
||||
|
||||
You can contribute by:
|
||||
|
||||
- Creating new Activities at [github.com/PreMiD/Activities](https://github.com/PreMiD/Activities)
|
||||
- Helping translate PreMiD on [Crowdin](https://crowdin.com/project/premid)
|
||||
- Reporting bugs and suggesting features at [feedback.premid.app](https://feedback.premid.app)
|
||||
- Supporting the project and spreading the word!
|
||||
|
||||
### Release
|
||||
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
import { defineConfig } from "drizzle-kit";
|
||||
|
||||
export default defineConfig({
|
||||
dbCredentials: {
|
||||
url: "postgresql://metrics:metrics@localhost:5432/metrics",
|
||||
},
|
||||
dialect: "postgresql",
|
||||
schema: "./src/db.ts",
|
||||
out: "./drizzle",
|
||||
});
|
||||
@@ -1,9 +0,0 @@
|
||||
CREATE TABLE IF NOT EXISTS "online_users_ip_data" (
|
||||
"uuid" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"ip" varchar(45) NOT NULL,
|
||||
"country" varchar(2) NOT NULL,
|
||||
"latitude" numeric(10, 8) NOT NULL,
|
||||
"longitude" numeric(11, 8) NOT NULL,
|
||||
"name" varchar(255),
|
||||
"timestamp" timestamp DEFAULT now()
|
||||
);
|
||||
@@ -1,2 +0,0 @@
|
||||
CREATE INDEX IF NOT EXISTS "idx_online_users_uuid" ON "online_users_ip_data" USING btree ("uuid");--> statement-breakpoint
|
||||
CREATE INDEX IF NOT EXISTS "idx_online_users_timestamp" ON "online_users_ip_data" USING btree ("timestamp");
|
||||
@@ -1 +0,0 @@
|
||||
ALTER TABLE "online_users_ip_data" ALTER COLUMN "timestamp" SET DATA TYPE timestamp with time zone;
|
||||
@@ -1,2 +0,0 @@
|
||||
ALTER TABLE "online_users_ip_data" ADD COLUMN "presences" jsonb DEFAULT '[]' NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "online_users_ip_data" DROP COLUMN IF EXISTS "name";
|
||||
@@ -1 +0,0 @@
|
||||
ALTER TABLE "online_users_ip_data" ADD COLUMN "sessions" integer DEFAULT 0 NOT NULL;
|
||||
@@ -1,70 +0,0 @@
|
||||
{
|
||||
"id": "e29a6708-01f1-455a-b345-63dac1e124dc",
|
||||
"prevId": "00000000-0000-0000-0000-000000000000",
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
"tables": {
|
||||
"public.online_users_ip_data": {
|
||||
"name": "online_users_ip_data",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"uuid": {
|
||||
"name": "uuid",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"default": "gen_random_uuid()"
|
||||
},
|
||||
"ip": {
|
||||
"name": "ip",
|
||||
"type": "varchar(45)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"country": {
|
||||
"name": "country",
|
||||
"type": "varchar(2)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"latitude": {
|
||||
"name": "latitude",
|
||||
"type": "numeric(10, 8)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"longitude": {
|
||||
"name": "longitude",
|
||||
"type": "numeric(11, 8)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"name": {
|
||||
"name": "name",
|
||||
"type": "varchar(255)",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"timestamp": {
|
||||
"name": "timestamp",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {}
|
||||
}
|
||||
},
|
||||
"enums": {},
|
||||
"schemas": {},
|
||||
"sequences": {},
|
||||
"_meta": {
|
||||
"columns": {},
|
||||
"schemas": {},
|
||||
"tables": {}
|
||||
}
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
{
|
||||
"id": "4aa32a8e-f573-43b9-976a-2d078a0df0ea",
|
||||
"prevId": "e29a6708-01f1-455a-b345-63dac1e124dc",
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
"tables": {
|
||||
"public.online_users_ip_data": {
|
||||
"name": "online_users_ip_data",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"uuid": {
|
||||
"name": "uuid",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"default": "gen_random_uuid()"
|
||||
},
|
||||
"ip": {
|
||||
"name": "ip",
|
||||
"type": "varchar(45)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"country": {
|
||||
"name": "country",
|
||||
"type": "varchar(2)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"latitude": {
|
||||
"name": "latitude",
|
||||
"type": "numeric(10, 8)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"longitude": {
|
||||
"name": "longitude",
|
||||
"type": "numeric(11, 8)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"name": {
|
||||
"name": "name",
|
||||
"type": "varchar(255)",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"timestamp": {
|
||||
"name": "timestamp",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"idx_online_users_uuid": {
|
||||
"name": "idx_online_users_uuid",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "uuid",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"idx_online_users_timestamp": {
|
||||
"name": "idx_online_users_timestamp",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "timestamp",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {}
|
||||
}
|
||||
},
|
||||
"enums": {},
|
||||
"schemas": {},
|
||||
"sequences": {},
|
||||
"_meta": {
|
||||
"columns": {},
|
||||
"schemas": {},
|
||||
"tables": {}
|
||||
}
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
{
|
||||
"id": "c1b8dbed-b232-4d66-9e74-b9af333095bc",
|
||||
"prevId": "4aa32a8e-f573-43b9-976a-2d078a0df0ea",
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
"tables": {
|
||||
"public.online_users_ip_data": {
|
||||
"name": "online_users_ip_data",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"uuid": {
|
||||
"name": "uuid",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"default": "gen_random_uuid()"
|
||||
},
|
||||
"ip": {
|
||||
"name": "ip",
|
||||
"type": "varchar(45)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"country": {
|
||||
"name": "country",
|
||||
"type": "varchar(2)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"latitude": {
|
||||
"name": "latitude",
|
||||
"type": "numeric(10, 8)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"longitude": {
|
||||
"name": "longitude",
|
||||
"type": "numeric(11, 8)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"name": {
|
||||
"name": "name",
|
||||
"type": "varchar(255)",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"timestamp": {
|
||||
"name": "timestamp",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"idx_online_users_uuid": {
|
||||
"name": "idx_online_users_uuid",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "uuid",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"idx_online_users_timestamp": {
|
||||
"name": "idx_online_users_timestamp",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "timestamp",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {}
|
||||
}
|
||||
},
|
||||
"enums": {},
|
||||
"schemas": {},
|
||||
"sequences": {},
|
||||
"_meta": {
|
||||
"columns": {},
|
||||
"schemas": {},
|
||||
"tables": {}
|
||||
}
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
{
|
||||
"id": "e409a4d0-f698-484a-b412-38966a7b3a19",
|
||||
"prevId": "c1b8dbed-b232-4d66-9e74-b9af333095bc",
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
"tables": {
|
||||
"public.online_users_ip_data": {
|
||||
"name": "online_users_ip_data",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"uuid": {
|
||||
"name": "uuid",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"default": "gen_random_uuid()"
|
||||
},
|
||||
"ip": {
|
||||
"name": "ip",
|
||||
"type": "varchar(45)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"country": {
|
||||
"name": "country",
|
||||
"type": "varchar(2)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"latitude": {
|
||||
"name": "latitude",
|
||||
"type": "numeric(10, 8)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"longitude": {
|
||||
"name": "longitude",
|
||||
"type": "numeric(11, 8)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"presences": {
|
||||
"name": "presences",
|
||||
"type": "jsonb",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'[]'"
|
||||
},
|
||||
"timestamp": {
|
||||
"name": "timestamp",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"idx_online_users_uuid": {
|
||||
"name": "idx_online_users_uuid",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "uuid",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"idx_online_users_timestamp": {
|
||||
"name": "idx_online_users_timestamp",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "timestamp",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {}
|
||||
}
|
||||
},
|
||||
"enums": {},
|
||||
"schemas": {},
|
||||
"sequences": {},
|
||||
"_meta": {
|
||||
"columns": {},
|
||||
"schemas": {},
|
||||
"tables": {}
|
||||
}
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
{
|
||||
"id": "179435b5-dc15-4a42-9539-c3f336699d63",
|
||||
"prevId": "e409a4d0-f698-484a-b412-38966a7b3a19",
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
"tables": {
|
||||
"public.online_users_ip_data": {
|
||||
"name": "online_users_ip_data",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"uuid": {
|
||||
"name": "uuid",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"default": "gen_random_uuid()"
|
||||
},
|
||||
"ip": {
|
||||
"name": "ip",
|
||||
"type": "varchar(45)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"country": {
|
||||
"name": "country",
|
||||
"type": "varchar(2)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"latitude": {
|
||||
"name": "latitude",
|
||||
"type": "numeric(10, 8)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"longitude": {
|
||||
"name": "longitude",
|
||||
"type": "numeric(11, 8)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"sessions": {
|
||||
"name": "sessions",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": 0
|
||||
},
|
||||
"presences": {
|
||||
"name": "presences",
|
||||
"type": "jsonb",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'[]'"
|
||||
},
|
||||
"timestamp": {
|
||||
"name": "timestamp",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"idx_online_users_uuid": {
|
||||
"name": "idx_online_users_uuid",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "uuid",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"idx_online_users_timestamp": {
|
||||
"name": "idx_online_users_timestamp",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "timestamp",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {}
|
||||
}
|
||||
},
|
||||
"enums": {},
|
||||
"schemas": {},
|
||||
"sequences": {},
|
||||
"_meta": {
|
||||
"columns": {},
|
||||
"schemas": {},
|
||||
"tables": {}
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
{
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
"entries": [
|
||||
{
|
||||
"idx": 0,
|
||||
"version": "7",
|
||||
"when": 1726516195146,
|
||||
"tag": "0000_flippant_marrow",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 1,
|
||||
"version": "7",
|
||||
"when": 1726516348344,
|
||||
"tag": "0001_white_lifeguard",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 2,
|
||||
"version": "7",
|
||||
"when": 1726516660134,
|
||||
"tag": "0002_new_darkhawk",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 3,
|
||||
"version": "7",
|
||||
"when": 1726517073510,
|
||||
"tag": "0003_narrow_mastermind",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 4,
|
||||
"version": "7",
|
||||
"when": 1726517405363,
|
||||
"tag": "0004_tiresome_puff_adder",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
5
apps/api-master/environment.d.ts
vendored
5
apps/api-master/environment.d.ts
vendored
@@ -1,5 +0,0 @@
|
||||
declare namespace NodeJS {
|
||||
export interface ProcessEnv {
|
||||
METRICS_DATABASE_URL?: string;
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
{
|
||||
"name": "@premid/api-master",
|
||||
"type": "module",
|
||||
"version": "0.0.39",
|
||||
"private": true,
|
||||
"description": "PreMiD's api master",
|
||||
"license": "MPL-2.0",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"start": "node --enable-source-maps .",
|
||||
"dev": "node --watch --env-file .env --enable-source-maps .",
|
||||
"db:generate": "drizzle-kit generate",
|
||||
"db:migrate": "drizzle-kit migrate",
|
||||
"db:update": "pnpm db:generate && pnpm db:migrate",
|
||||
"db:studio": "drizzle-kit studio"
|
||||
},
|
||||
"dependencies": {
|
||||
"@envelop/sentry": "^9.0.0",
|
||||
"@sentry/node": "^8.17.0",
|
||||
"cron": "^3.1.7",
|
||||
"debug": "^4.3.6",
|
||||
"drizzle-orm": "^0.33.0",
|
||||
"ioredis": "^5.3.2",
|
||||
"ky": "^1.7.2",
|
||||
"p-limit": "^6.1.0",
|
||||
"postgres": "^3.4.4",
|
||||
"prom-client": "^15.1.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/debug": "^4.1.12",
|
||||
"drizzle-kit": "^0.24.2"
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
import process from "node:process";
|
||||
import { decimal, index, integer, jsonb, pgTable, timestamp, uuid, varchar } from "drizzle-orm/pg-core";
|
||||
import { drizzle } from "drizzle-orm/postgres-js";
|
||||
import postgres from "postgres";
|
||||
|
||||
// Define the schema
|
||||
export const onlineUsersIpData = pgTable("online_users_ip_data", {
|
||||
uuid: uuid("uuid").primaryKey().defaultRandom(),
|
||||
ip: varchar("ip", { length: 45 }).notNull(),
|
||||
country: varchar("country", { length: 2 }).notNull(),
|
||||
latitude: decimal("latitude", { precision: 10, scale: 8 }).notNull(),
|
||||
longitude: decimal("longitude", { precision: 11, scale: 8 }).notNull(),
|
||||
sessions: integer("sessions").notNull().default(0),
|
||||
presences: jsonb("presences").notNull().default("[]").$type<string[]>(),
|
||||
timestamp: timestamp("timestamp", { withTimezone: true }).defaultNow(),
|
||||
}, table => ({
|
||||
idxOnlineUsersUuid: index("idx_online_users_uuid").on(table.uuid),
|
||||
idxOnlineUsersTimestamp: index("idx_online_users_timestamp").on(table.timestamp),
|
||||
}));
|
||||
|
||||
if (!process.env.METRICS_DATABASE_URL) {
|
||||
throw new Error("METRICS_DATABASE_URL is not set");
|
||||
}
|
||||
|
||||
export const sql = postgres(process.env.METRICS_DATABASE_URL);
|
||||
|
||||
export const db = drizzle(sql);
|
||||
@@ -1,10 +0,0 @@
|
||||
import { lt, sql } from "drizzle-orm";
|
||||
import { db, onlineUsersIpData } from "../db.js";
|
||||
import { mainLog } from "../index.js";
|
||||
|
||||
export async function cleanupOldUserData(retentionDays: number) {
|
||||
mainLog("Cleaning up old user ip data");
|
||||
const interval = `'${retentionDays} days'`;
|
||||
await db.delete(onlineUsersIpData)
|
||||
.where(lt(onlineUsersIpData.timestamp, sql`now() - interval ${sql.raw(interval)}`));
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
import pLimit from "p-limit";
|
||||
import ky, { HTTPError, TimeoutError } from "ky";
|
||||
import { mainLog, redis } from "../index.js";
|
||||
|
||||
let inProgress = false;
|
||||
export async function clearOldSessions() {
|
||||
if (inProgress) {
|
||||
mainLog("Session cleanup already in progress");
|
||||
return;
|
||||
}
|
||||
|
||||
inProgress = true;
|
||||
const now = Date.now();
|
||||
const pattern = "pmd-api.sessions.*";
|
||||
let cursor = "0";
|
||||
let totalSessions = 0;
|
||||
let cleared = 0;
|
||||
const batchSize = 100;
|
||||
let keysToDelete: string[] = [];
|
||||
|
||||
mainLog("Starting session cleanup");
|
||||
|
||||
const limit = pLimit(100); // Create a limit of 100 concurrent operations
|
||||
|
||||
do {
|
||||
const [newCursor, keys] = await redis.scan(cursor, "MATCH", pattern, "COUNT", 1000); //* Use SCAN with COUNT for memory efficiency
|
||||
|
||||
cursor = newCursor;
|
||||
totalSessions += keys.length;
|
||||
|
||||
const deletePromises: Promise<string>[] = [];
|
||||
|
||||
for (const key of keys) {
|
||||
const session = await redis.hgetall(key) as unknown as {
|
||||
token: string;
|
||||
session: string;
|
||||
lastUpdated: number;
|
||||
};
|
||||
|
||||
if (now - session.lastUpdated < 30000)
|
||||
continue;
|
||||
|
||||
deletePromises.push(limit(() => deleteSession(session, key)));
|
||||
}
|
||||
|
||||
const results = await Promise.allSettled(deletePromises);
|
||||
results.forEach((result) => {
|
||||
if (result.status === "fulfilled" && result.value) {
|
||||
keysToDelete.push(result.value);
|
||||
cleared++;
|
||||
}
|
||||
});
|
||||
|
||||
if (keysToDelete.length >= batchSize) {
|
||||
await redis.del(...keysToDelete);
|
||||
keysToDelete = [];
|
||||
}
|
||||
} while (cursor !== "0");
|
||||
|
||||
if (keysToDelete.length > 0) {
|
||||
await redis.del(...keysToDelete);
|
||||
}
|
||||
|
||||
if (totalSessions === 0) {
|
||||
mainLog("No sessions to clear");
|
||||
}
|
||||
else {
|
||||
mainLog(`Checked ${totalSessions} sessions, cleared ${cleared}`);
|
||||
}
|
||||
|
||||
inProgress = false;
|
||||
}
|
||||
|
||||
async function deleteSession(session: { token: string; session: string }, key: string): Promise<string> {
|
||||
try {
|
||||
await ky.post("https://discord.com/api/v10/users/@me/headless-sessions/delete", {
|
||||
json: {
|
||||
token: session.session,
|
||||
},
|
||||
headers: {
|
||||
Authorization: `Bearer ${session.token}`,
|
||||
},
|
||||
retry: 3,
|
||||
timeout: 5000,
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
if (error instanceof TimeoutError) {
|
||||
mainLog(`Session deletion aborted due to timeout for key ${key}`);
|
||||
}
|
||||
else if (error instanceof HTTPError) {
|
||||
mainLog(`Failed to delete session for key ${key}: [${error.name}] ${error.message} ${JSON.stringify(await error.response.json())}`);
|
||||
}
|
||||
else {
|
||||
mainLog(`Failed to delete session for key ${key}: Unknown error`);
|
||||
}
|
||||
}
|
||||
|
||||
return key;
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
import { hostname } from "node:os";
|
||||
import process from "node:process";
|
||||
|
||||
import { Redis } from "ioredis";
|
||||
|
||||
/* c8 ignore start */
|
||||
export default function createRedis(): Redis {
|
||||
const redis = new Redis({
|
||||
connectionName: `api-master-${hostname()}-${process.pid.toString()}`,
|
||||
lazyConnect: true,
|
||||
name: "mymaster",
|
||||
sentinels: process.env.REDIS_SENTINELS?.split(",").map(s => ({
|
||||
host: s,
|
||||
port: 26_379,
|
||||
})),
|
||||
});
|
||||
|
||||
/* c8 ignore next 3 */
|
||||
redis.on("error", (error) => {
|
||||
console.error("Redis error", error);
|
||||
});
|
||||
|
||||
/* c8 ignore next 4 */
|
||||
redis.on("connect", () => {
|
||||
// eslint-disable-next-line no-console
|
||||
console.log("Redis connected");
|
||||
});
|
||||
|
||||
return redis;
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
import type { InferInsertModel } from "drizzle-orm";
|
||||
import { db, onlineUsersIpData } from "../db.js";
|
||||
import { lookupIp } from "./lookupIp.js";
|
||||
|
||||
const batchSize = 1000;
|
||||
|
||||
export async function insertIpData(
|
||||
data: Map<string, {
|
||||
presences: string[];
|
||||
sessions: number;
|
||||
}>,
|
||||
) {
|
||||
const timestamp = new Date();
|
||||
const list = [...data.keys()];
|
||||
//* Split into batches of batchSize
|
||||
for (let i = 0; i < list.length; i += batchSize) {
|
||||
const batch = list.slice(i, i + batchSize);
|
||||
const mapped = await Promise.all(batch.map(async (ip) => {
|
||||
const parsed = await lookupIp(ip);
|
||||
if (parsed) {
|
||||
const { presences, sessions } = data.get(ip)!;
|
||||
return {
|
||||
ip,
|
||||
country: parsed.country,
|
||||
latitude: parsed.latitude.toString(),
|
||||
longitude: parsed.longitude.toString(),
|
||||
presences,
|
||||
sessions,
|
||||
timestamp,
|
||||
} satisfies InferInsertModel<typeof onlineUsersIpData>;
|
||||
}
|
||||
}));
|
||||
|
||||
const toInsert = mapped.filter(Boolean) as InferInsertModel<typeof onlineUsersIpData>[];
|
||||
|
||||
if (toInsert.length > 0) {
|
||||
await db.insert(onlineUsersIpData).values(toInsert);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
export async function lookupIp(_ip: string): Promise<{ latitude: number; longitude: number; country: string } | undefined> {
|
||||
return undefined;
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
import http from "node:http";
|
||||
import { mainLog } from "../index.js";
|
||||
import { register } from "../tracing.js";
|
||||
|
||||
export function setupServer() {
|
||||
const server = http.createServer(async (req, res) => {
|
||||
//* If it's a head request, just return 200
|
||||
if (req.method === "HEAD")
|
||||
return res.writeHead(200).end();
|
||||
|
||||
//* If it's a favicon request, just return 404
|
||||
if (req.url === "/favicon.ico")
|
||||
return res.writeHead(404).end();
|
||||
|
||||
//* Basic routing logic
|
||||
res.writeHead(200, { "Content-Type": "text/plain" });
|
||||
res.end(await register.metrics());
|
||||
});
|
||||
|
||||
server.listen(9464, () => {
|
||||
mainLog("Server running");
|
||||
});
|
||||
|
||||
return server;
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
import process from "node:process";
|
||||
import pLimit from "p-limit";
|
||||
import type { Gauge } from "prom-client";
|
||||
import { mainLog, redis } from "../index.js";
|
||||
import { insertIpData } from "./insertIpData.js";
|
||||
|
||||
export const updateActivePresenceGaugeLimit = pLimit(1);
|
||||
let log: debug.Debugger | undefined;
|
||||
|
||||
const scanCount = Number.parseInt(process.env.SCAN_COUNT || "1000", 10);
|
||||
|
||||
export async function updateActivePresenceGauge(gauge: Gauge) {
|
||||
await updateActivePresenceGaugeLimit(async () => {
|
||||
log ??= mainLog.extend("Heartbeat-Updates");
|
||||
log?.("Starting active presence gauge update");
|
||||
|
||||
const pattern = "pmd-api.heartbeatUpdates.*";
|
||||
let cursor: string = "0";
|
||||
const serviceCounts = new Map<string, number>();
|
||||
const ips = new Map<string, {
|
||||
presences: Set<string>;
|
||||
sessions: number;
|
||||
}>();
|
||||
|
||||
do {
|
||||
const [newCursor, keys] = await redis.scan(cursor, "MATCH", pattern, "COUNT", scanCount);
|
||||
cursor = newCursor;
|
||||
|
||||
//* Use pipelining for batch Redis operations
|
||||
const pipeline = redis.pipeline();
|
||||
keys.forEach(key => pipeline.hmget(key, "service", "version", "ip_address"));
|
||||
const hashes = await pipeline.exec();
|
||||
|
||||
if (!hashes) {
|
||||
log?.("No hashes found");
|
||||
return;
|
||||
}
|
||||
|
||||
hashes.forEach(([err, hash]) => {
|
||||
if (err || !Array.isArray(hash))
|
||||
return;
|
||||
|
||||
const [service, version, ip] = hash;
|
||||
const serviceVersion = service && version ? `${service}:${version}` : "none";
|
||||
serviceCounts.set(serviceVersion, (serviceCounts.get(serviceVersion) || 0) + 1);
|
||||
|
||||
if (ip) {
|
||||
const ipData = ips.get(ip) || { presences: new Set(), sessions: 0 };
|
||||
if (serviceVersion !== "none")
|
||||
ipData.presences.add(serviceVersion);
|
||||
ipData.sessions++;
|
||||
ips.set(ip, ipData);
|
||||
}
|
||||
});
|
||||
} while (cursor !== "0");
|
||||
|
||||
log?.("Updating active presence gauge");
|
||||
|
||||
//* Batch update the gauge
|
||||
gauge.reset();
|
||||
for (const [serviceVersion, count] of serviceCounts) {
|
||||
const [presence_name, version] = serviceVersion.split(":");
|
||||
gauge.set({ presence_name, version }, count);
|
||||
}
|
||||
|
||||
//* Convert IP data for insertion
|
||||
const ipDataForInsertion = new Map(
|
||||
Array.from(ips, ([ip, data]) => [ip, {
|
||||
presences: Array.from(data.presences),
|
||||
sessions: data.sessions,
|
||||
}]),
|
||||
);
|
||||
|
||||
await insertIpData(ipDataForInsertion);
|
||||
log?.("Active presence gauge update completed");
|
||||
});
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
import process from "node:process";
|
||||
import pLimit from "p-limit";
|
||||
import type { Gauge } from "prom-client";
|
||||
import { mainLog, redis } from "../index.js";
|
||||
|
||||
export const updateExtensionVersionGaugeLimit = pLimit(1);
|
||||
let log: debug.Debugger | undefined;
|
||||
|
||||
const scanCount = Number.parseInt(process.env.SCAN_COUNT || "1000", 10);
|
||||
|
||||
export async function updateExtensionVersionGauge(gauge: Gauge) {
|
||||
await updateExtensionVersionGaugeLimit(async () => {
|
||||
log ??= mainLog.extend("Extension-Version-Updates");
|
||||
log?.("Starting extension version gauge update");
|
||||
|
||||
const pattern = "pmd-api.heartbeatUpdates.*";
|
||||
let cursor: string = "0";
|
||||
const versionCounts = new Map<string, number>();
|
||||
|
||||
do {
|
||||
const [newCursor, keys] = await redis.scan(cursor, "MATCH", pattern, "COUNT", scanCount);
|
||||
cursor = newCursor;
|
||||
|
||||
//* Use pipelining for batch Redis operations
|
||||
const pipeline = redis.pipeline();
|
||||
keys.forEach(key => pipeline.hmget(key, "extension_version"));
|
||||
const hashes = await pipeline.exec();
|
||||
|
||||
if (!hashes) {
|
||||
log?.("No hashes found");
|
||||
return;
|
||||
}
|
||||
|
||||
hashes.forEach(([err, hash]) => {
|
||||
if (err || !Array.isArray(hash))
|
||||
return;
|
||||
|
||||
const [version] = hash;
|
||||
if (version && typeof version === "string")
|
||||
versionCounts.set(version, (versionCounts.get(version) || 0) + 1);
|
||||
});
|
||||
} while (cursor !== "0");
|
||||
|
||||
log?.("Updating extension version gauge");
|
||||
|
||||
//* Batch update the gauge
|
||||
gauge.reset();
|
||||
for (const [version, count] of versionCounts) {
|
||||
gauge.set({ version }, count);
|
||||
}
|
||||
|
||||
log?.("Extension version gauge update completed");
|
||||
});
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
import process from "node:process";
|
||||
import { CronJob } from "cron";
|
||||
import debug from "debug";
|
||||
import { clearOldSessions } from "./functions/clearOldSessions.js";
|
||||
import createRedis from "./functions/createRedis.js";
|
||||
import "./tracing.js";
|
||||
import { cleanupOldUserData } from "./functions/cleanupOldUserData.js";
|
||||
import { setupServer } from "./functions/setupServer.js";
|
||||
|
||||
export const redis = createRedis();
|
||||
|
||||
export const server = setupServer();
|
||||
|
||||
export const mainLog = debug("api-master");
|
||||
|
||||
debug("Starting cron jobs");
|
||||
|
||||
void new CronJob(
|
||||
// Every 5 seconds
|
||||
"*/5 * * * * *",
|
||||
() => {
|
||||
if (process.env.DISABLE_CLEAR_OLD_SESSIONS !== "true") {
|
||||
clearOldSessions();
|
||||
}
|
||||
},
|
||||
undefined,
|
||||
true,
|
||||
);
|
||||
|
||||
void new CronJob(
|
||||
// Every day at 1am
|
||||
"0 1 * * *",
|
||||
() => {
|
||||
cleanupOldUserData(14); // Keep 14 days of data
|
||||
},
|
||||
undefined,
|
||||
true,
|
||||
undefined,
|
||||
undefined,
|
||||
true,
|
||||
);
|
||||
@@ -1,54 +0,0 @@
|
||||
import process from "node:process";
|
||||
import { Counter, Gauge, Registry, collectDefaultMetrics } from "prom-client";
|
||||
import { updateActivePresenceGauge, updateActivePresenceGaugeLimit } from "./functions/updateActivePresenceGauge.js";
|
||||
import { updateExtensionVersionGauge, updateExtensionVersionGaugeLimit } from "./functions/updateVersionGauge.js";
|
||||
import { redis } from "./index.js";
|
||||
|
||||
const scanCount = Number.parseInt(process.env.SCAN_COUNT || "1000", 10);
|
||||
|
||||
export const register = new Registry();
|
||||
collectDefaultMetrics({ register });
|
||||
|
||||
export const activeSessionsCounter = new Counter({
|
||||
name: "active_sessions",
|
||||
help: "Number of active sessions",
|
||||
async collect() {
|
||||
this.reset();
|
||||
let length = 0;
|
||||
let cursor = "0";
|
||||
do {
|
||||
const reply = await redis.scan(cursor, "MATCH", "pmd-api.sessions.*", "COUNT", scanCount);
|
||||
cursor = reply[0];
|
||||
length += reply[1].length;
|
||||
} while (cursor !== "0");
|
||||
this.inc(length);
|
||||
},
|
||||
});
|
||||
|
||||
export const activePresencesCounter = new Gauge({
|
||||
name: "active_presences",
|
||||
help: "Number of active presences",
|
||||
labelNames: ["presence_name", "version"],
|
||||
async collect() {
|
||||
if (process.env.DISABLE_ACTIVE_PRESENCE_GAUGE !== "true") {
|
||||
this.reset();
|
||||
updateActivePresenceGaugeLimit.clearQueue();
|
||||
await updateActivePresenceGauge(this);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const versionCounter = new Gauge({
|
||||
name: "extension_version",
|
||||
help: "The version of the extension with the amount of users using it",
|
||||
labelNames: ["version"],
|
||||
async collect() {
|
||||
this.reset();
|
||||
updateExtensionVersionGaugeLimit.clearQueue();
|
||||
await updateExtensionVersionGauge(this);
|
||||
},
|
||||
});
|
||||
|
||||
register.registerMetric(activeSessionsCounter);
|
||||
register.registerMetric(activePresencesCounter);
|
||||
register.registerMetric(versionCounter);
|
||||
@@ -1,10 +0,0 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"rootDir": "src",
|
||||
"types": ["./environment.d.ts"],
|
||||
"outDir": "dist"
|
||||
},
|
||||
"include": ["src/**/*"]
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"extends": "./tsconfig.app.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": ".",
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["environment.d.ts", "src", "codegen.ts"]
|
||||
}
|
||||
1
apps/api-worker/.gitignore
vendored
1
apps/api-worker/.gitignore
vendored
@@ -1 +0,0 @@
|
||||
generated
|
||||
@@ -1,26 +0,0 @@
|
||||
import type { CodegenConfig } from "@graphql-codegen/cli";
|
||||
|
||||
const config: CodegenConfig = {
|
||||
generates: {
|
||||
"dist/generated/schema-v5.graphql": {
|
||||
plugins: ["schema-ast"],
|
||||
schema: "src/graphql/schema/v5/**/*.gql",
|
||||
},
|
||||
"src/generated/graphql-v5.ts": {
|
||||
config: {
|
||||
scalars: {
|
||||
StringOrStringArray: "string | string[]",
|
||||
},
|
||||
},
|
||||
plugins: ["typescript", "typescript-resolvers"],
|
||||
schema: "src/graphql/schema/v5/**/*.gql",
|
||||
},
|
||||
"src/generated/schema-v5.graphql": {
|
||||
plugins: ["schema-ast"],
|
||||
schema: "src/graphql/schema/v5/**/*.gql",
|
||||
},
|
||||
},
|
||||
overwrite: true,
|
||||
};
|
||||
|
||||
export default config;
|
||||
8
apps/api-worker/environment.d.ts
vendored
8
apps/api-worker/environment.d.ts
vendored
@@ -1,8 +0,0 @@
|
||||
declare namespace NodeJS {
|
||||
export interface ProcessEnv {
|
||||
NODE_ENV?: "development" | "production" | "test";
|
||||
DATABASE_URL?: string;
|
||||
SESSION_KEEP_ALIVE_INTERVAL?: string;
|
||||
HEARTBEATS?: "true" | "false";
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
{
|
||||
"name": "@premid/api-worker",
|
||||
"type": "module",
|
||||
"version": "0.0.19",
|
||||
"private": true,
|
||||
"description": "PreMiD's api",
|
||||
"license": "MPL-2.0",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"start": "node --enable-source-maps .",
|
||||
"dev": "node --watch --env-file .env --enable-source-maps .",
|
||||
"build": "pnpm codegen",
|
||||
"codegen": "graphql-codegen --config codegen.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@discordjs/rest": "^2.3.0",
|
||||
"@envelop/sentry": "^9.0.0",
|
||||
"@escape.tech/graphql-armor-max-aliases": "^2.5.0",
|
||||
"@escape.tech/graphql-armor-max-depth": "^2.3.0",
|
||||
"@escape.tech/graphql-armor-max-directives": "^2.2.0",
|
||||
"@escape.tech/graphql-armor-max-tokens": "^2.4.0",
|
||||
"@fastify/websocket": "^10.0.1",
|
||||
"@opentelemetry/api": "^1.9.0",
|
||||
"@opentelemetry/exporter-prometheus": "^0.52.1",
|
||||
"@opentelemetry/node": "^0.24.0",
|
||||
"@premid/db": "workspace:*",
|
||||
"@sentry/node": "^8.17.0",
|
||||
"arktype": "2.0.0-rc.6",
|
||||
"defu": "^6.1.4",
|
||||
"discord-api-types": "^0.37.92",
|
||||
"fastify": "^4.28.1",
|
||||
"graphql": "^16.9.0",
|
||||
"graphql-parse-resolve-info": "^4.13.0",
|
||||
"graphql-yoga": "^5.6.0",
|
||||
"ioredis": "^5.3.2",
|
||||
"mongoose": "^8.6.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@graphql-codegen/cli": "5.0.2",
|
||||
"@graphql-codegen/schema-ast": "^4.1.0",
|
||||
"@graphql-codegen/typescript": "4.0.9",
|
||||
"@graphql-codegen/typescript-resolvers": "4.2.1",
|
||||
"@parcel/watcher": "^2.4.1",
|
||||
"@types/ws": "^8.5.12"
|
||||
}
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
import { REST } from "@discordjs/rest";
|
||||
import { scope, type } from "arktype";
|
||||
import { Routes } from "discord-api-types/v10";
|
||||
import WebSocket from "ws";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import type { RawData } from "ws";
|
||||
import { redis } from "../functions/createServer.js";
|
||||
import { counter } from "../tracing.js";
|
||||
|
||||
const schema = scope({
|
||||
token: {
|
||||
"+": "delete",
|
||||
"type": "'token'",
|
||||
"token": "string.trim",
|
||||
"expires": "number.epoch",
|
||||
},
|
||||
session: {
|
||||
"+": "delete",
|
||||
"type": "'session'",
|
||||
"token": "string.trim",
|
||||
},
|
||||
validMessages: "token | session",
|
||||
}).export();
|
||||
|
||||
export class Socket {
|
||||
currentToken: typeof schema.token.infer | undefined;
|
||||
currentSession: typeof schema.session.infer | undefined;
|
||||
discord = new REST({ version: "10", authPrefix: "Bearer" });
|
||||
|
||||
constructor(
|
||||
public readonly socket: WebSocket.WebSocket,
|
||||
public readonly request: FastifyRequest,
|
||||
) {
|
||||
counter.add(1);
|
||||
socket.on("message", this.onMessage.bind(this));
|
||||
socket.on("close", () => this.onClose());
|
||||
}
|
||||
|
||||
async onMessage(message: RawData) {
|
||||
try {
|
||||
const out = schema.validMessages(JSON.parse(message.toString()));
|
||||
|
||||
if (out instanceof type.errors) {
|
||||
return this.close(1003, out.summary);
|
||||
}
|
||||
|
||||
switch (out.type) {
|
||||
case "token": {
|
||||
this.discord.setToken(out.token);
|
||||
if (!await this.isTokenValid(out)) {
|
||||
return this.close(1003, "Invalid token");
|
||||
}
|
||||
this.currentToken = out;
|
||||
break;
|
||||
}
|
||||
case "session": {
|
||||
await redis.hdel("pmd-api.sessions", out.token);
|
||||
this.currentSession = out;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
console.error(error);
|
||||
this.close(1011, "Internal Error");
|
||||
}
|
||||
}
|
||||
|
||||
async onClose() {
|
||||
counter.add(-1);
|
||||
|
||||
if (!this.currentToken || !this.currentSession)
|
||||
return;
|
||||
|
||||
await redis.hset(
|
||||
"pmd-api.sessions",
|
||||
this.currentSession.token,
|
||||
JSON.stringify({
|
||||
session: this.currentSession.token,
|
||||
token: this.currentToken.token,
|
||||
lastUpdated: Date.now(),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async isTokenValid(token: typeof schema.token.infer) {
|
||||
// ? Check the expiration date of the token
|
||||
if (token.expires < Date.now())
|
||||
return false;
|
||||
|
||||
// ? See if we can get the user's information
|
||||
try {
|
||||
await this.discord.get(Routes.user());
|
||||
return true;
|
||||
}
|
||||
catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
send(data: any) {
|
||||
this.socket.send(JSON.stringify(data));
|
||||
}
|
||||
|
||||
close(code: number = 1000, message?: string) {
|
||||
if (this.socket.readyState === WebSocket.CLOSED)
|
||||
return;
|
||||
this.socket.close(code, message);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
import process from "node:process";
|
||||
import { defu } from "defu";
|
||||
|
||||
const disabledFlags = process.env.DISABLED_FEATURE_FLAGS?.split(",") ?? [];
|
||||
const flags = Object.fromEntries(disabledFlags.map(flag => [flag, false]));
|
||||
|
||||
export const featureFlags = defu(flags, {
|
||||
WebSocketManager: true,
|
||||
SessionKeepAlive: true,
|
||||
});
|
||||
@@ -1,30 +0,0 @@
|
||||
import { hostname } from "node:os";
|
||||
import process from "node:process";
|
||||
|
||||
import { Redis } from "ioredis";
|
||||
|
||||
/* c8 ignore start */
|
||||
export default function createRedis(): Redis {
|
||||
const redis = new Redis({
|
||||
connectionName: `api-${hostname()}-${process.pid.toString()}`,
|
||||
lazyConnect: true,
|
||||
name: "mymaster",
|
||||
sentinels: process.env.REDIS_SENTINELS?.split(",").map(s => ({
|
||||
host: s,
|
||||
port: 26_379,
|
||||
})),
|
||||
});
|
||||
|
||||
/* c8 ignore next 3 */
|
||||
redis.on("error", (error) => {
|
||||
console.error("Redis error", error);
|
||||
});
|
||||
|
||||
/* c8 ignore next 4 */
|
||||
redis.on("connect", () => {
|
||||
// eslint-disable-next-line no-console
|
||||
console.log("Redis connected");
|
||||
});
|
||||
|
||||
return redis;
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
describe.concurrent("createServer", () => {
|
||||
it("should create a server", async () => {
|
||||
const createServer = await import("./createServer.js");
|
||||
const server = await createServer.default();
|
||||
expect(server).toBeDefined();
|
||||
expect(server).toHaveProperty("listen");
|
||||
});
|
||||
|
||||
it("should handle graphql requests", async () => {
|
||||
const createServer = await import("./createServer.js");
|
||||
const server = await createServer.default();
|
||||
expect(server).toBeDefined();
|
||||
expect(server).toHaveProperty("listen");
|
||||
|
||||
const response = await server.inject({
|
||||
method: "GET",
|
||||
url: "/v5/graphql",
|
||||
});
|
||||
|
||||
expect(response).toBeDefined();
|
||||
expect(response.statusCode).toBe(200);
|
||||
});
|
||||
});
|
||||
@@ -1,98 +0,0 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { maxAliasesPlugin } from "@escape.tech/graphql-armor-max-aliases";
|
||||
import { maxDepthPlugin } from "@escape.tech/graphql-armor-max-depth";
|
||||
import { maxDirectivesPlugin } from "@escape.tech/graphql-armor-max-directives";
|
||||
import { maxTokensPlugin } from "@escape.tech/graphql-armor-max-tokens";
|
||||
import fastifyWebsocket from "@fastify/websocket";
|
||||
import fastify from "fastify";
|
||||
|
||||
import { createSchema, createYoga } from "graphql-yoga";
|
||||
import type { FastifyReply, FastifyRequest } from "fastify";
|
||||
import { Socket } from "../classes/Socket.js";
|
||||
import { resolvers } from "../graphql/resolvers/v5/index.js";
|
||||
import { sessionKeepAlive } from "../routes/sessionKeepAlive.js";
|
||||
import { featureFlags } from "../constants.js";
|
||||
import { presences } from "../routes/presences.js";
|
||||
import createRedis from "./createRedis.js";
|
||||
|
||||
export interface FastifyContext {
|
||||
request: FastifyRequest;
|
||||
reply: FastifyReply;
|
||||
}
|
||||
|
||||
const __dirname = new URL(".", import.meta.url).pathname;
|
||||
|
||||
export default async function createServer() {
|
||||
const app = fastify({ logger: true });
|
||||
const yoga = createYoga<FastifyContext>({
|
||||
graphqlEndpoint: "/v5/graphql",
|
||||
logging: {
|
||||
/* c8 ignore next 12 */
|
||||
debug: (...arguments_) => {
|
||||
for (const argument of arguments_) app.log.debug(argument);
|
||||
},
|
||||
error: (...arguments_) => {
|
||||
for (const argument of arguments_) app.log.error(argument);
|
||||
},
|
||||
info: (...arguments_) => {
|
||||
for (const argument of arguments_) app.log.info(argument);
|
||||
},
|
||||
warn: (...arguments_) => {
|
||||
for (const argument of arguments_) app.log.warn(argument);
|
||||
},
|
||||
},
|
||||
plugins: [
|
||||
maxAliasesPlugin(),
|
||||
maxDepthPlugin(),
|
||||
maxDirectivesPlugin(),
|
||||
maxTokensPlugin(),
|
||||
/* useSentry(), */
|
||||
],
|
||||
schema: createSchema<FastifyContext>({
|
||||
resolvers,
|
||||
typeDefs: await readFile(
|
||||
resolve(__dirname, "../generated/schema-v5.graphql"),
|
||||
"utf8",
|
||||
),
|
||||
}),
|
||||
});
|
||||
|
||||
app.route({
|
||||
handler: async (request, reply) => {
|
||||
const response = await yoga.handleNodeRequest(request, {
|
||||
reply,
|
||||
request,
|
||||
});
|
||||
for (const [key, value] of response.headers.entries())
|
||||
void reply.header(key, value);
|
||||
|
||||
void reply.status(response.status);
|
||||
|
||||
void reply.send(response.body);
|
||||
|
||||
return reply;
|
||||
},
|
||||
method: ["GET", "POST", "OPTIONS"],
|
||||
url: "/v5/graphql",
|
||||
});
|
||||
|
||||
app.register(fastifyWebsocket);
|
||||
|
||||
app.register(async (app) => {
|
||||
app.get("/v5/ws", { websocket: true }, (websocket, request) => {
|
||||
void new Socket(websocket, request);
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/v5/feature-flags", async (request, reply) => {
|
||||
void reply.send(featureFlags);
|
||||
});
|
||||
|
||||
app.post("/v5/session-keep-alive", sessionKeepAlive);
|
||||
app.get("/v5/presence/:service/:file", presences);
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
export const redis = createRedis();
|
||||
@@ -1,33 +0,0 @@
|
||||
import { type } from "arktype";
|
||||
import { GraphQLError } from "graphql";
|
||||
import { redis } from "../../../../functions/createServer.js";
|
||||
import type { MutationResolvers } from "../../../../generated/graphql-v5.js";
|
||||
|
||||
const addScienceSchema = type({
|
||||
identifier: "string.uuid & string.lower",
|
||||
presences: "string.trim[]",
|
||||
platform: {
|
||||
arch: "string.trim",
|
||||
os: "string.trim",
|
||||
},
|
||||
});
|
||||
|
||||
const mutation: MutationResolvers["addScience"] = async (_parent, input) => {
|
||||
const out = addScienceSchema(input);
|
||||
|
||||
if (out instanceof type.errors)
|
||||
throw new GraphQLError(out.summary);
|
||||
|
||||
await redis.hset(
|
||||
"pmd-api.scienceUpdates",
|
||||
out.identifier,
|
||||
JSON.stringify(out),
|
||||
);
|
||||
|
||||
return {
|
||||
__typename: "AddScienceResult",
|
||||
...out,
|
||||
};
|
||||
};
|
||||
|
||||
export default mutation;
|
||||
@@ -1,57 +0,0 @@
|
||||
import process from "node:process";
|
||||
import { type } from "arktype";
|
||||
import { GraphQLError } from "graphql";
|
||||
import type { MutationResolvers } from "../../../../generated/graphql-v5.js";
|
||||
import { redis } from "../../../../functions/createServer.js";
|
||||
|
||||
const heartbeatSchema = type({
|
||||
"identifier": "string.uuid & string.lower",
|
||||
"presence?": {
|
||||
service: "string.trim",
|
||||
version: "string.semver",
|
||||
language: "string.trim",
|
||||
since: "number.epoch",
|
||||
},
|
||||
"extension": {
|
||||
"version": "string.semver",
|
||||
"language": "string.trim",
|
||||
"connected?": {
|
||||
app: "number.integer",
|
||||
discord: "boolean",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const mutation: MutationResolvers["heartbeat"] = async (_parent, input, context) => {
|
||||
const out = heartbeatSchema(input);
|
||||
|
||||
if (out instanceof type.errors)
|
||||
throw new GraphQLError(out.summary);
|
||||
|
||||
//* Get the user's IP address from Cloudflare headers or fallback to the request IP
|
||||
const userIp = context.request.headers.get("cf-connecting-ip") || context.request.ip;
|
||||
|
||||
// * Use Redis Hash with 'service' in the key to store heartbeat data
|
||||
const redisKey = `pmd-api.heartbeatUpdates.${out.identifier}`;
|
||||
if (process.env.HEARTBEATS !== "false") {
|
||||
await redis.hset(redisKey, {
|
||||
service: out.presence?.service,
|
||||
version: out.presence?.version,
|
||||
language: out.presence?.language,
|
||||
since: out.presence?.since.toString(),
|
||||
extension_version: out.extension.version,
|
||||
extension_language: out.extension.language,
|
||||
extension_connected_app: out.extension.connected?.app?.toString(),
|
||||
extension_connected_discord: out.extension.connected?.discord?.toString(),
|
||||
ip_address: userIp,
|
||||
});
|
||||
await redis.expire(redisKey, 300);
|
||||
}
|
||||
|
||||
return {
|
||||
__typename: "HeartbeatResult",
|
||||
...out,
|
||||
};
|
||||
};
|
||||
|
||||
export default mutation;
|
||||
@@ -1,8 +0,0 @@
|
||||
import type { MutationResolvers } from "../../../../generated/graphql-v5.js";
|
||||
import addScience from "./addScience.js";
|
||||
import heartbeat from "./heartbeat.js";
|
||||
|
||||
export const Mutation: MutationResolvers = {
|
||||
addScience,
|
||||
heartbeat,
|
||||
};
|
||||
@@ -1,6 +0,0 @@
|
||||
import type { QueryResolvers } from "../../../../generated/graphql-v5.js";
|
||||
import presences from "./presences.js";
|
||||
|
||||
export const Query: QueryResolvers = {
|
||||
presences,
|
||||
};
|
||||
@@ -1,58 +0,0 @@
|
||||
import { Presence } from "@premid/db";
|
||||
import { parseResolveInfo } from "graphql-parse-resolve-info";
|
||||
import type { PresenceSchema } from "@premid/db/Presence.js";
|
||||
import type { FilterQuery } from "mongoose";
|
||||
|
||||
import type { QueryResolvers } from "../../../../generated/graphql-v5.js";
|
||||
|
||||
const resolver: QueryResolvers["presences"] = async (
|
||||
_parent,
|
||||
{ author, contributor, limit, query, service, start, tag },
|
||||
_context,
|
||||
info,
|
||||
) => {
|
||||
const authorFilter: FilterQuery<PresenceSchema> = author
|
||||
? { "metadata.author.name": author }
|
||||
: {};
|
||||
const contributorFilter: FilterQuery<PresenceSchema> = contributor
|
||||
? { "metadata.contributors.name": contributor }
|
||||
: {};
|
||||
const serviceFilter: FilterQuery<PresenceSchema> = service
|
||||
? Array.isArray(service)
|
||||
? { "metadata.service": { $in: service } }
|
||||
: { "metadata.service": service }
|
||||
: {};
|
||||
const queryFilter: FilterQuery<PresenceSchema> = query
|
||||
? { "metadata.service": { $options: "i", $regex: query } }
|
||||
: {};
|
||||
const tagFilter: FilterQuery<PresenceSchema> = tag
|
||||
? { "metadata.tags": tag }
|
||||
: {};
|
||||
|
||||
const presences = await Presence.find(
|
||||
{
|
||||
...authorFilter,
|
||||
...contributorFilter,
|
||||
...serviceFilter,
|
||||
...queryFilter,
|
||||
...tagFilter,
|
||||
},
|
||||
Object.assign(
|
||||
{},
|
||||
...Object.keys(parseResolveInfo(info)!.fieldsByTypeName.Presence!).map(
|
||||
fieldName => ({ [fieldName]: true }),
|
||||
),
|
||||
) as Record<string, boolean>,
|
||||
{ ...(limit ? { limit } : {}), ...(start ? { skip: start } : {}) },
|
||||
);
|
||||
|
||||
return presences.map(presence => ({
|
||||
iframeJs: presence.iframeJs,
|
||||
metadata: presence.metadata,
|
||||
presenceJs: presence.presenceJs,
|
||||
url: presence.url,
|
||||
users: 0,
|
||||
}));
|
||||
};
|
||||
|
||||
export default resolver;
|
||||
@@ -1,8 +0,0 @@
|
||||
import type { Resolvers } from "../../../generated/graphql-v5.js";
|
||||
import { Mutation } from "./Mutation/index.js";
|
||||
import { Query } from "./Query/index.js";
|
||||
|
||||
export const resolvers: Resolvers = {
|
||||
Query,
|
||||
Mutation,
|
||||
};
|
||||
@@ -1,19 +0,0 @@
|
||||
type Mutation {
|
||||
addScience(identifier: String!, presences: [String!]!, platform: PlatformInput!): AddScienceResult
|
||||
}
|
||||
|
||||
input PlatformInput {
|
||||
arch: String!
|
||||
os: String!
|
||||
}
|
||||
|
||||
type AddScienceResult {
|
||||
identifier: String!
|
||||
presences: [String!]!
|
||||
platform: Platform!
|
||||
}
|
||||
|
||||
type Platform {
|
||||
arch: String!
|
||||
os: String!
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
type Query {
|
||||
"""
|
||||
Get the available languages
|
||||
"""
|
||||
availableLanguages: [Language!]!
|
||||
}
|
||||
|
||||
type Language {
|
||||
"""
|
||||
Language code
|
||||
"""
|
||||
lang: String!
|
||||
"""
|
||||
Native name of the language, eg. 'English', 'Deutsch', 'Español', etc.
|
||||
"""
|
||||
nativeName: String!
|
||||
"""
|
||||
'ltr' or 'rtl'
|
||||
"""
|
||||
direction: String!
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
type Query {
|
||||
"""
|
||||
Get the available presence languages for a specific presence
|
||||
"""
|
||||
availablePresenceLanguages(
|
||||
"""
|
||||
Presence, e.g. 'Netflix'
|
||||
"""
|
||||
presence: StringOrStringArray
|
||||
): [PresenceLanguage!]!
|
||||
}
|
||||
|
||||
type PresenceLanguage {
|
||||
"""
|
||||
Presence, e.g. 'Netflix'
|
||||
"""
|
||||
presence: String!
|
||||
"""
|
||||
The available languages for the presence
|
||||
"""
|
||||
languages: [Language!]!
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
type Mutation {
|
||||
heartbeat(
|
||||
identifier: String!
|
||||
presence: HeartbeatPresenceInput
|
||||
extension: HeartbeatExtensionInput!
|
||||
): HeartbeatResult!
|
||||
}
|
||||
|
||||
input HeartbeatPresenceInput {
|
||||
service: String!
|
||||
version: String!
|
||||
language: String!
|
||||
since: Float!
|
||||
}
|
||||
|
||||
input HeartbeatExtensionInput {
|
||||
version: String!
|
||||
language: String!
|
||||
connected: HeartbeatConnectedInput
|
||||
}
|
||||
|
||||
input HeartbeatConnectedInput {
|
||||
app: Int!
|
||||
discord: Boolean!
|
||||
}
|
||||
|
||||
type HeartbeatResult {
|
||||
identifier: String!
|
||||
presence: HeartbeatPresence
|
||||
extension: HeartbeatExtension!
|
||||
}
|
||||
|
||||
type HeartbeatPresence {
|
||||
service: String!
|
||||
version: String!
|
||||
language: String!
|
||||
since: Float!
|
||||
}
|
||||
|
||||
type HeartbeatExtension {
|
||||
version: String!
|
||||
language: String!
|
||||
connected: HeartbeatConnected
|
||||
}
|
||||
|
||||
type HeartbeatConnected {
|
||||
app: Int!
|
||||
discord: Boolean!
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
type Query {
|
||||
presences(
|
||||
service: StringOrStringArray
|
||||
author: String
|
||||
contributor: String
|
||||
start: Int
|
||||
limit: Int
|
||||
query: String
|
||||
tag: String
|
||||
): [Presence!]!
|
||||
}
|
||||
|
||||
type Presence {
|
||||
url: String!
|
||||
metadata: PresenceMetadata!
|
||||
presenceJs: String!
|
||||
iframeJs: String
|
||||
users: Int!
|
||||
}
|
||||
|
||||
type PresenceMetadata {
|
||||
apiVersion: Int!
|
||||
author: PresenceMetadataUser!
|
||||
contributors: [PresenceMetadataUser!]
|
||||
altnames: [String!]
|
||||
service: String!
|
||||
description: Scalar! # serialize
|
||||
url: Scalar! # serialize
|
||||
version: String!
|
||||
logo: String!
|
||||
thumbnail: String!
|
||||
color: String!
|
||||
tags: [String!]!
|
||||
category: String!
|
||||
iframe: Boolean
|
||||
regExp: String
|
||||
iFrameRegExp: String
|
||||
readLogs: Boolean
|
||||
button: Boolean
|
||||
warning: Boolean
|
||||
settings: [PresenceMetadataSettings!]
|
||||
}
|
||||
|
||||
type PresenceMetadataUser {
|
||||
id: String!
|
||||
name: String!
|
||||
}
|
||||
|
||||
type PresenceMetadataSettings {
|
||||
id: String!
|
||||
title: String
|
||||
icon: String
|
||||
if: Scalar # serialize
|
||||
placeholder: String
|
||||
value: Scalar # serialize
|
||||
values: Scalar # serialize
|
||||
multiLanguage: Scalar # serialize
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
scalar Scalar
|
||||
@@ -1 +0,0 @@
|
||||
scalar StringOrStringArray
|
||||
@@ -1,27 +0,0 @@
|
||||
/* eslint-disable no-console */
|
||||
import process from "node:process";
|
||||
import * as Sentry from "@sentry/node";
|
||||
import { connect } from "mongoose";
|
||||
import "./tracing.js";
|
||||
import createServer from "./functions/createServer.js";
|
||||
|
||||
// TODO SETUP SENTRY
|
||||
Sentry.init({
|
||||
integrations: [
|
||||
Sentry.graphqlIntegration(),
|
||||
Sentry.mongooseIntegration(),
|
||||
],
|
||||
});
|
||||
|
||||
if (!process.env.DATABASE_URL)
|
||||
throw new Error("DATABASE_URL is not set");
|
||||
|
||||
await connect(process.env.DATABASE_URL, { appName: "PreMiD API", dbName: "PreMiD" });
|
||||
|
||||
const server = await createServer();
|
||||
const url = await server.listen({
|
||||
port: Number.parseInt(process.env.PORT ?? "3001"),
|
||||
host: process.env.HOST ?? "0.0.0.0",
|
||||
});
|
||||
|
||||
console.log(`Server listening at ${url}`);
|
||||
@@ -1,34 +0,0 @@
|
||||
import { Presence } from "@premid/db";
|
||||
import { type } from "arktype";
|
||||
import type { FastifyReply, FastifyRequest } from "fastify";
|
||||
|
||||
const schema = type({
|
||||
service: "string.trim",
|
||||
file: "'metadata.json'|'presence.js'|'iframe.js'",
|
||||
});
|
||||
|
||||
export async function presences(request: FastifyRequest, reply: FastifyReply) {
|
||||
const out = schema(request.params);
|
||||
|
||||
if (out instanceof type.errors)
|
||||
return reply.status(400).send({ code: "INVALID_PARAMS", message: out.message });
|
||||
|
||||
const service = decodeURIComponent(out.service);
|
||||
const { file } = out;
|
||||
|
||||
const presence = await Presence.findOne({ "metadata.service": service });
|
||||
|
||||
if (!presence)
|
||||
return reply.status(404).send({ code: "PRESENCE_NOT_FOUND", message: "The presence was not found" });
|
||||
|
||||
switch (file) {
|
||||
case "metadata.json":
|
||||
return reply.status(200).type("application/json").send(presence.metadata);
|
||||
case "presence.js":
|
||||
return reply.status(200).type("application/javascript").send(presence.presenceJs);
|
||||
case "iframe.js":
|
||||
if (!presence.iframeJs)
|
||||
return reply.status(404).send({ code: "IFRAME_NOT_FOUND", message: "The presence does not have an iframe" });
|
||||
return reply.status(200).type("application/javascript").send(presence.iframeJs);
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
import process from "node:process";
|
||||
import { REST } from "@discordjs/rest";
|
||||
import { type } from "arktype";
|
||||
import { Routes } from "discord-api-types/v10";
|
||||
import type { FastifyReply, FastifyRequest } from "fastify";
|
||||
import { redis } from "../functions/createServer.js";
|
||||
import { featureFlags } from "../constants.js";
|
||||
|
||||
const schema = type({
|
||||
token: "string.trim",
|
||||
session: "string.trim",
|
||||
version: "string.semver & string.trim",
|
||||
scienceId: "string.trim",
|
||||
});
|
||||
|
||||
export async function sessionKeepAlive(request: FastifyRequest, reply: FastifyReply) {
|
||||
if (!featureFlags.SessionKeepAlive)
|
||||
return reply.status(202).send();
|
||||
|
||||
//* Get the headers
|
||||
const out = schema({
|
||||
token: request.headers["x-token"],
|
||||
session: request.headers["x-session"],
|
||||
version: request.headers["x-version"] ?? "2.6.8",
|
||||
scienceId: request.headers["x-science-id"] ?? request.headers["x-token"],
|
||||
});
|
||||
|
||||
if (out instanceof type.errors)
|
||||
return reply.status(400).send({ code: "MISSING_HEADERS", message: out.message });
|
||||
|
||||
if (!await isTokenValid(out.token))
|
||||
return reply.status(400).send({ code: "INVALID_TOKEN", message: "The token is invalid" });
|
||||
|
||||
const redisKey = `pmd-api.sessions.${out.scienceId}`;
|
||||
await redis.hset(redisKey, {
|
||||
session: out.session,
|
||||
token: out.token,
|
||||
lastUpdated: Date.now(),
|
||||
});
|
||||
await redis.expire(redisKey, 300); // 5 minutes
|
||||
|
||||
const interval = Number.parseInt(process.env.SESSION_KEEP_ALIVE_INTERVAL ?? "5000"); // 5 seconds
|
||||
|
||||
return reply.status(200).send({
|
||||
code: "OK",
|
||||
message: "Session updated",
|
||||
nextUpdate: interval,
|
||||
});
|
||||
}
|
||||
|
||||
async function isTokenValid(token: string) {
|
||||
const discord = new REST({ version: "10", authPrefix: "Bearer" });
|
||||
|
||||
discord.setToken(token);
|
||||
try {
|
||||
await discord.get(Routes.user());
|
||||
return true;
|
||||
}
|
||||
catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
import { ValueType } from "@opentelemetry/api";
|
||||
import { PrometheusExporter } from "@opentelemetry/exporter-prometheus";
|
||||
import { MeterProvider } from "@opentelemetry/sdk-metrics";
|
||||
|
||||
const prometheusExporter = new PrometheusExporter();
|
||||
|
||||
const provider = new MeterProvider({
|
||||
readers: [prometheusExporter],
|
||||
});
|
||||
|
||||
const meter = provider.getMeter("nice");
|
||||
|
||||
export const counter = meter.createUpDownCounter("active_activites", {
|
||||
description: "Number of active activities",
|
||||
valueType: ValueType.INT,
|
||||
});
|
||||
|
||||
prometheusExporter.startServer();
|
||||
@@ -1,10 +0,0 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"rootDir": "src",
|
||||
"types": ["@ark/schema"],
|
||||
"outDir": "dist"
|
||||
},
|
||||
"include": ["src/**/*"]
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"extends": "./tsconfig.app.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": ".",
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["environment.d.ts", "src", "codegen.ts"]
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
{
|
||||
"name": "@premid/discord-bot",
|
||||
"type": "module",
|
||||
"version": "1.0.8",
|
||||
"private": true,
|
||||
"description": "PreMiD's discord bot",
|
||||
"license": "MPL-2.0",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"start": "node --enable-source-maps .",
|
||||
"dev": "node --watch --env-file .env --enable-source-maps ."
|
||||
},
|
||||
"dependencies": {
|
||||
"@premid/db": "workspace:*",
|
||||
"@sentry/node": "^8.17.0",
|
||||
"defu": "^6.1.4",
|
||||
"discord.js": "^14.16.2",
|
||||
"glob": "^11.0.0",
|
||||
"mongoose": "^8.2.0",
|
||||
"winston": "^3.14.2"
|
||||
}
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
import type { AutocompleteInteraction, ChatInputCommandInteraction } from "discord.js";
|
||||
import { ActionRowBuilder, ButtonBuilder, ButtonStyle, SlashCommandBuilder } from "discord.js";
|
||||
import { Presence as Activity } from "@premid/db";
|
||||
import { createStandardEmbed } from "../util/createStandardEmbed.js";
|
||||
import type { Command } from "../util/loadCommands.js";
|
||||
import { getActivityList } from "../util/activityList.js";
|
||||
import { client } from "../constants.js";
|
||||
|
||||
export default {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName("activity")
|
||||
.setDescription("Search for an activity")
|
||||
.addStringOption(option =>
|
||||
option
|
||||
.setName("query")
|
||||
.setDescription("The activity to search for")
|
||||
.setAutocomplete(true)
|
||||
.setRequired(true),
|
||||
),
|
||||
autocomplete: async (interaction: AutocompleteInteraction) => {
|
||||
const focusedValue = interaction.options.getFocused();
|
||||
const activityList = getActivityList();
|
||||
const filtered = activityList.filter(({ service }) => service.toLowerCase().includes(focusedValue.toLowerCase()));
|
||||
|
||||
return interaction.respond(filtered.slice(0, 25).map(({ service }) => ({ name: service, value: service })));
|
||||
},
|
||||
execute: async (interaction: ChatInputCommandInteraction) => {
|
||||
const query = interaction.options.getString("query");
|
||||
|
||||
if (!query)
|
||||
return interaction.reply({ content: "Please provide a query to search for", ephemeral: true });
|
||||
|
||||
const activity = await Activity.findOne({ name: query }, {
|
||||
_id: false,
|
||||
metadata: {
|
||||
service: true,
|
||||
author: { id: true },
|
||||
contributors: { id: true },
|
||||
url: true,
|
||||
description: {
|
||||
en: true,
|
||||
},
|
||||
logo: true,
|
||||
color: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!activity)
|
||||
return interaction.reply({ content: "Activity not found", ephemeral: true });
|
||||
|
||||
const embed = createStandardEmbed({
|
||||
title: activity.metadata.service,
|
||||
description: activity.metadata.description.en,
|
||||
color: activity.metadata.color,
|
||||
fields: activity.metadata.contributors?.length
|
||||
? [{
|
||||
name: "Contributors",
|
||||
value: activity.metadata.contributors.map(contributor => `<@${contributor.id}>`).join(", "),
|
||||
}]
|
||||
: undefined,
|
||||
});
|
||||
|
||||
embed.setURL(`https://${Array.isArray(activity.metadata.url) ? activity.metadata.url[0] : activity.metadata.url}`);
|
||||
embed.setThumbnail(activity.metadata.logo);
|
||||
|
||||
const author = await client.users.fetch(activity.metadata.author.id).catch(() => null);
|
||||
if (author) {
|
||||
embed.setAuthor({
|
||||
name: author.username,
|
||||
iconURL: author.displayAvatarURL(),
|
||||
});
|
||||
}
|
||||
|
||||
return interaction.reply({ embeds: [embed], components: [
|
||||
new ActionRowBuilder<ButtonBuilder>()
|
||||
.addComponents(
|
||||
new ButtonBuilder()
|
||||
.setLabel("Open in Store")
|
||||
.setURL(`https://premid.app/store/presences/${encodeURI(activity.metadata.service)}`)
|
||||
.setStyle(ButtonStyle.Link),
|
||||
),
|
||||
] });
|
||||
},
|
||||
help: {
|
||||
name: "activity",
|
||||
value: "activity",
|
||||
command: "/activity <query>",
|
||||
commandDescription: "Search for an activity",
|
||||
embed: createStandardEmbed({
|
||||
title: "Command: /activity",
|
||||
description: "Search for an activity",
|
||||
fields: [
|
||||
{ name: "Usage", value: "`/activity <query>`", inline: true },
|
||||
{ name: "Example", value: "`/activity YouTube`", inline: true },
|
||||
],
|
||||
}),
|
||||
},
|
||||
} satisfies Command;
|
||||
@@ -1,61 +0,0 @@
|
||||
import type { ChatInputCommandInteraction } from "discord.js";
|
||||
import { SlashCommandBuilder } from "discord.js";
|
||||
import { BetaUsers } from "@premid/db";
|
||||
import { createStandardEmbed } from "../util/createStandardEmbed.js";
|
||||
import type { Command } from "../util/loadCommands.js";
|
||||
import { client, processEnv } from "../constants.js";
|
||||
|
||||
export default {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName("beta")
|
||||
.setDescription("Join or leave the beta program")
|
||||
.addSubcommand(subcommand =>
|
||||
subcommand
|
||||
.setName("leave")
|
||||
.setDescription("Leave the beta program"),
|
||||
).addSubcommand(subcommand =>
|
||||
subcommand
|
||||
.setName("join")
|
||||
.setDescription("Join the beta program"),
|
||||
),
|
||||
execute: async (interaction: ChatInputCommandInteraction) => {
|
||||
if (!interaction.inGuild())
|
||||
return;
|
||||
if (interaction.options.getSubcommand() === "leave") {
|
||||
const user = await BetaUsers.findOne({ userId: interaction.user.id });
|
||||
if (!user) {
|
||||
return interaction.reply({ content: "You are not a beta tester", ephemeral: true });
|
||||
}
|
||||
|
||||
await BetaUsers.deleteOne({ userId: interaction.user.id });
|
||||
const member = client.guilds.cache.get(interaction.guildId)?.members.cache.get(interaction.user.id);
|
||||
await member?.roles.remove(processEnv.BETA_ROLE, "Left the beta program");
|
||||
|
||||
return interaction.reply({ content: "You are no longer a beta tester", ephemeral: true });
|
||||
}
|
||||
else if (interaction.options.getSubcommand() === "join") {
|
||||
await BetaUsers.updateOne({ userId: interaction.user.id }, { $set: { userId: interaction.user.id } }, { upsert: true });
|
||||
const member = client.guilds.cache.get(interaction.guildId)?.members.cache.get(interaction.user.id);
|
||||
await member?.roles.add(processEnv.BETA_ROLE, "Joined the beta program");
|
||||
|
||||
return interaction.reply({ content: "You are now a beta tester", ephemeral: true });
|
||||
}
|
||||
else {
|
||||
return interaction.reply({ content: "Invalid subcommand", ephemeral: true });
|
||||
}
|
||||
},
|
||||
help: {
|
||||
name: "beta",
|
||||
value: "beta",
|
||||
command: "/beta <join/leave>",
|
||||
commandDescription: "Join or leave the beta program",
|
||||
embed: createStandardEmbed({
|
||||
title: "Command: /beta <join/leave>",
|
||||
description: "Join or leave the beta program",
|
||||
fields: [
|
||||
{ name: "Usage", value: "`/beta <join/leave>`", inline: true },
|
||||
{ name: "Example", value: "`/beta join`", inline: true },
|
||||
],
|
||||
}),
|
||||
},
|
||||
} satisfies Command;
|
||||
@@ -1,83 +0,0 @@
|
||||
import {
|
||||
ActionRowBuilder,
|
||||
type AutocompleteInteraction,
|
||||
ButtonBuilder,
|
||||
ButtonStyle,
|
||||
type ChatInputCommandInteraction,
|
||||
SlashCommandBuilder,
|
||||
} from "discord.js";
|
||||
import { createStandardEmbed } from "../util/createStandardEmbed.js";
|
||||
import { type Command, commands } from "../util/loadCommands.js";
|
||||
|
||||
export default {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName("help")
|
||||
.setDescription("Shows help and usage information for PreMiD commands")
|
||||
.addStringOption(option =>
|
||||
option
|
||||
.setName("command")
|
||||
.setDescription("The specific command to get help for")
|
||||
.setAutocomplete(true),
|
||||
),
|
||||
autocomplete: async (interaction: AutocompleteInteraction) => {
|
||||
const focusedValue = interaction.options.getFocused();
|
||||
const choices = [...commands.values()]
|
||||
.filter(cmd => cmd.help)
|
||||
.map(cmd => ({ name: cmd.help!.name, value: cmd.help!.value }));
|
||||
|
||||
const filtered = choices.filter(choice => choice.name.toLowerCase().includes(focusedValue.toLowerCase()));
|
||||
return interaction.respond(filtered.slice(0, 25));
|
||||
},
|
||||
execute: async (interaction: ChatInputCommandInteraction) => {
|
||||
const command = interaction.options.getString("command");
|
||||
|
||||
if (command) {
|
||||
const help = [...commands.values()].find(({ help }) => help?.value === command)?.help;
|
||||
if (!help)
|
||||
return interaction.reply({ content: "Command not found", ephemeral: true });
|
||||
|
||||
return interaction.reply({
|
||||
embeds: [help.embed],
|
||||
ephemeral: true,
|
||||
});
|
||||
}
|
||||
|
||||
const generalCommands = [];
|
||||
|
||||
for (const cmd of commands.values()) {
|
||||
if (cmd.help) {
|
||||
if (cmd.help.command)
|
||||
generalCommands.push(`\`${cmd.help.command}\` - ${cmd.help.commandDescription}`);
|
||||
}
|
||||
}
|
||||
|
||||
const embed = createStandardEmbed({
|
||||
title: "🛠️ PreMiD Help",
|
||||
description: "PreMiD is a simple, configurable utility that allows you to show what you're doing on the web in your Discord now playing status.",
|
||||
fields: [
|
||||
{
|
||||
name: "🔧 Commands",
|
||||
value: generalCommands.join("\n") || "No commands available",
|
||||
inline: false,
|
||||
},
|
||||
{
|
||||
name: "📚 Additional Information",
|
||||
value: "Use `/help <command>` for detailed information about a specific command.",
|
||||
inline: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return interaction.reply({
|
||||
embeds: [embed],
|
||||
components: [
|
||||
new ActionRowBuilder<ButtonBuilder>().addComponents(
|
||||
new ButtonBuilder().setLabel("View Website").setURL("https://premid.app/").setStyle(ButtonStyle.Link),
|
||||
new ButtonBuilder().setLabel("View Store").setURL("https://premid.app/store").setStyle(ButtonStyle.Link),
|
||||
new ButtonBuilder().setLabel("Downloads").setURL("https://premid.app/downloads").setStyle(ButtonStyle.Link),
|
||||
),
|
||||
],
|
||||
ephemeral: true,
|
||||
});
|
||||
},
|
||||
} satisfies Command;
|
||||
@@ -1,289 +0,0 @@
|
||||
import type { APIButtonComponent, AutocompleteInteraction, ChatInputCommandInteraction, ColorResolvable } from "discord.js";
|
||||
import { ActionRowBuilder, ButtonBuilder, ButtonStyle, SlashCommandBuilder } from "discord.js";
|
||||
import { createStandardEmbed } from "../util/createStandardEmbed.js";
|
||||
import type { Command } from "../util/loadCommands.js";
|
||||
|
||||
const shortInfos: {
|
||||
[key: string]: {
|
||||
title: string;
|
||||
description: string;
|
||||
emoji?: string;
|
||||
image?: string;
|
||||
color?: ColorResolvable;
|
||||
links?: Partial<APIButtonComponent>[];
|
||||
};
|
||||
} = {
|
||||
troubleshooting: {
|
||||
title: "Troubleshooting",
|
||||
emoji: "❓",
|
||||
description:
|
||||
"If you have problems with PreMiD, you should read our troubleshooting guide and if that doesn't help, create a new post in <#1019726199494279248>.",
|
||||
|
||||
links: [
|
||||
{
|
||||
label: "Troubleshooting Guide",
|
||||
url: "https://docs.premid.app/troubleshooting",
|
||||
},
|
||||
],
|
||||
},
|
||||
modifiedClients: {
|
||||
title: "Modified Clients",
|
||||
color: "#FF5050",
|
||||
description:
|
||||
"Using a modified client is an violation of Discord's ToS and therefore you run the risk of losing your account. If you want to keep using Discord, you have to follow them and make sure you're not breaking any of the rules Discord. Even using modified clients for theming or other customizations are against Discord's ToS. If you don't believe us, read it yourself.",
|
||||
links: [
|
||||
{
|
||||
label: "Discord's ToS",
|
||||
url: "https://discordapp.com/terms",
|
||||
},
|
||||
{
|
||||
label: "Discord's Tweet",
|
||||
url: "https://twitter.com/discordapp/status/908000828690182145",
|
||||
},
|
||||
],
|
||||
},
|
||||
creatingAPresence: {
|
||||
title: "Creating a Presence",
|
||||
emoji: "🏗",
|
||||
description:
|
||||
"If you wish to add support for a service that does not have a Presence yet, you can either open an issue on GitHub to request the presence to be created or you create it yourself. If you wish to create a Presence for PreMiD you need to have basic knowledge of TypeScript. For more information and docs on how to create a Presence follow our documentation.",
|
||||
links: [
|
||||
{
|
||||
label: "Documentation",
|
||||
url: "https://docs.premid.app/dev/presence",
|
||||
},
|
||||
{
|
||||
label: "Service Request",
|
||||
url: "https://github.com/PreMiD/Presences/issues/new?assignees=&labels=Service+Request&template=service_request.yml",
|
||||
},
|
||||
],
|
||||
},
|
||||
docs: {
|
||||
title: "Read the Docs",
|
||||
description:
|
||||
"If you have any questions regarding PreMiD, please read our documentation before creating a ticket. Presence development related queries should be redirected to <#607524579874832446>",
|
||||
links: [
|
||||
{
|
||||
label: "Documentation",
|
||||
url: "https://docs.premid.app",
|
||||
},
|
||||
],
|
||||
},
|
||||
website: {
|
||||
title: "Visit Our Website",
|
||||
emoji: "🌐",
|
||||
description: "Press the button below to visit our website full of greatness.",
|
||||
links: [
|
||||
{
|
||||
label: "Website",
|
||||
url: "https://premid.app",
|
||||
},
|
||||
],
|
||||
},
|
||||
presenceStore: {
|
||||
title: "Presence Store",
|
||||
emoji: "🏪",
|
||||
description: "Press the button below to visit our Presence Store full of the your favourite services!",
|
||||
links: [{ label: "Presence Store", url: "https://premid.app/store" }],
|
||||
},
|
||||
downloadPreMiD: {
|
||||
title: "Download PreMiD",
|
||||
emoji: "📦",
|
||||
description:
|
||||
"You can download PreMiD's extension for your browser via the button below.\n**Note:** You no longer need to download any application!",
|
||||
links: [{ label: "Downloads", url: "https://premid.app/downloads" }],
|
||||
},
|
||||
donate: {
|
||||
title: "Donate",
|
||||
emoji: "💵",
|
||||
description:
|
||||
"Want to support PreMiD's development? Great! You can do so by boosting our Discord server, which you will get a special role, or you can support us on Patreon!",
|
||||
links: [
|
||||
{ label: "Patreon", url: "https://patreon.com/Timeraa" },
|
||||
{ label: "GitHub Sponsors", url: "https://github.com/sponsors/Timeraa" },
|
||||
],
|
||||
},
|
||||
creatingATicket: {
|
||||
title: "Creating a Support Ticket",
|
||||
emoji: "🙋",
|
||||
description:
|
||||
"Recently, we have migrated to use Discord's new forum channels for our support system. You can now create a ticket by creating a new post in <#1019726199494279248>",
|
||||
},
|
||||
suggestingAPresence: {
|
||||
title: "Suggesting a Presence",
|
||||
emoji: "🗳",
|
||||
description:
|
||||
"If you'd like to suggest a presence, you can do this on our GitHub repository by creating a new issue with the Service Request template! If want to create a Presence yourself, you can find more information on our documentation",
|
||||
links: [
|
||||
{
|
||||
label: "PreMiD Documentation",
|
||||
url: "https://docs.premid.app/dev/presence",
|
||||
},
|
||||
{
|
||||
label: "GitHub Repository",
|
||||
url: "https://github.com/PreMiD/Presences",
|
||||
},
|
||||
{
|
||||
label: "Service Request",
|
||||
url: "https://github.com/PreMiD/Presences/issues/new?assignees=&labels=Service+Request&template=service_request.yml",
|
||||
},
|
||||
],
|
||||
},
|
||||
tos: {
|
||||
title: "PreMiD and Discord",
|
||||
emoji: "🧬",
|
||||
description: "PreMiD is compliant to Discord's ToS and therefore you can use it without any risk of losing your Discord account.",
|
||||
links: [
|
||||
{
|
||||
label: "Proof",
|
||||
url: "https://twitter.com/discord/status/1233704070390669312",
|
||||
},
|
||||
],
|
||||
},
|
||||
unidentifiedDeveloper: {
|
||||
title: "Allow apps from unidentified developers (macOS)",
|
||||
description:
|
||||
"Steps for **macOS Big Sur (11.0+)**:\n1. Right click on our installer.\n2. Click `Open` in the dropdown menu.\n3. Click `Open` in popup.\n\nSteps for **older macOS versions**:\n1. Open System Preferences.\n2. Go to the Security & Privacy tab.\n3. Click on the lock and enter your password or scan your fingerprint so you can make changes.\n4. Change the setting for 'Allow apps downloaded from' to 'App Store and identified developers' from just 'App Store'.",
|
||||
},
|
||||
reportingaPresenceBug: {
|
||||
title: "Reporting a Presence bug",
|
||||
emoji: "🐛",
|
||||
description:
|
||||
"If you've found an issue with a presence, it is important that you report your issue on the Presence repository so the bug is resolved within a timely fashion. You can report the bug using the Bug Report template, **ensuring you fill in the template properly**.",
|
||||
links: [
|
||||
{
|
||||
label: "Presence Repository",
|
||||
url: "https://github.com/PreMiD/Presences",
|
||||
},
|
||||
{
|
||||
label: "Bug Report",
|
||||
url: "https://github.com/PreMiD/Presences/issues/new?assignees=&labels=%F0%9F%90%9B+Bug&template=bug_report.yml&title=Service+Name+%7C+Service+URL",
|
||||
},
|
||||
],
|
||||
},
|
||||
adblockDetection: {
|
||||
title: "Adblock Detection",
|
||||
emoji: "🚫",
|
||||
description:
|
||||
"If our website has falsely detected the presence of an ad-blocker, you can simply press \"I don't want to support\" six times and you will be redirected to the download. Alternatively, you can find direct download links below.",
|
||||
links: [
|
||||
{
|
||||
label: "Download Links",
|
||||
url: "https://discord.com/channels/493130730549805057/527675240231206934/715852870062309386",
|
||||
},
|
||||
],
|
||||
},
|
||||
requestANewFeature: {
|
||||
title: "Requesting a Presence feature",
|
||||
emoji: "🗳",
|
||||
description:
|
||||
"Does a presence you use not support a crucial page or not support all the possible domains for the website? If you believe a presence should include more features, you should open an issue on the Presence Repository using the Feature Request template.",
|
||||
links: [
|
||||
{
|
||||
label: "Template",
|
||||
url: "https://github.com/PreMiD/Presences/issues/new?assignees=&labels=Feature+Request&template=feature_request.yml",
|
||||
},
|
||||
],
|
||||
},
|
||||
beta: {
|
||||
title: "PreMiD Beta",
|
||||
emoji: "✨",
|
||||
description:
|
||||
"Do you want cool new features? Want to use PreMiD with the browser version of Discord? Download the beta!",
|
||||
links: [
|
||||
{
|
||||
label: "Beta Release Page",
|
||||
url: "https://premid.app/beta",
|
||||
},
|
||||
],
|
||||
},
|
||||
frequentFixes: {
|
||||
title: "Frequent fixes for Presence bugs",
|
||||
emoji: "🗳",
|
||||
description:
|
||||
"There are some frequent fixes for presences, use the buttons to navigate to these.\n If this doesn't work, please submit your issue to <#1019726199494279248>",
|
||||
links: [
|
||||
{
|
||||
label: "YouTube/Netflix",
|
||||
url: "https://discord.com/channels/493130730549805057/527675240231206934/831995042469642251",
|
||||
},
|
||||
{
|
||||
label: "YouTube",
|
||||
url: "https://discord.com/channels/493130730549805057/527675240231206934/827037909504753704",
|
||||
},
|
||||
{
|
||||
label: "General fix",
|
||||
url: "https://discord.com/channels/493130730549805057/527675240231206934/723231955893747763",
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
export default {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName("info")
|
||||
.setDescription("Posts an information message")
|
||||
.addStringOption(option =>
|
||||
option
|
||||
.setName("query")
|
||||
.setDescription("The infomation message to search for")
|
||||
.setAutocomplete(true),
|
||||
)
|
||||
.addUserOption(option =>
|
||||
option
|
||||
.setName("user")
|
||||
.setDescription("User to mention")
|
||||
.setRequired(false),
|
||||
),
|
||||
autocomplete: async (interaction: AutocompleteInteraction) => {
|
||||
const focusedValue = interaction.options.getFocused();
|
||||
const choices = Object.entries(shortInfos).map(([key, data]) => ({ name: data.title, value: key }));
|
||||
|
||||
const filtered = choices.filter(choice => choice.name.toLowerCase().includes(focusedValue.toLowerCase()));
|
||||
return interaction.respond(filtered.slice(0, 25));
|
||||
},
|
||||
execute: async (interaction: ChatInputCommandInteraction) => {
|
||||
const query = interaction.options.getString("query");
|
||||
const user = interaction.options.getUser("user");
|
||||
|
||||
if (!query)
|
||||
return interaction.reply({ content: "Please provide a query to search for", ephemeral: true });
|
||||
|
||||
const info = shortInfos[query];
|
||||
if (!info)
|
||||
return interaction.reply({ content: "No information found for that query", ephemeral: true });
|
||||
|
||||
const embed = createStandardEmbed({
|
||||
title: `${info.emoji || "🔖"} ${info.title}`,
|
||||
description: info.description,
|
||||
});
|
||||
|
||||
let actionRow: ActionRowBuilder<ButtonBuilder> | undefined;
|
||||
if (info.links) {
|
||||
actionRow = new ActionRowBuilder<ButtonBuilder>();
|
||||
|
||||
for (const link of info.links) {
|
||||
actionRow.addComponents(new ButtonBuilder({
|
||||
style: ButtonStyle.Link,
|
||||
...link,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
return interaction.reply({ embeds: [embed], content: user ? user.toString() : undefined, components: actionRow ? [actionRow] : undefined });
|
||||
},
|
||||
help: {
|
||||
name: "info",
|
||||
value: "info",
|
||||
command: "/info <query> [user]",
|
||||
commandDescription: "Posts an information message",
|
||||
embed: createStandardEmbed({
|
||||
title: "Command: /info",
|
||||
description: "Posts an information message",
|
||||
fields: [
|
||||
{ name: "Usage", value: "`/info <query> [user]`", inline: true },
|
||||
{ name: "Example", value: "`/info troubleshooting`\n`/info beta @User`", inline: true },
|
||||
],
|
||||
}),
|
||||
},
|
||||
} satisfies Command;
|
||||
@@ -1,71 +0,0 @@
|
||||
import process from "node:process";
|
||||
import { defu } from "defu";
|
||||
import { Client, GatewayIntentBits, REST } from "discord.js";
|
||||
|
||||
export const processEnv = defu({
|
||||
TOKEN: process.env.TOKEN,
|
||||
DATABASE_URL: process.env.DATABASE_URL,
|
||||
SENTRY_DSN: process.env.SENTRY_DSN,
|
||||
}, {
|
||||
TOKEN: "",
|
||||
DATABASE_URL: "mongodb://localhost:27017/premid",
|
||||
SENTRY_DSN: "",
|
||||
GUILD_ID: "493130730549805057",
|
||||
BETA_ROLE: "591284574823120909",
|
||||
ALPHA_ROLE: "694481247564595211",
|
||||
});
|
||||
|
||||
export const client = new Client({
|
||||
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildPresences],
|
||||
presence: {
|
||||
status: "online",
|
||||
},
|
||||
});
|
||||
|
||||
export const rest = new REST().setToken(processEnv.TOKEN);
|
||||
|
||||
export const roles = {
|
||||
PROJECT_LEADER: "493135149274365975",
|
||||
STAFF_COORDINATOR: "691382096878370837",
|
||||
ADMINISTRATOR: "685969048399249459",
|
||||
PROJECT_MANAGEMENT: "673682085608816652",
|
||||
REVIEWER: "630445337143935009",
|
||||
DEVELOPER: "1027665813525778436",
|
||||
DESIGNER: "691386502566903850",
|
||||
MODERATOR: "514546359865442304",
|
||||
SUPPORT_AGENT: "566417964820070421",
|
||||
MARKETING_DIRECTOR: "673681900476432387",
|
||||
LOCALIZATION_MANAGER: "811262682408943616",
|
||||
SOCIALS_MANAGER: "1027665964684300358",
|
||||
REPRESENTATIVE: "691384256672563332",
|
||||
CONTRIBUTOR: "1032759805732978708",
|
||||
PATRON: "515874214750715904",
|
||||
DONATOR: "502165799172309013",
|
||||
BOOSTER: "585532751663333383",
|
||||
PROOFREADER: "522755339448483840",
|
||||
TRANSLATOR: "502148045991968788",
|
||||
PRESENCE_DEV: "606222296016879722",
|
||||
} as const;
|
||||
|
||||
export const roleColors = {
|
||||
PROJECT_LEADER: "#E43725",
|
||||
STAFF_COORDINATOR: "#E43725",
|
||||
ADMINISTRATOR: "#E43725",
|
||||
PROJECT_MANAGEMENT: "#E43725",
|
||||
REVIEWER: "#3BA576",
|
||||
DEVELOPER: "#3BA576",
|
||||
DESIGNER: "#3BA576",
|
||||
MODERATOR: "#D67118",
|
||||
SUPPORT_AGENT: "#D67118",
|
||||
MARKETING_DIRECTOR: "#3BA576",
|
||||
LOCALIZATION_MANAGER: "#3BA576",
|
||||
SOCIALS_MANAGER: "#1abc9c",
|
||||
REPRESENTATIVE: "#3BA576",
|
||||
CONTRIBUTOR: "#EB459E",
|
||||
PATRON: "#E5472F",
|
||||
DONATOR: "#FFAA33",
|
||||
BOOSTER: "#F265FF",
|
||||
PROOFREADER: "#00B0E6",
|
||||
TRANSLATOR: "#2286D0",
|
||||
PRESENCE_DEV: "#96A5E9",
|
||||
} as const;
|
||||
@@ -1,31 +0,0 @@
|
||||
import { Events } from "discord.js";
|
||||
import { DiscordUsers, Presence } from "@premid/db";
|
||||
import { client, roles as rolesEnv } from "../constants.js";
|
||||
|
||||
client.on(Events.GuildMemberAdd, async (member) => {
|
||||
const [presence] = await Promise.all([
|
||||
Presence.findOne({
|
||||
$or: [{ "metadata.author.id": member.id }, { "metadata.contributors.id": member.id }],
|
||||
}, { name: true }),
|
||||
DiscordUsers.updateOne(
|
||||
{ userId: member.id },
|
||||
{
|
||||
$set: {
|
||||
avatar: member.user.avatar,
|
||||
created: member.user.createdTimestamp,
|
||||
discriminator: member.user.discriminator,
|
||||
userId: member.id,
|
||||
username: member.user.displayName ?? member.user.username,
|
||||
},
|
||||
},
|
||||
{ upsert: true },
|
||||
),
|
||||
]);
|
||||
|
||||
//* User should have Presence Developer Role
|
||||
if (presence) {
|
||||
if (!member.roles.cache.has(rolesEnv.PRESENCE_DEV)) {
|
||||
await member.roles.add(rolesEnv.PRESENCE_DEV, "User should have Presence Developer Role");
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1,12 +0,0 @@
|
||||
import { Events } from "discord.js";
|
||||
import { AlphaUsers, BetaUsers, Credits, DiscordUsers } from "@premid/db";
|
||||
import { client } from "../constants.js";
|
||||
|
||||
client.on(Events.GuildMemberRemove, async (member) => {
|
||||
await Promise.all([
|
||||
BetaUsers.deleteOne({ userId: member.id }),
|
||||
AlphaUsers.deleteOne({ userId: member.id }),
|
||||
DiscordUsers.deleteOne({ userId: member.id }),
|
||||
Credits.deleteOne({ userId: member.id }),
|
||||
]);
|
||||
});
|
||||
@@ -1,86 +0,0 @@
|
||||
import { Events } from "discord.js";
|
||||
import { AlphaUsers, BetaUsers, Credits, DiscordUsers } from "@premid/db";
|
||||
import { client, processEnv, roleColors, roles as rolesEnv } from "../constants.js";
|
||||
|
||||
client.on(Events.GuildMemberUpdate, async (oldMember, newMember) => {
|
||||
const highestRole = newMember.roles.cache
|
||||
.filter(role => (Object.values(rolesEnv) as string[]).includes(role.id))
|
||||
.sort((a, b) => b.position - a.position)
|
||||
.at(0);
|
||||
|
||||
await Promise.all([
|
||||
DiscordUsers.updateOne(
|
||||
{ userId: newMember.id },
|
||||
{
|
||||
$set: {
|
||||
avatar: newMember.user.avatar,
|
||||
created: newMember.user.createdTimestamp,
|
||||
discriminator: newMember.user.discriminator,
|
||||
userId: newMember.id,
|
||||
username: newMember.user.displayName ?? newMember.user.username,
|
||||
},
|
||||
},
|
||||
{ upsert: true },
|
||||
),
|
||||
highestRole
|
||||
? Credits.updateOne(
|
||||
{ userId: newMember.id },
|
||||
{
|
||||
$set: {
|
||||
userId: newMember.id,
|
||||
name: newMember.user.displayName ?? newMember.user.username,
|
||||
tag: newMember.user.discriminator,
|
||||
avatar: newMember.user.displayAvatarURL({
|
||||
extension: "png",
|
||||
forceStatic: false,
|
||||
}),
|
||||
premium_since: newMember.premiumSince !== null ? newMember.premiumSinceTimestamp! : undefined,
|
||||
role: highestRole.name,
|
||||
roleId: highestRole.id,
|
||||
roles: newMember.roles.cache.filter(r => r.name !== "@everyone").map(r => r.name),
|
||||
roleIds: newMember.roles.cache.filter(r => r.name !== "@everyone").map(r => r.id),
|
||||
roleColor: roleColors[
|
||||
Object.entries(rolesEnv).find(([, id]) => id === highestRole.id)![0] as keyof typeof roleColors
|
||||
],
|
||||
rolePosition: highestRole.position,
|
||||
status: newMember.presence?.status ?? "offline",
|
||||
flags: newMember.user.flags?.toArray() ?? [],
|
||||
},
|
||||
},
|
||||
{ upsert: true },
|
||||
)
|
||||
: Promise.resolve(),
|
||||
]);
|
||||
|
||||
const roles = newMember.roles.cache.map(role => role.id);
|
||||
|
||||
//* User should have Alpha Role
|
||||
if (roles.includes(rolesEnv.BOOSTER) || roles.includes(rolesEnv.PATRON) || newMember.roles.cache.has(processEnv.ALPHA_ROLE)) {
|
||||
if (!newMember.roles.cache.has(processEnv.ALPHA_ROLE)) {
|
||||
await newMember.roles.add(processEnv.ALPHA_ROLE, "User should have Alpha Role");
|
||||
}
|
||||
if (newMember.roles.cache.has(processEnv.BETA_ROLE)) {
|
||||
await newMember.roles.remove(processEnv.BETA_ROLE, "User should have Alpha Role");
|
||||
}
|
||||
await Promise.all([
|
||||
AlphaUsers.updateOne({ userId: newMember.id }, { $set: { userId: newMember.id } }, { upsert: true }),
|
||||
BetaUsers.deleteOne({ userId: newMember.id }),
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
//* User should have Beta Role
|
||||
const betaUser = await BetaUsers.findOne({ userId: newMember.id });
|
||||
if (roles.includes(rolesEnv.DONATOR) || betaUser || newMember.roles.cache.has(processEnv.BETA_ROLE) || oldMember.roles.cache.has(processEnv.ALPHA_ROLE)) {
|
||||
if (newMember.roles.cache.has(processEnv.ALPHA_ROLE)) {
|
||||
await newMember.roles.remove(processEnv.ALPHA_ROLE, "User should have Beta Role");
|
||||
}
|
||||
if (!newMember.roles.cache.has(processEnv.BETA_ROLE)) {
|
||||
await newMember.roles.add(processEnv.BETA_ROLE, "User should have Beta Role");
|
||||
}
|
||||
await Promise.all([
|
||||
BetaUsers.updateOne({ userId: newMember.id }, { $set: { userId: newMember.id } }, { upsert: true }),
|
||||
AlphaUsers.deleteOne({ userId: newMember.id }),
|
||||
]);
|
||||
}
|
||||
});
|
||||
@@ -1,42 +0,0 @@
|
||||
import { Events, InteractionType } from "discord.js";
|
||||
import { client } from "../constants.js";
|
||||
import { commands } from "../util/loadCommands.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
client.on(Events.InteractionCreate, async (interaction) => {
|
||||
if (!interaction.inGuild()) {
|
||||
logger.debug("Interaction received outside of a guild, ignoring.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (interaction.type === InteractionType.ApplicationCommand || interaction.type === InteractionType.ApplicationCommandAutocomplete) {
|
||||
const { commandName } = interaction;
|
||||
logger.info(`Command "${commandName}" ${interaction.type === InteractionType.ApplicationCommandAutocomplete ? "autocomplete" : "executed"} in guild ${interaction.guildId} by user ${interaction.user.id}`);
|
||||
|
||||
if (!commands.has(commandName.toLowerCase()))
|
||||
return;
|
||||
|
||||
const command = commands.get(commandName.toLowerCase())!;
|
||||
|
||||
if (interaction.type === InteractionType.ApplicationCommandAutocomplete) {
|
||||
if (command.autocomplete) {
|
||||
try {
|
||||
await command.autocomplete(interaction);
|
||||
logger.debug(`Autocomplete for command "${commandName}" handled successfully`);
|
||||
}
|
||||
catch (error) {
|
||||
logger.error(`Error handling autocomplete for command "${commandName}":`, error);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await command.execute(interaction);
|
||||
logger.debug(`Command "${commandName}" executed successfully`);
|
||||
}
|
||||
catch (error) {
|
||||
logger.error(`Error executing command "${commandName}":`, error);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1,180 +0,0 @@
|
||||
import type { GuildMember } from "discord.js";
|
||||
import { Events } from "discord.js";
|
||||
import { AlphaUsers, BetaUsers, Credits, Presence } from "@premid/db";
|
||||
import { client, processEnv, roleColors, roles as rolesEnv } from "../constants.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
client.once(Events.ClientReady, async () => {
|
||||
logger.debug("Giving roles to members");
|
||||
const guild = await client.guilds.fetch(processEnv.GUILD_ID);
|
||||
const members = await guild.members.fetch();
|
||||
|
||||
let count = 0;
|
||||
for (const [, member] of members) {
|
||||
count++;
|
||||
const roles = member.roles.cache.map(role => role.id);
|
||||
|
||||
//* User should have Alpha Role
|
||||
if (roles.includes(rolesEnv.BOOSTER) || roles.includes(rolesEnv.PATRON) || member.roles.cache.has(processEnv.ALPHA_ROLE)) {
|
||||
if (!member.roles.cache.has(processEnv.ALPHA_ROLE)) {
|
||||
await member.roles.add(processEnv.ALPHA_ROLE, "User should have Alpha Role");
|
||||
}
|
||||
if (member.roles.cache.has(processEnv.BETA_ROLE)) {
|
||||
await member.roles.remove(processEnv.BETA_ROLE, "User should have Alpha Role");
|
||||
}
|
||||
await Promise.all([
|
||||
AlphaUsers.updateOne({ userId: member.id }, { $set: { userId: member.id } }, { upsert: true }),
|
||||
BetaUsers.deleteOne({ userId: member.id }),
|
||||
]);
|
||||
}
|
||||
else {
|
||||
const betaUser = await BetaUsers.findOne({ userId: member.id });
|
||||
//* User should have Beta Role
|
||||
if (roles.includes(rolesEnv.DONATOR) || betaUser || member.roles.cache.has(processEnv.BETA_ROLE)) {
|
||||
if (member.roles.cache.has(processEnv.ALPHA_ROLE)) {
|
||||
await member.roles.remove(processEnv.ALPHA_ROLE, "User should have Beta Role");
|
||||
}
|
||||
if (!member.roles.cache.has(processEnv.BETA_ROLE)) {
|
||||
await member.roles.add(processEnv.BETA_ROLE, "User should have Beta Role");
|
||||
}
|
||||
await Promise.all([
|
||||
BetaUsers.updateOne({ userId: member.id }, { $set: { userId: member.id } }, { upsert: true }),
|
||||
AlphaUsers.deleteOne({ userId: member.id }),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
if (count % 1000 === 0) {
|
||||
logger.debug(`Processed ${count}/${members.size} members`);
|
||||
}
|
||||
}
|
||||
logger.debug(`Gave roles to ${count}/${members.size} members`);
|
||||
|
||||
//* Presence Developers
|
||||
logger.debug("Checking for presence developers");
|
||||
const presenceDevelopers = await Presence.find({}, {
|
||||
"metadata.author.id": true,
|
||||
"metadata.contributors.id": true,
|
||||
"_id": false,
|
||||
});
|
||||
|
||||
for (const presenceDeveloper of [
|
||||
...new Set(
|
||||
presenceDevelopers
|
||||
.map(presence => [presence.metadata.author.id, ...(presence.metadata.contributors?.map(c => c.id) || [])])
|
||||
.flat(),
|
||||
),
|
||||
]) {
|
||||
const member = guild.members.cache.get(presenceDeveloper);
|
||||
|
||||
if (!member)
|
||||
continue;
|
||||
|
||||
if (!member.roles.cache.has(rolesEnv.PRESENCE_DEV)) {
|
||||
await member.roles.add(rolesEnv.PRESENCE_DEV, "User should have Presence Developer Role");
|
||||
}
|
||||
}
|
||||
logger.debug("Checked for presence developers");
|
||||
|
||||
//* Update Credits
|
||||
const usersToCredit = new Set<GuildMember>();
|
||||
|
||||
for (const roleId of Object.values(rolesEnv)) {
|
||||
const role = await guild.roles.fetch(roleId);
|
||||
if (!role)
|
||||
continue;
|
||||
|
||||
for (const member of role.members.values()) {
|
||||
usersToCredit.add(member);
|
||||
}
|
||||
}
|
||||
|
||||
const usersToRemove = await Credits.find({ userId: { $nin: [...usersToCredit].map(member => member.user.id) } });
|
||||
|
||||
await Credits.bulkWrite([
|
||||
...usersToRemove.map(user => ({ deleteOne: { filter: { userId: user.userId } } })),
|
||||
...[...usersToCredit].map((member) => {
|
||||
const highestRole = member.roles.cache
|
||||
.filter(role => (Object.values(rolesEnv) as string[]).includes(role.id))
|
||||
.sort((a, b) => b.position - a.position)
|
||||
.at(0)!;
|
||||
|
||||
const color = roleColors[
|
||||
Object.entries(rolesEnv).find(([, id]) => id === highestRole.id)![0] as keyof typeof roleColors
|
||||
];
|
||||
return {
|
||||
updateOne: {
|
||||
filter: { userId: member.id },
|
||||
update: {
|
||||
$set: {
|
||||
userId: member.id,
|
||||
name: member.user.displayName ?? member.user.username,
|
||||
tag: member.user.discriminator,
|
||||
avatar: member.user.displayAvatarURL({
|
||||
extension: "png",
|
||||
forceStatic: false,
|
||||
}),
|
||||
premium_since: member.premiumSince !== null ? member.premiumSinceTimestamp! : undefined,
|
||||
role: highestRole.name,
|
||||
roleId: highestRole.id,
|
||||
roles: member.roles.cache.filter(r => r.name !== "@everyone").map(r => r.name),
|
||||
roleIds: member.roles.cache.filter(r => r.name !== "@everyone").map(r => r.id),
|
||||
roleColor: color,
|
||||
rolePosition: highestRole.position,
|
||||
status: member.presence?.status ?? "offline",
|
||||
flags: member.user.flags?.toArray() ?? [],
|
||||
},
|
||||
},
|
||||
upsert: true,
|
||||
},
|
||||
};
|
||||
}),
|
||||
]);
|
||||
logger.debug("Updated Credits");
|
||||
|
||||
//* Beta can be requested from the website so we need to periodically check for that, presence developers are external too so we need to periodically check for that
|
||||
setInterval(async () => {
|
||||
//* Beta Users
|
||||
logger.debug("Checking for beta users");
|
||||
const betaUsers = await BetaUsers.find({});
|
||||
const guild = await client.guilds.fetch(processEnv.GUILD_ID);
|
||||
|
||||
for (const betaUser of betaUsers) {
|
||||
const member = guild.members.cache.get(betaUser.userId);
|
||||
|
||||
if (!member)
|
||||
continue;
|
||||
|
||||
if (!member.roles.cache.has(processEnv.BETA_ROLE)) {
|
||||
await member.roles.add(processEnv.BETA_ROLE, "User should have Beta Role");
|
||||
}
|
||||
}
|
||||
logger.debug("Checked for beta users");
|
||||
|
||||
//* Presence Developers
|
||||
logger.debug("Checking for presence developers");
|
||||
const presenceDevelopers = await Presence.find({}, {
|
||||
"metadata.author.id": true,
|
||||
"metadata.contributors.id": true,
|
||||
"_id": false,
|
||||
});
|
||||
|
||||
for (const presenceDeveloper of [
|
||||
...new Set(
|
||||
presenceDevelopers
|
||||
.map(presence => [presence.metadata.author.id, ...(presence.metadata.contributors?.map(c => c.id) || [])])
|
||||
.flat(),
|
||||
),
|
||||
]) {
|
||||
const member = guild.members.cache.get(presenceDeveloper);
|
||||
|
||||
if (!member)
|
||||
continue;
|
||||
|
||||
if (!member.roles.cache.has(rolesEnv.PRESENCE_DEV)) {
|
||||
await member.roles.add(rolesEnv.PRESENCE_DEV, "User should have Presence Developer Role");
|
||||
}
|
||||
}
|
||||
logger.debug("Checked for presence developers");
|
||||
}, 1000 * 60 * 5);
|
||||
});
|
||||
@@ -1,89 +0,0 @@
|
||||
import process from "node:process";
|
||||
import { connect } from "mongoose";
|
||||
import { Routes } from "discord.js";
|
||||
import * as Sentry from "@sentry/node";
|
||||
import { client, processEnv, rest } from "./constants.js";
|
||||
import { getActivity } from "./util/getActivity.js";
|
||||
import loadCommands, { commands } from "./util/loadCommands.js";
|
||||
import loadEvents from "./util/loadEvents.js";
|
||||
import { logger } from "./util/logger.js";
|
||||
import { updateActivityList } from "./util/activityList.js";
|
||||
|
||||
Sentry.init({
|
||||
integrations: [
|
||||
Sentry.mongooseIntegration(),
|
||||
],
|
||||
dsn: processEnv.SENTRY_DSN,
|
||||
});
|
||||
|
||||
logger.info("Starting bot initialization...");
|
||||
|
||||
try {
|
||||
await loadCommands();
|
||||
logger.info("Commands loaded successfully");
|
||||
}
|
||||
catch (error) {
|
||||
logger.error("Error loading commands:", error);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
try {
|
||||
await loadEvents();
|
||||
logger.info("Events loaded successfully");
|
||||
}
|
||||
catch (error) {
|
||||
logger.error("Error loading events:", error);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
try {
|
||||
await connect(processEnv.DATABASE_URL, { appName: "PreMiD Discord Bot" });
|
||||
logger.info("Successfully connected to database");
|
||||
await updateActivityList();
|
||||
logger.info("Successfully updated presence list");
|
||||
}
|
||||
catch (error) {
|
||||
logger.error("Error connecting to database:", error);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
try {
|
||||
await client.login(processEnv.TOKEN);
|
||||
logger.info("Bot logged in successfully");
|
||||
client.user?.setActivity(getActivity({}));
|
||||
}
|
||||
catch (error) {
|
||||
logger.error("Failed to log in:", error);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
client.once("ready", async (client) => {
|
||||
logger.info(`Bot is ready! Logged in as ${client.user?.tag}`);
|
||||
|
||||
try {
|
||||
//* Register guild-specific commands
|
||||
await rest.put(Routes.applicationGuildCommands(client.application.id, processEnv.GUILD_ID), {
|
||||
body: Array.from(commands.values()).map(({ data }) => data),
|
||||
});
|
||||
|
||||
//* Clear global commands
|
||||
await rest.put(Routes.applicationCommands(client.application.id), { body: [] });
|
||||
logger.info("Successfully registered commands");
|
||||
}
|
||||
catch (error) {
|
||||
logger.error("Failed to register commands:", error);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
setInterval(async () => {
|
||||
const newActivity = getActivity({
|
||||
previous: client.user?.presence.activities[0]?.name,
|
||||
});
|
||||
client.user?.setActivity(newActivity);
|
||||
logger.debug(`Updated bot activity to: ${newActivity.name}`);
|
||||
}, 60000);
|
||||
|
||||
setInterval(() => {
|
||||
updateActivityList();
|
||||
}, 1000 * 60 * 5);
|
||||
@@ -1,17 +0,0 @@
|
||||
import { Presence } from "@premid/db";
|
||||
import type { PresenceMetadataCategory } from "@premid/db/Presence.js";
|
||||
import { logger } from "./logger.js";
|
||||
|
||||
let presenceList: { service: string; category: PresenceMetadataCategory }[] = [];
|
||||
|
||||
export async function updateActivityList() {
|
||||
presenceList = (await Presence.find({}, { metadata: { category: true, service: true } })).map(presence => ({
|
||||
service: presence.metadata.service,
|
||||
category: presence.metadata.category,
|
||||
}));
|
||||
logger.debug(`Updated presence list with ${presenceList.length} presences`);
|
||||
}
|
||||
|
||||
export function getActivityList() {
|
||||
return presenceList;
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
import { type APIEmbedField, type ColorResolvable, EmbedBuilder } from "discord.js";
|
||||
|
||||
interface StandardEmbedOptions {
|
||||
title: string;
|
||||
description: string;
|
||||
fields?: APIEmbedField[];
|
||||
footer?: string;
|
||||
color?: number | string;
|
||||
}
|
||||
|
||||
export function createStandardEmbed({
|
||||
title,
|
||||
description,
|
||||
fields = [],
|
||||
footer = "PreMiD",
|
||||
color = "Blurple",
|
||||
}: StandardEmbedOptions): EmbedBuilder {
|
||||
return new EmbedBuilder()
|
||||
.setColor(color as ColorResolvable)
|
||||
.setTitle(title)
|
||||
.setDescription(description)
|
||||
.addFields(fields)
|
||||
.setFooter({ text: footer })
|
||||
.setTimestamp();
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
import type { ActivitiesOptions } from "discord.js";
|
||||
import { ActivityType } from "discord.js";
|
||||
import { getActivityList } from "./activityList.js";
|
||||
|
||||
export function getActivity({ previous }: {
|
||||
previous?: string;
|
||||
}): ActivitiesOptions {
|
||||
const activityList = getActivityList();
|
||||
const statuses = activityList.filter(status => status.service !== previous);
|
||||
const selectedStatus = statuses[Math.floor(Math.random() * statuses.length)]!;
|
||||
|
||||
return {
|
||||
type: selectedStatus.category === "music"
|
||||
? ActivityType.Listening
|
||||
: selectedStatus.category === "anime"
|
||||
? ActivityType.Watching
|
||||
: selectedStatus.category === "videos"
|
||||
? ActivityType.Watching
|
||||
: ActivityType.Playing,
|
||||
name: selectedStatus.service,
|
||||
};
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
import { resolve } from "node:path";
|
||||
import type { APIApplicationCommandOptionChoice, EmbedBuilder, SharedSlashCommandOptions, SlashCommandSubcommandsOnlyBuilder } from "discord.js";
|
||||
import { glob } from "glob";
|
||||
|
||||
export interface CommandHelp extends APIApplicationCommandOptionChoice<string> {
|
||||
embed: EmbedBuilder;
|
||||
command?: string;
|
||||
commandDescription?: string;
|
||||
}
|
||||
|
||||
export interface Command {
|
||||
data: SharedSlashCommandOptions<any> | SlashCommandSubcommandsOnlyBuilder;
|
||||
execute: (interaction: any) => Promise<any>;
|
||||
autocomplete?: (interaction: any) => Promise<any>;
|
||||
help?: CommandHelp;
|
||||
}
|
||||
|
||||
export const commands = new Map<string, Command>();
|
||||
|
||||
export default async function loadCommands() {
|
||||
for (const file of await glob("*.js", { cwd: resolve(import.meta.dirname, "../commands") })) {
|
||||
const imported = await import(`../commands/${file}`);
|
||||
|
||||
const name = typeof imported.default.data === "function" ? imported.default.data().name : imported.default.data.name;
|
||||
commands.set(name.toLowerCase(), imported.default);
|
||||
|
||||
if (imported.default.init) {
|
||||
try {
|
||||
await imported.default.init();
|
||||
}
|
||||
catch (error) {
|
||||
//* Failed to initialize command
|
||||
console.error(`Failed to initialize command ${name}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return commands;
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
import { resolve } from "node:path";
|
||||
import { glob } from "glob";
|
||||
|
||||
export default async function loadEvents() {
|
||||
for (const file of await glob("*.js", { cwd: resolve(import.meta.dirname, "../events") })) {
|
||||
import(`../events/${file}`);
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
import process from "node:process";
|
||||
import { createLogger, format, transports } from "winston";
|
||||
|
||||
export const logger = createLogger({
|
||||
level: process.env.NODE_ENV === "production" ? (process.env.LOG_LEVEL || "info") : (process.env.LOG_LEVEL || "debug"),
|
||||
format: format.combine(
|
||||
format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
|
||||
format.errors({ stack: true }),
|
||||
format.splat(),
|
||||
format.json(),
|
||||
),
|
||||
transports: [
|
||||
new transports.Console({
|
||||
format: format.combine(
|
||||
format.colorize(),
|
||||
format.printf(({ timestamp, level, message, ...metadata }) => {
|
||||
let msg = `${timestamp} [${level}] : ${message}`;
|
||||
if (Object.keys(metadata).length > 0) {
|
||||
msg += `\n${JSON.stringify(metadata, null, 2)}`;
|
||||
}
|
||||
return msg;
|
||||
}),
|
||||
),
|
||||
}),
|
||||
new transports.File({
|
||||
filename: "error.log",
|
||||
level: "error",
|
||||
format: format.combine(
|
||||
format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
|
||||
format.json(),
|
||||
),
|
||||
}),
|
||||
new transports.File({
|
||||
filename: "combined.log",
|
||||
format: format.combine(
|
||||
format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
|
||||
format.json(),
|
||||
),
|
||||
}),
|
||||
],
|
||||
});
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"rootDir": "src",
|
||||
"outDir": "dist"
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"extends": "./tsconfig.app.json",
|
||||
"compilerOptions": {
|
||||
"types": ["@types/node"],
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
1
apps/docs/.vitepress/.gitignore
vendored
1
apps/docs/.vitepress/.gitignore
vendored
@@ -1 +0,0 @@
|
||||
cache
|
||||
@@ -1,129 +0,0 @@
|
||||
import { defineConfig } from "vitepress";
|
||||
|
||||
// https://vitepress.dev/reference/site-config
|
||||
export default defineConfig({
|
||||
title: "Documentation",
|
||||
description: "Official Documentation",
|
||||
locales: {
|
||||
root: {
|
||||
label: "English",
|
||||
lang: "en-US",
|
||||
},
|
||||
de: {
|
||||
label: "Deutsch",
|
||||
lang: "de-DE",
|
||||
},
|
||||
},
|
||||
themeConfig: {
|
||||
nav: [
|
||||
{
|
||||
text: "Presence Development",
|
||||
link: "/dev/getting-started",
|
||||
},
|
||||
{
|
||||
text: "Reference",
|
||||
link: "/reference/presence",
|
||||
},
|
||||
],
|
||||
sidebar: {
|
||||
"/default": {
|
||||
base: "/",
|
||||
items: [
|
||||
{
|
||||
text: "Getting Started",
|
||||
link: "/",
|
||||
items: [
|
||||
{
|
||||
text: "Introduction",
|
||||
link: "/introduction/",
|
||||
},
|
||||
{
|
||||
text: "Installation",
|
||||
link: "/installation/",
|
||||
},
|
||||
{
|
||||
text: "Setup",
|
||||
link: "/setup/",
|
||||
},
|
||||
{
|
||||
text: "FAQ",
|
||||
link: "/faq/",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Development",
|
||||
link: "/development/",
|
||||
items: [
|
||||
{
|
||||
text: "Presence Development",
|
||||
link: "/presence-development/",
|
||||
collapsed: true,
|
||||
items: [
|
||||
{
|
||||
text: "Getting Started",
|
||||
link: "/presence-development/getting-started/",
|
||||
},
|
||||
{
|
||||
text: "Creating a Presence",
|
||||
link: "/presence-development/creating-a-presence/",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Contribute",
|
||||
link: "/contribute/",
|
||||
items: [
|
||||
{
|
||||
text: "Report a Bug",
|
||||
link: "https://github.com/PreMiD",
|
||||
},
|
||||
{
|
||||
text: "Submit a Feature",
|
||||
link: "https://discord.premid.app",
|
||||
},
|
||||
{
|
||||
text: "Donate",
|
||||
link: "https://patreon.com/Timeraa",
|
||||
},
|
||||
{
|
||||
text: "Translate",
|
||||
link: "https://crowdin.com/project/premid",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
"/reference/": {
|
||||
base: "/reference",
|
||||
items: [
|
||||
{
|
||||
text: "Reference",
|
||||
link: "/presence",
|
||||
items: [
|
||||
{
|
||||
text: "Presence",
|
||||
link: "/presence",
|
||||
},
|
||||
{
|
||||
text: "Iframe",
|
||||
link: "/iframe",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
socialLinks: [
|
||||
{ icon: "github", link: "https://github.com/PreMiD" },
|
||||
{ icon: "discord", link: "https://discord.premid.app" },
|
||||
{ icon: "x", link: "https://x.com/PreMiDapp" },
|
||||
],
|
||||
i18nRouting: true,
|
||||
logo: "/logo.svg",
|
||||
search: { provider: "local" },
|
||||
},
|
||||
lastUpdated: true,
|
||||
});
|
||||
@@ -1,77 +0,0 @@
|
||||
# Creating a Presence
|
||||
|
||||
## Introduction
|
||||
|
||||
PreMiD Presences are the core of the PreMiD application. They allow you to add support for your favorite websites and services, or create your own custom Presences. This guide will walk you through the process of creating a Presence for PreMiD.
|
||||
|
||||
Please go through the [Getting Started](./getting-started) guide before proceeding with this guide. It will help you set up your development environment and install the necessary tools.
|
||||
|
||||
To make the process of creating a Presence easier, we have provided a command-line interface (CLI) tool. This tool will help you generate a new Presence project with all the necessary files and configurations, so you can start coding your Presence right away.
|
||||
|
||||
The CLI will also help you build and test your Presence before submitting it to the PreMiD Store. Testing is required to ensure your Presence works as expected and meets the quality standards. Proof that your Presence works is required for it to be approved. This is usually done by providing a video or a screenshot of your Presence in action.
|
||||
|
||||
## Creating a New Presence
|
||||
|
||||
To create a new Presence, we will run some scripts. This will generate a new Presence project with all the necessary files and configurations. To create a new Presence, follow these steps:
|
||||
|
||||
1. Open your terminal and run the following command:
|
||||
|
||||
```sh
|
||||
pnpm create
|
||||
```
|
||||
|
||||
2. Follow the on-screen instructions to create a new Presence project.
|
||||
|
||||
### Coding your Presence
|
||||
|
||||
Once you have created a new Presence project, you can start coding your Presence. First of all, you need to understand the structure of a Presence project.
|
||||
|
||||
#### Presence Structure
|
||||
|
||||
A Presence project consists of the following files and directories:
|
||||
|
||||
- `metadata.json`: This file contains the metadata for your Presence, such as the name, description, and version.
|
||||
- `presence.ts`: This file contains the code for your Presence. This is where you will write the logic to detect the presence of your website or service.
|
||||
- `iframe.ts` (optional): This file contains the code for the Presence's iframe. This is where we will be able to interact with embedded iframes on the website.
|
||||
|
||||
#### Development Server
|
||||
|
||||
Let's start a Development Server to build and test your Presence. Follow these steps:
|
||||
|
||||
1. Start a development server to be able to build and test your Presence:
|
||||
|
||||
```sh
|
||||
pnpm dev "Your Presence Name"
|
||||
```
|
||||
|
||||
2. Open your browser and go to the PreMiD Extension settings page, then enable Developer Mode.
|
||||
3. You should now see your new Presence in the list of Presences.
|
||||
|
||||
#### Editing the `presence.ts` File
|
||||
|
||||
In order to fetch the data from the website, you need to write the logic in the `presence.ts` file. We will use native JavaScript functions to fetch the data from the website. Let's see an example:
|
||||
|
||||
```ts
|
||||
const presence = new Presence({
|
||||
clientId: "Your Client ID",
|
||||
});
|
||||
|
||||
const enum Asset {
|
||||
Logo = "https://cdn.rcd.gg/PreMiD.png",
|
||||
}
|
||||
|
||||
presence.on("UpdateData", async () => {
|
||||
const title = document.querySelector("title");
|
||||
const description = document.querySelector("meta[name=\"description\"]");
|
||||
|
||||
const data: PresenceData = {
|
||||
details: title.textContent,
|
||||
state: description.getAttribute("content"),
|
||||
largeImageKey: Asset.Logo,
|
||||
};
|
||||
|
||||
presence.setActivity(data);
|
||||
});
|
||||
```
|
||||
|
||||
In this example, we are fetching the title and description of the website and setting them as the Presence details and state, respectively. We are also setting a custom logo as the large image key.
|
||||
@@ -1,50 +0,0 @@
|
||||
# Getting Started
|
||||
|
||||
## Installation
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- [Git](https://git-scm.com/).
|
||||
- [Node.js](https://nodejs.org/) version 18 or higher, includes [Corepack](https://github.com/nodejs/corepack) by default.
|
||||
- Terminal for accessing PreMiD's Developer Tools via its command-line interface (CLI).
|
||||
- Text Editor with [TypeScript](https://www.typescriptlang.org/) syntax highlighting support.
|
||||
- [Visual Studio Code](https://code.visualstudio.com/) is recommended, as it includes TypeScript support out-of-the-box.
|
||||
|
||||
### Clone the Repository
|
||||
|
||||
- Open your terminal and run the following command:
|
||||
```sh
|
||||
git clone https://github.com/PreMiD/Presences.git
|
||||
```
|
||||
- Change your working directory to the repository:
|
||||
```sh
|
||||
cd Presences
|
||||
```
|
||||
|
||||
### Install Dependencies
|
||||
|
||||
- Ensure you have Node.js installed by running:
|
||||
```sh
|
||||
node -v
|
||||
```
|
||||
If you see a version number, Node.js is installed. Make sure you have Node.js version 18 or higher.
|
||||
- Enable Corepack by running:
|
||||
```sh
|
||||
corepack enable
|
||||
```
|
||||
- Install the project dependencies:
|
||||
```sh
|
||||
pnpm install
|
||||
```
|
||||
|
||||
## Coding your Presence
|
||||
|
||||
Follow the [Creating a Presence](./creating-a-presence) guide to get started with coding your own Presence.
|
||||
|
||||
## Submitting your Presence
|
||||
|
||||
Once you've finished coding your Presence, you can submit it to the PreMiD Store for others to use. Follow the [Submitting a Presence](./submitting-a-presence) guide to learn how to submit your Presence.
|
||||
|
||||
A member of the PreMiD Team will review your submission and if it meets the guidelines, it will be added to the PreMiD Store for everyone to use. If your submission is rejected, you will receive feedback on how to improve it.
|
||||
|
||||
Please note that all submissions are subject to review and approval by the PreMiD Team. We reserve the right to reject any submission that does not meet our guidelines or quality standards. Reviews may take up to 7 days to complete.
|
||||
@@ -1,5 +0,0 @@
|
||||
# Getting Started
|
||||
|
||||
Welcome to the official documentation for PreMiD! This guide will help you get started with PreMiD.
|
||||
|
||||
## Installation
|
||||
@@ -1,51 +0,0 @@
|
||||
---
|
||||
# https://vitepress.dev/reference/default-theme-home-page
|
||||
layout: home
|
||||
|
||||
hero:
|
||||
name: "PreMiD"
|
||||
text: "Documentation"
|
||||
tagline: "The official documentation for PreMiD."
|
||||
image:
|
||||
src: /logo.svg
|
||||
alt: PreMiD Logo
|
||||
actions:
|
||||
- theme: brand
|
||||
text: Get Started
|
||||
link: /getting-started
|
||||
- theme: alt
|
||||
text: Presence Development
|
||||
link: /dev/getting-started
|
||||
features:
|
||||
- icon: 🛠️
|
||||
title: Extensible
|
||||
details: Add Presences for your favorite websites and services. Or create your own!
|
||||
- icon: 🌐
|
||||
title: Cross-Platform
|
||||
details: PreMiD is available for all major browsers and platforms.
|
||||
- icon: 🚀
|
||||
title: Lightweight
|
||||
details: PreMiD is designed to be as lightweight as possible, so it won't slow down your system.
|
||||
---
|
||||
|
||||
<style>
|
||||
:root {
|
||||
--vp-home-hero-name-color: transparent;
|
||||
--vp-home-hero-name-background: -webkit-linear-gradient(120deg, rgb(209, 122, 254) 30%, rgb(89, 195, 246));
|
||||
|
||||
--vp-home-hero-image-background-image: linear-gradient(-45deg, rgb(209, 122, 254) 50%, rgb(89, 195, 246) 50%);
|
||||
--vp-home-hero-image-filter: blur(44px);
|
||||
}
|
||||
|
||||
@media (min-width: 640px) {
|
||||
:root {
|
||||
--vp-home-hero-image-filter: blur(56px);
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 960px) {
|
||||
:root {
|
||||
--vp-home-hero-image-filter: blur(68px);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,14 +0,0 @@
|
||||
{
|
||||
"name": "@premid/docs",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"description": "Documentation for Premid",
|
||||
"scripts": {
|
||||
"dev": "vitepress dev",
|
||||
"build": "vitepress build",
|
||||
"preview": "vitepress preview"
|
||||
},
|
||||
"devDependencies": {
|
||||
"vitepress": "1.3.1"
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
|
Before Width: | Height: | Size: 288 KiB |
@@ -1,68 +0,0 @@
|
||||
# Presence Class
|
||||
|
||||
The `Presence` class is the main class used to create a Presence.
|
||||
|
||||
## Overview
|
||||
|
||||
The `Presence` class is the main class used to create a Presence. It is used to interact with the PreMiD Extension.
|
||||
|
||||
### Example
|
||||
|
||||
```javascript
|
||||
const presence = new Presence({
|
||||
clientId: "<Your Client ID>",
|
||||
});
|
||||
|
||||
presence.on("UpdateData", () => {
|
||||
// Logic to update the presence data
|
||||
|
||||
presence.setActivity({
|
||||
details: "Example Presence",
|
||||
state: "Example State",
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Constructor
|
||||
|
||||
### `new Presence(options: PresenceOptions)`
|
||||
|
||||
Creates a new `Presence` instance.
|
||||
|
||||
#### Parameters
|
||||
|
||||
- `options` (`PresenceOptions`): The options for the Presence.
|
||||
|
||||
#### Returns
|
||||
|
||||
- `Presence`: The new `Presence` instance.
|
||||
|
||||
## Properties
|
||||
|
||||
### `clientId: string`
|
||||
|
||||
The Client ID of the Presence.
|
||||
|
||||
## Methods
|
||||
|
||||
### `setActivity(activity: PresenceActivity)`
|
||||
|
||||
Sets the activity of the Presence.
|
||||
|
||||
#### Parameters
|
||||
|
||||
- `activity` (`PresenceActivity`): The activity to set.
|
||||
|
||||
### `clearActivity()`
|
||||
|
||||
Clears the activity of the Presence.
|
||||
|
||||
### `on(event: string, listener: Function)`
|
||||
|
||||
Adds a listener to an event.
|
||||
|
||||
#### Parameters
|
||||
|
||||
- `event` (`string`): The event to listen to.
|
||||
|
||||
- `listener` (`Function`): The listener to add.
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@premid/schema-server",
|
||||
"type": "module",
|
||||
"version": "1.0.10",
|
||||
"version": "1.0.11",
|
||||
"private": true,
|
||||
"description": "A small service to serve the JSON schemas for PreMiD",
|
||||
"license": "MPL-2.0",
|
||||
|
||||
255
apps/schema-server/schemas/metadata/1.16.json
Normal file
255
apps/schema-server/schemas/metadata/1.16.json
Normal file
@@ -0,0 +1,255 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema",
|
||||
"$id": "https://schemas.premid.app/metadata/1.16",
|
||||
"title": "Metadata",
|
||||
"type": "object",
|
||||
"description": "Metadata that describes an activity.",
|
||||
"definitions": {
|
||||
"user": {
|
||||
"type": "object",
|
||||
"description": "User information.",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string",
|
||||
"description": "The name of the user."
|
||||
},
|
||||
"id": {
|
||||
"type": "string",
|
||||
"description": "The Discord snowflake of the user.",
|
||||
"pattern": "^\\d+$"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"name",
|
||||
"id"
|
||||
]
|
||||
}
|
||||
},
|
||||
"properties": {
|
||||
"$schema": {
|
||||
"$comment": "This is required otherwise the schema will fail itself when it is applied to a document via $schema. This is optional so that validators that use this schema don't fail if the metadata doesn't have the $schema property.",
|
||||
"type": "string",
|
||||
"description": "The metadata schema URL."
|
||||
},
|
||||
"author": {
|
||||
"$ref": "#/definitions/user",
|
||||
"description": "The author of this activity."
|
||||
},
|
||||
"contributors": {
|
||||
"type": "array",
|
||||
"description": "Any extra contributors to this activity.",
|
||||
"items": {
|
||||
"$ref": "#/definitions/user"
|
||||
}
|
||||
},
|
||||
"service": {
|
||||
"type": "string",
|
||||
"description": "The service this activity is for."
|
||||
},
|
||||
"altnames": {
|
||||
"type": "array",
|
||||
"description": "Alternative names for the service.",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"description": "An alternative name."
|
||||
},
|
||||
"minItems": 1
|
||||
},
|
||||
"description": {
|
||||
"type": "object",
|
||||
"description": "A description of the activity in multiple languages.",
|
||||
"propertyNames": {
|
||||
"type": "string",
|
||||
"description": "The language key in the format: languagecode or languagecode-regioncode.",
|
||||
"pattern": "^[a-z]{2,3}(?:-(?:[a-z]{2}|[0-9]{1,3}))?$"
|
||||
},
|
||||
"patternProperties": {
|
||||
"^[a-z]{2,3}(?:-(?:[a-z]{2}|[0-9]{1,3}))?$": {
|
||||
"type": "string",
|
||||
"description": "The description of the activity in the key's language."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"en"
|
||||
]
|
||||
},
|
||||
"url": {
|
||||
"type": [
|
||||
"string",
|
||||
"array"
|
||||
],
|
||||
"description": "The service's website URL, or an array of URLs. Protocols should not be added. Not used for matching.",
|
||||
"pattern": "^(([a-z0-9-]+\\.)*[0-9a-z_-]+(\\.[a-z]+)+|(\\d{1,3}\\.){3}\\d{1,3}|localhost)$",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"description": "One of the service's website URLs.",
|
||||
"pattern": "^(([a-z0-9-]+\\.)*[0-9a-z_-]+(\\.[a-z]+)+|(\\d{1,3}\\.){3}\\d{1,3}|localhost)$"
|
||||
},
|
||||
"minItems": 2
|
||||
},
|
||||
"version": {
|
||||
"type": "string",
|
||||
"description": "The SemVer version of the activity in the format: major.minor.patch.",
|
||||
"pattern": "^\\d+\\.\\d+\\.\\d+$"
|
||||
},
|
||||
"apiVersion": {
|
||||
"type": "integer",
|
||||
"description": "The Activity System version this activity supports.",
|
||||
"minimum": 1,
|
||||
"maximum": 2
|
||||
},
|
||||
"logo": {
|
||||
"type": "string",
|
||||
"description": "The logo of the service this activity is for.",
|
||||
"pattern": "^https?://.+\\.(png|jpe?g|gif|webp)$"
|
||||
},
|
||||
"thumbnail": {
|
||||
"type": "string",
|
||||
"description": "A thumbnail of the service this activity is for.",
|
||||
"pattern": "^https?://.+\\.(png|jpe?g|gif|webp)$"
|
||||
},
|
||||
"color": {
|
||||
"type": "string",
|
||||
"description": "The theme color of the service this activity is for. Must be either a 6 digit or a 3 digit hex code.",
|
||||
"pattern": "^#([A-Fa-f0-9]{3}){1,2}$"
|
||||
},
|
||||
"tags": {
|
||||
"type": "array",
|
||||
"description": "The tags for the activity.",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"description": "A tag.",
|
||||
"pattern": "^[^A-Z\\s!\"#$%&'()*+,./:;<=>?@\\[\\\\\\]^_`{|}~]+$"
|
||||
},
|
||||
"minItems": 1
|
||||
},
|
||||
"category": {
|
||||
"type": "string",
|
||||
"description": "The category the activity falls under.",
|
||||
"enum": [
|
||||
"anime",
|
||||
"games",
|
||||
"music",
|
||||
"socials",
|
||||
"videos",
|
||||
"other"
|
||||
]
|
||||
},
|
||||
"iframe": {
|
||||
"type": "boolean",
|
||||
"description": "Whether or not the activity should run in iframes."
|
||||
},
|
||||
"readLogs": {
|
||||
"type": "boolean",
|
||||
"description": "Whether or not the extension should be reading logs."
|
||||
},
|
||||
"regExp": {
|
||||
"type": "string",
|
||||
"description": "A regular expression used to match URLs for the activity to inject into."
|
||||
},
|
||||
"iFrameRegExp": {
|
||||
"type": "string",
|
||||
"description": "A regular expression used to match iframes for the activity to inject into."
|
||||
},
|
||||
"allowURLOverrides": {
|
||||
"type": "boolean",
|
||||
"description": "Whether or not the activity should allow the user to override the activity's matching regExps."
|
||||
},
|
||||
"settings": {
|
||||
"type": "array",
|
||||
"description": "An array of settings the user can change in the activity.",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"description": "A setting.",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"description": "The ID of the setting."
|
||||
},
|
||||
"title": {
|
||||
"type": "string",
|
||||
"description": "The title of the setting. Required only if `multiLanguage` is disabled."
|
||||
},
|
||||
"description": {
|
||||
"type": "string",
|
||||
"description": "The description of the setting. Only applicable if `multiLanguage` is disabled."
|
||||
},
|
||||
"icon": {
|
||||
"type": "string",
|
||||
"description": "The icon of the setting. Required only if `multiLanguage` is disabled.",
|
||||
"pattern": "^fa([bsdrlt]|([-](brands|solid|duotone|regular|light|thin))) fa-[0-9a-z-]+$"
|
||||
},
|
||||
"if": {
|
||||
"type": "object",
|
||||
"description": "Restrict showing this setting if another setting is the defined value.",
|
||||
"propertyNames": {
|
||||
"type": "string",
|
||||
"description": "The ID of the setting."
|
||||
},
|
||||
"patternProperties": {
|
||||
"": {
|
||||
"type": [
|
||||
"string",
|
||||
"number",
|
||||
"boolean"
|
||||
],
|
||||
"description": "The value of the setting."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"placeholder": {
|
||||
"type": "string",
|
||||
"description": "The placeholder for settings that require input. Shown when the input is empty."
|
||||
},
|
||||
"value": {
|
||||
"type": [
|
||||
"string",
|
||||
"number",
|
||||
"boolean"
|
||||
],
|
||||
"description": "The default value of the setting. Not compatible with `values`."
|
||||
},
|
||||
"values": {
|
||||
"type": "array",
|
||||
"description": "The default values of the setting. Not compatible with `value`.",
|
||||
"items": {
|
||||
"type": [
|
||||
"string",
|
||||
"number",
|
||||
"boolean"
|
||||
],
|
||||
"description": "The value of the setting."
|
||||
}
|
||||
},
|
||||
"multiLanguage": {
|
||||
"type": "boolean",
|
||||
"description": "When true, strings from the `general.json` file are available for use, plus the <service>.json file. False is not allowed."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"mobile": {
|
||||
"type": "boolean",
|
||||
"description": "Whether or not the activity has support for mobile devices."
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"author",
|
||||
"service",
|
||||
"description",
|
||||
"url",
|
||||
"version",
|
||||
"apiVersion",
|
||||
"logo",
|
||||
"thumbnail",
|
||||
"color",
|
||||
"tags",
|
||||
"category",
|
||||
"regExp"
|
||||
]
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
NUXT_DISCORD_BOT_TOKEN=""
|
||||
24
apps/website/.gitignore
vendored
24
apps/website/.gitignore
vendored
@@ -1,24 +0,0 @@
|
||||
# Nuxt dev/build outputs
|
||||
.output
|
||||
.data
|
||||
.nuxt
|
||||
.nitro
|
||||
.cache
|
||||
dist
|
||||
|
||||
# Node dependencies
|
||||
node_modules
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
|
||||
# Misc
|
||||
.DS_Store
|
||||
.fleet
|
||||
.idea
|
||||
|
||||
# Local env files
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
@@ -1,373 +0,0 @@
|
||||
Mozilla Public License Version 2.0
|
||||
==================================
|
||||
|
||||
1. Definitions
|
||||
--------------
|
||||
|
||||
1.1. "Contributor"
|
||||
means each individual or legal entity that creates, contributes to
|
||||
the creation of, or owns Covered Software.
|
||||
|
||||
1.2. "Contributor Version"
|
||||
means the combination of the Contributions of others (if any) used
|
||||
by a Contributor and that particular Contributor's Contribution.
|
||||
|
||||
1.3. "Contribution"
|
||||
means Covered Software of a particular Contributor.
|
||||
|
||||
1.4. "Covered Software"
|
||||
means Source Code Form to which the initial Contributor has attached
|
||||
the notice in Exhibit A, the Executable Form of such Source Code
|
||||
Form, and Modifications of such Source Code Form, in each case
|
||||
including portions thereof.
|
||||
|
||||
1.5. "Incompatible With Secondary Licenses"
|
||||
means
|
||||
|
||||
(a) that the initial Contributor has attached the notice described
|
||||
in Exhibit B to the Covered Software; or
|
||||
|
||||
(b) that the Covered Software was made available under the terms of
|
||||
version 1.1 or earlier of the License, but not also under the
|
||||
terms of a Secondary License.
|
||||
|
||||
1.6. "Executable Form"
|
||||
means any form of the work other than Source Code Form.
|
||||
|
||||
1.7. "Larger Work"
|
||||
means a work that combines Covered Software with other material, in
|
||||
a separate file or files, that is not Covered Software.
|
||||
|
||||
1.8. "License"
|
||||
means this document.
|
||||
|
||||
1.9. "Licensable"
|
||||
means having the right to grant, to the maximum extent possible,
|
||||
whether at the time of the initial grant or subsequently, any and
|
||||
all of the rights conveyed by this License.
|
||||
|
||||
1.10. "Modifications"
|
||||
means any of the following:
|
||||
|
||||
(a) any file in Source Code Form that results from an addition to,
|
||||
deletion from, or modification of the contents of Covered
|
||||
Software; or
|
||||
|
||||
(b) any new file in Source Code Form that contains any Covered
|
||||
Software.
|
||||
|
||||
1.11. "Patent Claims" of a Contributor
|
||||
means any patent claim(s), including without limitation, method,
|
||||
process, and apparatus claims, in any patent Licensable by such
|
||||
Contributor that would be infringed, but for the grant of the
|
||||
License, by the making, using, selling, offering for sale, having
|
||||
made, import, or transfer of either its Contributions or its
|
||||
Contributor Version.
|
||||
|
||||
1.12. "Secondary License"
|
||||
means either the GNU General Public License, Version 2.0, the GNU
|
||||
Lesser General Public License, Version 2.1, the GNU Affero General
|
||||
Public License, Version 3.0, or any later versions of those
|
||||
licenses.
|
||||
|
||||
1.13. "Source Code Form"
|
||||
means the form of the work preferred for making modifications.
|
||||
|
||||
1.14. "You" (or "Your")
|
||||
means an individual or a legal entity exercising rights under this
|
||||
License. For legal entities, "You" includes any entity that
|
||||
controls, is controlled by, or is under common control with You. For
|
||||
purposes of this definition, "control" means (a) the power, direct
|
||||
or indirect, to cause the direction or management of such entity,
|
||||
whether by contract or otherwise, or (b) ownership of more than
|
||||
fifty percent (50%) of the outstanding shares or beneficial
|
||||
ownership of such entity.
|
||||
|
||||
2. License Grants and Conditions
|
||||
--------------------------------
|
||||
|
||||
2.1. Grants
|
||||
|
||||
Each Contributor hereby grants You a world-wide, royalty-free,
|
||||
non-exclusive license:
|
||||
|
||||
(a) under intellectual property rights (other than patent or trademark)
|
||||
Licensable by such Contributor to use, reproduce, make available,
|
||||
modify, display, perform, distribute, and otherwise exploit its
|
||||
Contributions, either on an unmodified basis, with Modifications, or
|
||||
as part of a Larger Work; and
|
||||
|
||||
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
||||
for sale, have made, import, and otherwise transfer either its
|
||||
Contributions or its Contributor Version.
|
||||
|
||||
2.2. Effective Date
|
||||
|
||||
The licenses granted in Section 2.1 with respect to any Contribution
|
||||
become effective for each Contribution on the date the Contributor first
|
||||
distributes such Contribution.
|
||||
|
||||
2.3. Limitations on Grant Scope
|
||||
|
||||
The licenses granted in this Section 2 are the only rights granted under
|
||||
this License. No additional rights or licenses will be implied from the
|
||||
distribution or licensing of Covered Software under this License.
|
||||
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
||||
Contributor:
|
||||
|
||||
(a) for any code that a Contributor has removed from Covered Software;
|
||||
or
|
||||
|
||||
(b) for infringements caused by: (i) Your and any other third party's
|
||||
modifications of Covered Software, or (ii) the combination of its
|
||||
Contributions with other software (except as part of its Contributor
|
||||
Version); or
|
||||
|
||||
(c) under Patent Claims infringed by Covered Software in the absence of
|
||||
its Contributions.
|
||||
|
||||
This License does not grant any rights in the trademarks, service marks,
|
||||
or logos of any Contributor (except as may be necessary to comply with
|
||||
the notice requirements in Section 3.4).
|
||||
|
||||
2.4. Subsequent Licenses
|
||||
|
||||
No Contributor makes additional grants as a result of Your choice to
|
||||
distribute the Covered Software under a subsequent version of this
|
||||
License (see Section 10.2) or under the terms of a Secondary License (if
|
||||
permitted under the terms of Section 3.3).
|
||||
|
||||
2.5. Representation
|
||||
|
||||
Each Contributor represents that the Contributor believes its
|
||||
Contributions are its original creation(s) or it has sufficient rights
|
||||
to grant the rights to its Contributions conveyed by this License.
|
||||
|
||||
2.6. Fair Use
|
||||
|
||||
This License is not intended to limit any rights You have under
|
||||
applicable copyright doctrines of fair use, fair dealing, or other
|
||||
equivalents.
|
||||
|
||||
2.7. Conditions
|
||||
|
||||
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
||||
in Section 2.1.
|
||||
|
||||
3. Responsibilities
|
||||
-------------------
|
||||
|
||||
3.1. Distribution of Source Form
|
||||
|
||||
All distribution of Covered Software in Source Code Form, including any
|
||||
Modifications that You create or to which You contribute, must be under
|
||||
the terms of this License. You must inform recipients that the Source
|
||||
Code Form of the Covered Software is governed by the terms of this
|
||||
License, and how they can obtain a copy of this License. You may not
|
||||
attempt to alter or restrict the recipients' rights in the Source Code
|
||||
Form.
|
||||
|
||||
3.2. Distribution of Executable Form
|
||||
|
||||
If You distribute Covered Software in Executable Form then:
|
||||
|
||||
(a) such Covered Software must also be made available in Source Code
|
||||
Form, as described in Section 3.1, and You must inform recipients of
|
||||
the Executable Form how they can obtain a copy of such Source Code
|
||||
Form by reasonable means in a timely manner, at a charge no more
|
||||
than the cost of distribution to the recipient; and
|
||||
|
||||
(b) You may distribute such Executable Form under the terms of this
|
||||
License, or sublicense it under different terms, provided that the
|
||||
license for the Executable Form does not attempt to limit or alter
|
||||
the recipients' rights in the Source Code Form under this License.
|
||||
|
||||
3.3. Distribution of a Larger Work
|
||||
|
||||
You may create and distribute a Larger Work under terms of Your choice,
|
||||
provided that You also comply with the requirements of this License for
|
||||
the Covered Software. If the Larger Work is a combination of Covered
|
||||
Software with a work governed by one or more Secondary Licenses, and the
|
||||
Covered Software is not Incompatible With Secondary Licenses, this
|
||||
License permits You to additionally distribute such Covered Software
|
||||
under the terms of such Secondary License(s), so that the recipient of
|
||||
the Larger Work may, at their option, further distribute the Covered
|
||||
Software under the terms of either this License or such Secondary
|
||||
License(s).
|
||||
|
||||
3.4. Notices
|
||||
|
||||
You may not remove or alter the substance of any license notices
|
||||
(including copyright notices, patent notices, disclaimers of warranty,
|
||||
or limitations of liability) contained within the Source Code Form of
|
||||
the Covered Software, except that You may alter any license notices to
|
||||
the extent required to remedy known factual inaccuracies.
|
||||
|
||||
3.5. Application of Additional Terms
|
||||
|
||||
You may choose to offer, and to charge a fee for, warranty, support,
|
||||
indemnity or liability obligations to one or more recipients of Covered
|
||||
Software. However, You may do so only on Your own behalf, and not on
|
||||
behalf of any Contributor. You must make it absolutely clear that any
|
||||
such warranty, support, indemnity, or liability obligation is offered by
|
||||
You alone, and You hereby agree to indemnify every Contributor for any
|
||||
liability incurred by such Contributor as a result of warranty, support,
|
||||
indemnity or liability terms You offer. You may include additional
|
||||
disclaimers of warranty and limitations of liability specific to any
|
||||
jurisdiction.
|
||||
|
||||
4. Inability to Comply Due to Statute or Regulation
|
||||
---------------------------------------------------
|
||||
|
||||
If it is impossible for You to comply with any of the terms of this
|
||||
License with respect to some or all of the Covered Software due to
|
||||
statute, judicial order, or regulation then You must: (a) comply with
|
||||
the terms of this License to the maximum extent possible; and (b)
|
||||
describe the limitations and the code they affect. Such description must
|
||||
be placed in a text file included with all distributions of the Covered
|
||||
Software under this License. Except to the extent prohibited by statute
|
||||
or regulation, such description must be sufficiently detailed for a
|
||||
recipient of ordinary skill to be able to understand it.
|
||||
|
||||
5. Termination
|
||||
--------------
|
||||
|
||||
5.1. The rights granted under this License will terminate automatically
|
||||
if You fail to comply with any of its terms. However, if You become
|
||||
compliant, then the rights granted under this License from a particular
|
||||
Contributor are reinstated (a) provisionally, unless and until such
|
||||
Contributor explicitly and finally terminates Your grants, and (b) on an
|
||||
ongoing basis, if such Contributor fails to notify You of the
|
||||
non-compliance by some reasonable means prior to 60 days after You have
|
||||
come back into compliance. Moreover, Your grants from a particular
|
||||
Contributor are reinstated on an ongoing basis if such Contributor
|
||||
notifies You of the non-compliance by some reasonable means, this is the
|
||||
first time You have received notice of non-compliance with this License
|
||||
from such Contributor, and You become compliant prior to 30 days after
|
||||
Your receipt of the notice.
|
||||
|
||||
5.2. If You initiate litigation against any entity by asserting a patent
|
||||
infringement claim (excluding declaratory judgment actions,
|
||||
counter-claims, and cross-claims) alleging that a Contributor Version
|
||||
directly or indirectly infringes any patent, then the rights granted to
|
||||
You by any and all Contributors for the Covered Software under Section
|
||||
2.1 of this License shall terminate.
|
||||
|
||||
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
|
||||
end user license agreements (excluding distributors and resellers) which
|
||||
have been validly granted by You or Your distributors under this License
|
||||
prior to termination shall survive termination.
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 6. Disclaimer of Warranty *
|
||||
* ------------------------- *
|
||||
* *
|
||||
* Covered Software is provided under this License on an "as is" *
|
||||
* basis, without warranty of any kind, either expressed, implied, or *
|
||||
* statutory, including, without limitation, warranties that the *
|
||||
* Covered Software is free of defects, merchantable, fit for a *
|
||||
* particular purpose or non-infringing. The entire risk as to the *
|
||||
* quality and performance of the Covered Software is with You. *
|
||||
* Should any Covered Software prove defective in any respect, You *
|
||||
* (not any Contributor) assume the cost of any necessary servicing, *
|
||||
* repair, or correction. This disclaimer of warranty constitutes an *
|
||||
* essential part of this License. No use of any Covered Software is *
|
||||
* authorized under this License except under this disclaimer. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 7. Limitation of Liability *
|
||||
* -------------------------- *
|
||||
* *
|
||||
* Under no circumstances and under no legal theory, whether tort *
|
||||
* (including negligence), contract, or otherwise, shall any *
|
||||
* Contributor, or anyone who distributes Covered Software as *
|
||||
* permitted above, be liable to You for any direct, indirect, *
|
||||
* special, incidental, or consequential damages of any character *
|
||||
* including, without limitation, damages for lost profits, loss of *
|
||||
* goodwill, work stoppage, computer failure or malfunction, or any *
|
||||
* and all other commercial damages or losses, even if such party *
|
||||
* shall have been informed of the possibility of such damages. This *
|
||||
* limitation of liability shall not apply to liability for death or *
|
||||
* personal injury resulting from such party's negligence to the *
|
||||
* extent applicable law prohibits such limitation. Some *
|
||||
* jurisdictions do not allow the exclusion or limitation of *
|
||||
* incidental or consequential damages, so this exclusion and *
|
||||
* limitation may not apply to You. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
8. Litigation
|
||||
-------------
|
||||
|
||||
Any litigation relating to this License may be brought only in the
|
||||
courts of a jurisdiction where the defendant maintains its principal
|
||||
place of business and such litigation shall be governed by laws of that
|
||||
jurisdiction, without reference to its conflict-of-law provisions.
|
||||
Nothing in this Section shall prevent a party's ability to bring
|
||||
cross-claims or counter-claims.
|
||||
|
||||
9. Miscellaneous
|
||||
----------------
|
||||
|
||||
This License represents the complete agreement concerning the subject
|
||||
matter hereof. If any provision of this License is held to be
|
||||
unenforceable, such provision shall be reformed only to the extent
|
||||
necessary to make it enforceable. Any law or regulation which provides
|
||||
that the language of a contract shall be construed against the drafter
|
||||
shall not be used to construe this License against a Contributor.
|
||||
|
||||
10. Versions of the License
|
||||
---------------------------
|
||||
|
||||
10.1. New Versions
|
||||
|
||||
Mozilla Foundation is the license steward. Except as provided in Section
|
||||
10.3, no one other than the license steward has the right to modify or
|
||||
publish new versions of this License. Each version will be given a
|
||||
distinguishing version number.
|
||||
|
||||
10.2. Effect of New Versions
|
||||
|
||||
You may distribute the Covered Software under the terms of the version
|
||||
of the License under which You originally received the Covered Software,
|
||||
or under the terms of any subsequent version published by the license
|
||||
steward.
|
||||
|
||||
10.3. Modified Versions
|
||||
|
||||
If you create software not governed by this License, and you want to
|
||||
create a new license for such software, you may create and use a
|
||||
modified version of this License if you rename the license and remove
|
||||
any references to the name of the license steward (except to note that
|
||||
such modified license differs from this License).
|
||||
|
||||
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
||||
Licenses
|
||||
|
||||
If You choose to distribute Source Code Form that is Incompatible With
|
||||
Secondary Licenses under the terms of this version of the License, the
|
||||
notice described in Exhibit B of this License must be attached.
|
||||
|
||||
Exhibit A - Source Code Form License Notice
|
||||
-------------------------------------------
|
||||
|
||||
This Source Code Form is subject to the terms of the Mozilla Public
|
||||
License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
||||
|
||||
If it is not possible or desirable to put the notice in a particular
|
||||
file, then You may include the notice in a location (such as a LICENSE
|
||||
file in a relevant directory) where a recipient would be likely to look
|
||||
for such a notice.
|
||||
|
||||
You may add additional accurate notices of copyright ownership.
|
||||
|
||||
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
||||
---------------------------------------------------------
|
||||
|
||||
This Source Code Form is "Incompatible With Secondary Licenses", as
|
||||
defined by the Mozilla Public License, v. 2.0.
|
||||
@@ -1,77 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { useExtensionStore } from "./stores/useExtension";
|
||||
|
||||
useHead({
|
||||
htmlAttrs: {
|
||||
lang: "en",
|
||||
},
|
||||
bodyAttrs: {
|
||||
id: "app",
|
||||
},
|
||||
link: [
|
||||
{
|
||||
rel: "icon",
|
||||
type: "image/png",
|
||||
href: "/assets/images/icon.png",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
//* Cloudflare specific
|
||||
if (import.meta.env.PROD) {
|
||||
useHead({
|
||||
script: [
|
||||
{ src: "/cdn-cgi/challenge-platform/scripts/jsd/main.js", crossorigin: "anonymous", referrerpolicy: "origin" },
|
||||
],
|
||||
}, { mode: "client" });
|
||||
}
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
useSeoMeta({
|
||||
title: "PreMiD",
|
||||
ogTitle: "PreMiD",
|
||||
description: t("page.home.description"),
|
||||
ogDescription: t("page.home.description"),
|
||||
ogImage: "https://cdn.rcd.gg/PreMiD.png",
|
||||
twitterCard: "summary_large_image",
|
||||
ogUrl: "https://premid.app",
|
||||
twitterTitle: "PreMiD",
|
||||
twitterDescription: t("page.home.description"),
|
||||
applicationName: "PreMiD",
|
||||
twitterImage: "https://cdn.rcd.gg/PreMiD.png",
|
||||
});
|
||||
|
||||
/* useScriptGoogleAdsense({
|
||||
client: "ca-pub-1575460061917202",
|
||||
}); */
|
||||
|
||||
const extension = useExtensionStore();
|
||||
extension.setupGlobalEvents();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<NuxtRouteAnnouncer />
|
||||
<NuxtLoadingIndicator
|
||||
color="#7289da"
|
||||
:height="4"
|
||||
/>
|
||||
<NuxtLayout>
|
||||
<NuxtPage />
|
||||
</NuxtLayout>
|
||||
</template>
|
||||
|
||||
<style lang="scss">
|
||||
.page-enter-active,
|
||||
.page-leave-active {
|
||||
transition:
|
||||
opacity 0.3s ease-in-out,
|
||||
transform 0.3s ease-in-out;
|
||||
}
|
||||
|
||||
.page-enter-from,
|
||||
.page-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(10px);
|
||||
}
|
||||
</style>
|
||||
@@ -1,10 +0,0 @@
|
||||
const breakpoints = {
|
||||
"2xl": "1536px",
|
||||
"lg": "1200px",
|
||||
"md": "768px",
|
||||
"sm": "640px",
|
||||
"xl": "1280px",
|
||||
"xs": "480px",
|
||||
};
|
||||
|
||||
export default breakpoints;
|
||||
@@ -1,79 +0,0 @@
|
||||
<script lang="ts" setup>
|
||||
const { browser } = defineProps<{
|
||||
browser: string;
|
||||
highlight?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits(["click"]);
|
||||
|
||||
const isWIP = ref(false);
|
||||
|
||||
function getIcon(browser: string) {
|
||||
switch (browser) {
|
||||
case "Safari":
|
||||
isWIP.value = true;
|
||||
return "fa-brands fa-safari";
|
||||
case "Edge":
|
||||
return "fa-brands fa-edge";
|
||||
case "Firefox":
|
||||
return "fa-brands fa-firefox";
|
||||
case "Opera":
|
||||
return "fa-brands fa-opera";
|
||||
case "Brave":
|
||||
return "fa-brands fa-brave";
|
||||
case "Chrome":
|
||||
return "fa-brands fa-chrome";
|
||||
default:
|
||||
return ["fa-brands fa-chrome", "fa-brands fa-brave", "fa-brands fa-opera", "fa-brands fa-edge"];
|
||||
}
|
||||
}
|
||||
|
||||
let iconUpdateInterval: number | undefined;
|
||||
const iconIndex = ref<number>(0);
|
||||
|
||||
const currentIcon = computed(() => {
|
||||
if (!Array.isArray(getIcon(browser)))
|
||||
return getIcon(browser);
|
||||
|
||||
return getIcon(browser)[iconIndex.value];
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
if (typeof getIcon(browser) === "string")
|
||||
return;
|
||||
|
||||
iconIndex.value = 0;
|
||||
iconUpdateInterval = window.setInterval(() => {
|
||||
iconIndex.value = (iconIndex.value + 1) % getIcon(browser).length;
|
||||
if (iconIndex.value >= getIcon(browser).length) {
|
||||
iconIndex.value = 0;
|
||||
}
|
||||
}, 1000);
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
clearInterval(iconUpdateInterval);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ClientOnly>
|
||||
<VTooltip :disabled="!isWIP">
|
||||
<div class="flex items-center font-bold cursor-pointer transition-colors relative select-none bg-gray gap-2 px5 border-rounded w-50 h-20" :class="[highlight && !isWIP ? 'bg-primary hover:bg-primary-highlight c-black' : '', isWIP ? 'bg-op-60 cursor-not-allowed' : 'hover:bg-primary']" @click="!isWIP && emit('click')">
|
||||
<FAIcon
|
||||
class="h-auto mr-2 w-7"
|
||||
:icon="currentIcon"
|
||||
/>
|
||||
<span>
|
||||
{{ browser }}
|
||||
</span>
|
||||
<span v-if="isWIP" class="rounded-full absolute text-ellipsis overflow-hidden py-1 whitespace-nowrap bg-red-500 top--2 right--2 px-2 max-w-25 max-h-7">
|
||||
{{ $t("component.browserCard.wip") }}
|
||||
</span>
|
||||
</div>
|
||||
<template #popper>
|
||||
{{ $t("component.browserCard.support.safari") }}
|
||||
</template>
|
||||
</VTooltip>
|
||||
</ClientOnly>
|
||||
</template>
|
||||
@@ -1,70 +0,0 @@
|
||||
<script lang="ts" setup>
|
||||
import tinycolor from "tinycolor2";
|
||||
import type { ContributorsQuery } from "#gql";
|
||||
|
||||
type ContributorType = NonNullable<ContributorsQuery["credits"]>[number];
|
||||
|
||||
const { user } = defineProps<{ user: ContributorType }>();
|
||||
|
||||
const hovered = ref(false);
|
||||
|
||||
// eslint-disable-next-line one-var
|
||||
const cardGradientColor = computed(() => {
|
||||
return {
|
||||
primary: tinycolor(user?.user?.roleColor ?? "")
|
||||
.setAlpha(1)
|
||||
.darken(5)
|
||||
.toRgbString(),
|
||||
secondary: tinycolor(user?.user?.roleColor ?? "")
|
||||
.analogous()[2]
|
||||
.setAlpha(0.5)
|
||||
.saturate(20)
|
||||
.toRgbString(),
|
||||
};
|
||||
}),
|
||||
cardShadowColor = computed(() =>
|
||||
hovered.value
|
||||
? tinycolor(cardGradientColor.value.primary)
|
||||
.setAlpha(0.3)
|
||||
.saturate(20)
|
||||
.toRgbString()
|
||||
: "transparent",
|
||||
),
|
||||
computedBackground = computed(() => {
|
||||
return `background: linear-gradient(-35deg, ${cardGradientColor.value.secondary} 20%, ${cardGradientColor.value.primary} 130%); box-shadow: 0 2px 52px 0 ${cardShadowColor.value}`;
|
||||
});
|
||||
|
||||
const nonce = useNonce();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="flex items-center select-none py-1 justify-between duration-200 h-17 w-60 rd-2 px-3 transition-all hover:translate-y--1.5"
|
||||
:style="computedBackground"
|
||||
@mouseover="hovered = true"
|
||||
@mouseleave="hovered = false"
|
||||
>
|
||||
<div class="grid gap-1">
|
||||
<h1 class="text-ellipsis overflow-hidden whitespace-nowrap font-size-4.5 font-800">
|
||||
{{ user?.user?.name }}
|
||||
</h1>
|
||||
<p class="font-bold color-white:70 font-size-3.5">
|
||||
{{ user?.user?.role }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="relative ml2">
|
||||
<NuxtImg
|
||||
v-if="user?.user?.avatar"
|
||||
:nonce="nonce"
|
||||
:src="`${user?.user?.avatar}?size=40`"
|
||||
class="h-auto w-10 min-w-10 rd-100"
|
||||
draggable="false"
|
||||
:alt="`${user?.user?.name}'s avatar`"
|
||||
>
|
||||
<span
|
||||
class="rd-100 absolute block right-0 border-solid bg-green h-2.5 w-2.5 bottom-0 border-1 border-black"
|
||||
/>
|
||||
</nuxtimg>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user