Compare commits
180 Commits
main
...
api-master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bb56949dfb | ||
|
|
c06fe04b65 | ||
|
|
ef976341ba | ||
|
|
38893891af | ||
|
|
63eeeefda7 | ||
|
|
056db21cb0 | ||
|
|
d8dc08c6c3 | ||
|
|
634391b6e3 | ||
|
|
c46cf6975a | ||
|
|
68c6b4fcdc | ||
|
|
55fa07d5b5 | ||
|
|
903c238b33 | ||
|
|
acd9afb2b1 | ||
|
|
4bd42390eb | ||
|
|
c014504464 | ||
|
|
24fe349b60 | ||
|
|
ee5428ce08 | ||
|
|
e4b1010160 | ||
|
|
34c42d59ed | ||
|
|
d9267361aa | ||
|
|
0d5382fd50 | ||
|
|
e9015b1204 | ||
|
|
cea36426ab | ||
|
|
48c141094e | ||
|
|
e67fb97e14 | ||
|
|
0bd0d759f6 | ||
|
|
60b7f63409 | ||
|
|
78b482be4f | ||
|
|
9db9e931b6 | ||
|
|
665263e9b5 | ||
|
|
60257dbe53 | ||
|
|
411a70f567 | ||
|
|
4d1b092ee5 | ||
|
|
aa41f1cdae | ||
|
|
04b5d54697 | ||
|
|
fb096bc4be | ||
|
|
6e9e4ae1b6 | ||
|
|
d8f73202b9 | ||
|
|
b175a08dce | ||
|
|
2284ee94ad | ||
|
|
78a3311342 | ||
|
|
a1fabd3fd6 | ||
|
|
93c62cc38f | ||
|
|
8553613593 | ||
|
|
bf83dc4452 | ||
|
|
91bf2237c2 | ||
|
|
ae9b579e84 | ||
|
|
2488d98ede | ||
|
|
3eedb8ba81 | ||
|
|
bc5cc3054b | ||
|
|
5340b6ec2e | ||
|
|
0a28b2181b | ||
|
|
389ee87757 | ||
|
|
f3976f5aaf | ||
|
|
e85015725d | ||
|
|
a624b7a1cb | ||
|
|
6c85d66eab | ||
|
|
175f5ec430 | ||
|
|
18dc9fd594 | ||
|
|
6dd3c5ffcb | ||
|
|
dad3fbf44d | ||
|
|
c42fbfe8b0 | ||
|
|
3a30457944 | ||
|
|
2eae287e18 | ||
|
|
457882c515 | ||
|
|
224925c772 | ||
|
|
b5fca1c943 | ||
|
|
265a4ffffd | ||
|
|
ec5ff30ef3 | ||
|
|
947b3b91a9 | ||
|
|
71eefae4b4 | ||
|
|
6800649154 | ||
|
|
2100e4420b | ||
|
|
d4fc4c97ce | ||
|
|
ad658b1433 | ||
|
|
40c94fa8e5 | ||
|
|
902b1e4887 | ||
|
|
2e98a5a24e | ||
|
|
fbb9c815df | ||
|
|
0ed9f5b264 | ||
|
|
692fb2a8a5 | ||
|
|
151f7df388 | ||
|
|
9281ce0984 | ||
|
|
a82d435e22 | ||
|
|
6deda1ec8f | ||
|
|
258585efa0 | ||
|
|
2d1eaafbf9 | ||
|
|
5837c5be5b | ||
|
|
2106300635 | ||
|
|
82e7a260fb | ||
|
|
64f5cd6c12 | ||
|
|
8e56c12b29 | ||
|
|
febb0e1927 | ||
|
|
4ea97b6b42 | ||
|
|
8322b09221 | ||
|
|
854cb4145c | ||
|
|
c36f60d960 | ||
|
|
6bf1d58daa | ||
|
|
1c4cb32a6e | ||
|
|
009384a20d | ||
|
|
6e17a2d382 | ||
|
|
0e75dab8ff | ||
|
|
517119365e | ||
|
|
3e15ddf988 | ||
|
|
fb279a418a | ||
|
|
3e86393b25 | ||
|
|
14c476101b | ||
|
|
10cdf6ff47 | ||
|
|
975c354617 | ||
|
|
744a252469 | ||
|
|
e0305773c7 | ||
|
|
af25311e36 | ||
|
|
0877e706d2 | ||
|
|
ec516f2d02 | ||
|
|
311b1d96fa | ||
|
|
be181718e3 | ||
|
|
85ec19bda3 | ||
|
|
6314acbf81 | ||
|
|
c8136da505 | ||
|
|
3a41060d91 | ||
|
|
9e12a9f84f | ||
|
|
664e5c3e73 | ||
|
|
34bf4daa6a | ||
|
|
b2f4051e11 | ||
|
|
03cc674601 | ||
|
|
da3d007a35 | ||
|
|
80d9888b37 | ||
|
|
3ae265d6fe | ||
|
|
3c9e7708f8 | ||
|
|
7663eacb58 | ||
|
|
85d5fa14fa | ||
|
|
2b55d34c19 | ||
|
|
9d1c2167be | ||
|
|
ce52ce9a97 | ||
|
|
d73db7e5a9 | ||
|
|
98ce2ff939 | ||
|
|
f98d615e7b | ||
|
|
9c461c83ff | ||
|
|
dc8dacd5f5 | ||
|
|
db47ae9043 | ||
|
|
a0f4e141b5 | ||
|
|
5bc4c0e5c0 | ||
|
|
c4765b8eeb | ||
|
|
ebc953b549 | ||
|
|
b407003450 | ||
|
|
3857702040 | ||
|
|
e997e946a0 | ||
|
|
2bcb87ec9c | ||
|
|
1d5af93390 | ||
|
|
8a0e10eab0 | ||
|
|
13e413329c | ||
|
|
d0fac8c495 | ||
|
|
74525de586 | ||
|
|
115923b935 | ||
|
|
b7af6bb80e | ||
|
|
b053e6395c | ||
|
|
698ea34848 | ||
|
|
d689324e62 | ||
|
|
fee8133965 | ||
|
|
b93db93236 | ||
|
|
1efa4b9bb0 | ||
|
|
4cf00f5ca9 | ||
|
|
94303a9bca | ||
|
|
fa611923b4 | ||
|
|
c57d4db5a3 | ||
|
|
5d7760caa3 | ||
|
|
0d5fe8e5ab | ||
|
|
1ac552f3cd | ||
|
|
4cf4e01286 | ||
|
|
e96e2c0cb6 | ||
|
|
8fb93a09f9 | ||
|
|
4d20ba95b1 | ||
|
|
85f428a295 | ||
|
|
a3018f528d | ||
|
|
3d8431c4d5 | ||
|
|
074d55b6d4 | ||
|
|
d22d88b3a6 | ||
|
|
f55a83977b | ||
|
|
4ccc02f16c | ||
|
|
759b2abef9 |
1
.devcontainer/Dockerfile
Normal file
@@ -0,0 +1 @@
|
||||
FROM mcr.microsoft.com/devcontainers/base:bullseye
|
||||
24
.devcontainer/devcontainer.json
Normal file
@@ -0,0 +1,24 @@
|
||||
// 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"
|
||||
}
|
||||
32
.devcontainer/docker-compose.yml
Normal file
@@ -0,0 +1,32 @@
|
||||
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"
|
||||
11
.dockerignore
Normal file
@@ -0,0 +1,11 @@
|
||||
.vscode
|
||||
.DS_Store
|
||||
.Trashes
|
||||
.nuxt
|
||||
.output
|
||||
dist
|
||||
node_modules
|
||||
.env
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
generated
|
||||
13
.gitattributes
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
* text eol=lf
|
||||
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.jpeg binary
|
||||
*.gif binary
|
||||
*.ico binary
|
||||
*.mp4 binary
|
||||
*.mp3 binary
|
||||
*.gz binary
|
||||
*.zip binary
|
||||
*.ttf binary
|
||||
*.woff binary
|
||||
30
.github/CONTRIBUTING.md
vendored
@@ -1,30 +0,0 @@
|
||||
# Contributing
|
||||
|
||||
## Requiered knowledge
|
||||
|
||||
- JavaScript
|
||||
- html5
|
||||
- NodeJS
|
||||
|
||||
Additional:
|
||||
|
||||
- CSS
|
||||
- [VueJS](https://vuejs.org/)
|
||||
- [ElectronJS](https://electronjs.org/)
|
||||
- [NPMjs](https://www.npmjs.com/)
|
||||
|
||||
A source code editor is also requiered. We recommend [Visual Studio Code](https://code.visualstudio.com/).
|
||||
|
||||
### Installing the components
|
||||
|
||||
1. Install [Git](https://git-scm.com/)
|
||||
2. Install [Node](https://nodejs.org/en/)
|
||||
|
||||
### Cloning the project
|
||||
|
||||
1. Fork the [repository](https://github.com/PreMiD/PreMiD)
|
||||
2. Open a terminal and type `git clone https://github.com/PreMiD/PreMiD`
|
||||
|
||||
### Coding your vision
|
||||
|
||||
Please keep the structure. We don't want to disorganize our project. Chaotic files may not be accepted.
|
||||
BIN
.github/Electron/Chrome_bsp.png
vendored
|
Before Width: | Height: | Size: 332 KiB |
BIN
.github/Electron/PMD_Banner.png
vendored
|
Before Width: | Height: | Size: 682 KiB |
2
.github/FUNDING.yml
vendored
@@ -1,3 +1,3 @@
|
||||
github: Timeraa
|
||||
github: [PreMiD, Timeraa]
|
||||
patreon: Timeraa
|
||||
ko_fi: Timeraa
|
||||
|
||||
31
.github/ISSUE_TEMPLATE/bug_report.md
vendored
@@ -1,31 +0,0 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
---
|
||||
|
||||
<!-- NOTE -->
|
||||
<!-- Keep all presence related bugs in our Presences repository! -->
|
||||
<!-- https://github.com/PreMiD/Presences/issues -->
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
1.
|
||||
2.
|
||||
3.
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Screenshots**
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**Desktop (please complete the following information):**
|
||||
- OS: [e.g. iOS]
|
||||
- Browser [e.g. chrome, safari]
|
||||
- Version [e.g. 22]
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here.
|
||||
16
.github/ISSUE_TEMPLATE/feature_request.md
vendored
@@ -1,16 +0,0 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for PreMiD
|
||||
---
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
BIN
.github/Logo.png
vendored
|
Before Width: | Height: | Size: 11 KiB |
BIN
.github/Patreon.png
vendored
|
Before Width: | Height: | Size: 3.0 KiB |
1
.github/PayPal.svg
vendored
|
Before Width: | Height: | Size: 5.1 KiB |
13
.github/SUPPORT.md
vendored
@@ -1,13 +0,0 @@
|
||||
# How to get support
|
||||
|
||||
## Take a look at the [wiki](https://wiki.premid.app)
|
||||
Our GitHub wiki is full of information around PreMiD.<br>
|
||||
Take a look and feel free to contribute if you want to add something new.
|
||||
|
||||
## [Open a issue](https://github.com/PreMiD/PreMiD/issues/new/choose) on [GitHub](https://github.com/PreMiD/PreMiD)
|
||||
Simply open a issue if you don't feel allright.<br>
|
||||
*Aand there he goes...*
|
||||
|
||||
## Ask a staff member in [#support](https://discord.premid.app)
|
||||
The team is ready to tell you the secrets of the underworld.<br>
|
||||
Join our [Discord server](https://discord.premid.app) and find out what we're hiding.
|
||||
BIN
.github/TwitterButton.png
vendored
|
Before Width: | Height: | Size: 4.1 KiB |
36
.github/actions/build-and-push-docker/action.yaml
vendored
Normal file
@@ -0,0 +1,36 @@
|
||||
name: Build and Push Docker Image
|
||||
description: Builds a Docker image and pushes it to GitHub Container Registry
|
||||
inputs:
|
||||
app:
|
||||
description: Name of the app
|
||||
required: true
|
||||
token:
|
||||
description: GitHub token
|
||||
required: true
|
||||
outputs:
|
||||
version:
|
||||
description: Version of the app
|
||||
value: ${{ steps.get_version.outputs.version }}
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Get package.json version
|
||||
id: get_version
|
||||
run: echo ::set-output name=version::$(node -p "require('./apps/${{ inputs.app }}/package.json').version")
|
||||
shell: bash
|
||||
|
||||
- name: Convert repository owner to lowercase
|
||||
id: repo
|
||||
run: echo "::set-output name=lowercase::$(echo ${{ github.repository_owner }} | awk '{print tolower($0)}')"
|
||||
shell: bash
|
||||
|
||||
- name: Build and Push Docker Image
|
||||
uses: premid/premid/.github/actions/build-docker@monorepo
|
||||
with:
|
||||
dockerfile: ./apps/${{ inputs.app }}/Dockerfile
|
||||
push: true
|
||||
token: ${{ inputs.token }}
|
||||
tags: ghcr.io/${{ steps.repo.outputs.lowercase }}/${{ inputs.app }}:${{ steps.get_version.outputs.version }},ghcr.io/${{ steps.repo.outputs.lowercase }}/${{ inputs.app }}:latest
|
||||
46
.github/actions/build-docker/action.yaml
vendored
Normal file
@@ -0,0 +1,46 @@
|
||||
name: Build Docker Image
|
||||
description: Builds a Docker image using Docker Buildx
|
||||
inputs:
|
||||
dockerfile:
|
||||
description: Path to the Dockerfile
|
||||
required: true
|
||||
tags:
|
||||
description: Comma-separated list of tags for the Docker image
|
||||
required: true
|
||||
push:
|
||||
description: Whether to push the Docker image to the registry
|
||||
required: false
|
||||
default: "false"
|
||||
token:
|
||||
description: GitHub Token
|
||||
required: false
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Setup Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
if: ${{ inputs.push == 'true' }}
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ inputs.token }}
|
||||
|
||||
- name: Build Docker Image
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
file: ${{ inputs.dockerfile }}
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: ${{ inputs.push }}
|
||||
tags: ${{ inputs.tags }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
20
.github/dependabot.yml
vendored
@@ -1,20 +0,0 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "npm"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
commit-message:
|
||||
prefix: chore
|
||||
include: scope
|
||||
labels:
|
||||
- "dependencies"
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
commit-message:
|
||||
prefix: chore
|
||||
include: scope
|
||||
labels:
|
||||
- "dependencies"
|
||||
BIN
.github/example.png
vendored
|
Before Width: | Height: | Size: 332 KiB |
5
.github/renovate.json
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||
"extends": ["github>Recodive/Recodive:renovate-config"],
|
||||
"automerge": false
|
||||
}
|
||||
68
.github/workflows/cd.yaml
vendored
Normal file
@@ -0,0 +1,68 @@
|
||||
name: CD
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- monorepo
|
||||
tags:
|
||||
- "*"
|
||||
permissions:
|
||||
packages: write
|
||||
jobs:
|
||||
build:
|
||||
name: Build Docker Images
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
target:
|
||||
- pd
|
||||
- schema-server
|
||||
- website
|
||||
- api-worker
|
||||
- api-master
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Build and Push website
|
||||
uses: docker/build-push-action@v6
|
||||
if: matrix.target == 'website'
|
||||
with:
|
||||
push: true
|
||||
platforms: linux/amd64,linux/arm64
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
build-args: SERVICE=${{ matrix.target }}
|
||||
target: website
|
||||
tags: ghcr.io/premid/${{ matrix.target }}:beta-${{ github.sha }}-${{ github.run_number }}
|
||||
|
||||
- name: Get package.json version
|
||||
if: matrix.target != 'website'
|
||||
id: get_version
|
||||
run: echo ::set-output name=version::$(node -p "require('./apps/${{ matrix.target }}/package.json').version")
|
||||
shell: bash
|
||||
|
||||
- name: Build and push other images
|
||||
uses: docker/build-push-action@v6
|
||||
if: matrix.target != 'website' && startsWith(github.ref, 'refs/tags/')
|
||||
with:
|
||||
push: true
|
||||
platforms: linux/amd64,linux/arm64
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
target: prod
|
||||
build-args: SERVICE=${{ matrix.target }}
|
||||
tags: ghcr.io/premid/${{ matrix.target }}:latest,ghcr.io/premid/${{ matrix.target }}:${{ steps.get_version.outputs.version }}
|
||||
71
.github/workflows/ci.yaml
vendored
Normal file
@@ -0,0 +1,71 @@
|
||||
name: Build, Lint and Test
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- monorepo
|
||||
pull_request:
|
||||
jobs:
|
||||
build:
|
||||
name: Build, Lint and Test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v3
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
cache: pnpm
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install Dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Codegen
|
||||
run: pnpm -r codegen
|
||||
|
||||
- name: Lint
|
||||
run: pnpm run lint
|
||||
|
||||
- name: Build
|
||||
run: pnpm run build
|
||||
|
||||
- name: Test
|
||||
run: pnpm test
|
||||
|
||||
build-docker:
|
||||
name: Build Docker Images
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
target:
|
||||
- pd
|
||||
- schema-server
|
||||
- api-worker
|
||||
- api-master
|
||||
- website
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Get Target
|
||||
id: get_target
|
||||
run: echo "target=$([[ ${{ matrix.target }} == 'website' ]] && echo 'website' || echo 'prod')" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Build
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
target: ${{ steps.get_target.outputs.target }}
|
||||
build-args: SERVICE=${{ matrix.target }}
|
||||
98
.github/workflows/deploy.yml
vendored
@@ -1,98 +0,0 @@
|
||||
name: DePloY
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
env:
|
||||
NODE_ENV: DePloY
|
||||
jobs:
|
||||
package:
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [macOS-latest, windows-latest]
|
||||
steps:
|
||||
- uses: actions/checkout@master
|
||||
- uses: actions/setup-node@master
|
||||
- name: Install Dependencies
|
||||
run: |
|
||||
npm i
|
||||
npm i -g typescript rimraf
|
||||
- name: Prepare to package
|
||||
run: npm run init
|
||||
- name: Package
|
||||
run: |
|
||||
npm run pkg
|
||||
rimraf dist/app
|
||||
node util/zip dist ${{ matrix.os }}.zip --zip
|
||||
- name: Upload bundle
|
||||
env:
|
||||
SSHHOST: ${{ secrets.MAIN_HOST }}
|
||||
SSH_USERNAME: ${{ secrets.SSH_USERNAME }}
|
||||
SSH_KEY: ${{ secrets.SSH_KEY }}
|
||||
run: |
|
||||
tsc util/uploadFile util/zip
|
||||
node util/uploadFile ${{ matrix.os }}.zip /home/PreMiD/download/util/${{ matrix.os }}.zip
|
||||
createInstallers:
|
||||
runs-on: "ubuntu-latest"
|
||||
needs: package
|
||||
steps:
|
||||
- uses: actions/checkout@master
|
||||
- uses: actions/setup-node@master
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
sudo npm i
|
||||
sudo npm i -g typescript
|
||||
- name: Download InstallBuilder
|
||||
run: |
|
||||
wget https://clients.bitrock.com/installbuilder/installbuilder-enterprise-20.12.0-linux-x64-installer.run
|
||||
chmod u+x installbuilder-enterprise-20.12.0-linux-x64-installer.run
|
||||
- name: Install InstallBuilder
|
||||
run: |
|
||||
./installbuilder-enterprise-20.12.0-linux-x64-installer.run --installer-language en --prefix ./installbuilder --mode unattended
|
||||
echo "${{ secrets.IBLICENSE }}" > ./installbuilder/license.xml
|
||||
- name: Prepare Upgrade Installer
|
||||
run: |
|
||||
tsc util/prepare
|
||||
node util/prepare
|
||||
- name: Create Upgrade Installer (MacOS 64bit)
|
||||
run: |
|
||||
installbuilder/bin/builder build installer_assets/PreMiD-Upgrade.xml osx
|
||||
- name: Create Upgrade Installer (Windows)
|
||||
run: |
|
||||
installbuilder/bin/builder build installer_assets/PreMiD-Upgrade.xml windows
|
||||
- name: Upload files
|
||||
env:
|
||||
SSHHOST: ${{ secrets.MAIN_HOST }}
|
||||
SSH_USERNAME: ${{ secrets.SSH_USERNAME }}
|
||||
SSH_KEY: ${{ secrets.SSH_KEY }}
|
||||
run: |
|
||||
tsc util/uploadFile util/zip
|
||||
node util/uploadFile dist/installer/upgrader.exe /home/PreMiD/download/upgrader.exe
|
||||
node util/uploadFile dist/installer/upgrader.app.zip /home/PreMiD/download/util/upgrader.app.zip
|
||||
- name: Finalize build
|
||||
uses: appleboy/ssh-action@master
|
||||
with:
|
||||
host: ${{ secrets.MAIN_HOST }}
|
||||
username: ${{ secrets.SSH_USERNAME }}
|
||||
key: ${{ secrets.SSH_KEY }}
|
||||
script: |
|
||||
cd /home/PreMiD/download/util
|
||||
unzip upgrader.app.zip
|
||||
tar -czvf upgrader.app.tgz upgrader.app
|
||||
mv upgrader.app.tgz ../
|
||||
rm -rf upgrader.app upgrader.app.zip
|
||||
unzip windows-latest.zip
|
||||
cd windows-latest/PreMiD-win32-x64/
|
||||
zip -r ../../PreMiD-win32-x64.zip .
|
||||
mv ../../PreMiD-win32-x64.zip /home/PreMiD/download/
|
||||
cd ../PreMiD-win32-ia32/
|
||||
zip -r ../../PreMiD-win32-x86.zip .
|
||||
mv ../../PreMiD-win32-x86.zip /home/PreMiD/download/
|
||||
cd ../..
|
||||
rm -rf windows-latest windows-latest.zip
|
||||
unzip macOS-latest.zip
|
||||
cd macOS-latest/PreMiD-darwin-x64/
|
||||
zip -r ../../PreMiD-darwin-x64.zip .
|
||||
mv ../../PreMiD-darwin-x64.zip /home/PreMiD/download/
|
||||
cd ../..
|
||||
rm -rf macOS-latest macOS-latest.zip
|
||||
5
.gitignore
vendored
@@ -2,6 +2,7 @@ node_modules
|
||||
out
|
||||
dist
|
||||
tmp
|
||||
lib
|
||||
|
||||
.vscode
|
||||
.env
|
||||
@@ -18,3 +19,7 @@ src/update.ini
|
||||
*.app
|
||||
*.xml.backup
|
||||
*.js
|
||||
!eslint.config.js
|
||||
|
||||
coverage
|
||||
*.tsbuildinfo
|
||||
2
.husky/commit-msg
Normal file
@@ -0,0 +1,2 @@
|
||||
#!/bin/sh
|
||||
pnpm exec commitlint --edit $1
|
||||
2
.prettierignore
Normal file
@@ -0,0 +1,2 @@
|
||||
*.js
|
||||
*.ts
|
||||
22
@types/PreMiD/ExtensionSettings.d.ts
vendored
@@ -1,22 +0,0 @@
|
||||
export default interface ExtensionSettings {
|
||||
/**
|
||||
* If extension is enabled
|
||||
*/
|
||||
enabled: boolean;
|
||||
/**
|
||||
* Autolaunch enabled
|
||||
*/
|
||||
autoLaunch: boolean;
|
||||
/**
|
||||
* Media keys enabled
|
||||
*/
|
||||
mediaKeys: boolean;
|
||||
/**
|
||||
* title menubar (TrayTitle)
|
||||
*/
|
||||
titleMenubar: boolean;
|
||||
/**
|
||||
* language of extension
|
||||
*/
|
||||
language: string;
|
||||
}
|
||||
16
@types/PreMiD/Presence.d.ts
vendored
@@ -1,16 +0,0 @@
|
||||
import * as Discord from "discord-rpc";
|
||||
|
||||
export default interface Presence {
|
||||
/**
|
||||
* Client ID of presence
|
||||
*/
|
||||
clientId: string;
|
||||
/**
|
||||
* Rich Procedual call connection
|
||||
*/
|
||||
rpc: Discord.Client;
|
||||
/**
|
||||
* Connection ready?
|
||||
*/
|
||||
ready: Boolean;
|
||||
}
|
||||
33
@types/PreMiD/PresenceData.d.ts
vendored
@@ -1,33 +0,0 @@
|
||||
import * as Discord from "discord-rpc";
|
||||
|
||||
export default interface PresenceData {
|
||||
/**
|
||||
* Client ID of presence
|
||||
*/
|
||||
clientId: string;
|
||||
/**
|
||||
* Tray title to be shown in Mac OS tray
|
||||
*/
|
||||
trayTitle: string;
|
||||
/**
|
||||
* service name of presence
|
||||
* @deprecated
|
||||
*/
|
||||
service: string;
|
||||
/**
|
||||
* Determines if the service is currently playing something back or not, if false it will automatically hide after 1 minute
|
||||
*/
|
||||
playback: boolean;
|
||||
/**
|
||||
* Discord Presence which gets sent directly to Discord app
|
||||
*/
|
||||
presenceData: Discord.Presence;
|
||||
/**
|
||||
* Determines if the service should be hidden (clearActivity)
|
||||
*/
|
||||
hidden: boolean;
|
||||
/**
|
||||
* Determines if the service is mediaKey able / uses them
|
||||
*/
|
||||
mediaKeys: boolean;
|
||||
}
|
||||
@@ -1 +1 @@
|
||||
* @Timeraa
|
||||
* @Timeraa
|
||||
@@ -2,65 +2,38 @@
|
||||
|
||||
## Our Pledge
|
||||
|
||||
In the interest of fostering an open and welcoming environment, we as
|
||||
contributors and maintainers pledge to making participation in our project and
|
||||
our community a harassment-free experience for everyone, regardless of age, body
|
||||
size, disability, ethnicity, sex characteristics, gender identity and expression,
|
||||
level of experience, education, socio-economic status, nationality, personal
|
||||
appearance, race, religion, or sexual identity and orientation.
|
||||
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to creating a positive environment
|
||||
include:
|
||||
Examples of behavior that contributes to creating a positive environment include:
|
||||
|
||||
* Using welcoming and inclusive language
|
||||
* Being respectful of differing viewpoints and experiences
|
||||
* Gracefully accepting constructive criticism
|
||||
* Focusing on what is best for the community
|
||||
* Showing empathy towards other community members
|
||||
- Using welcoming and inclusive language
|
||||
- Being respectful of differing viewpoints and experiences
|
||||
- Gracefully accepting constructive criticism
|
||||
- Focusing on what is best for the community
|
||||
- Showing empathy towards other community members
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
* The use of sexualized language or imagery and unwelcome sexual attention or
|
||||
advances
|
||||
* Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or electronic
|
||||
address, without explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
- The use of sexualized language or imagery and unwelcome sexual attention or advances
|
||||
- Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
- Public or private harassment
|
||||
- Publishing others' private information, such as a physical or electronic address, without explicit permission
|
||||
- Other conduct which could reasonably be considered inappropriate in a professional setting
|
||||
|
||||
## Our Responsibilities
|
||||
|
||||
Project maintainers are responsible for clarifying the standards of acceptable
|
||||
behavior and are expected to take appropriate and fair corrective action in
|
||||
response to any instances of unacceptable behavior.
|
||||
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or
|
||||
reject comments, commits, code, wiki edits, issues, and other contributions
|
||||
that are not aligned to this Code of Conduct, or to ban temporarily or
|
||||
permanently any contributor for other behaviors that they deem inappropriate,
|
||||
threatening, offensive, or harmful.
|
||||
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies both within project spaces and in public spaces
|
||||
when an individual is representing the project or its community. Examples of
|
||||
representing a project or community include using an official project e-mail
|
||||
address, posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event. Representation of a project may be
|
||||
further defined and clarified by project maintainers.
|
||||
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported by contacting the project team at contact@premid.app or by contacting a staff member on our [Discord server](https://discord.premid.app). All
|
||||
complaints will be reviewed and investigated and will result in a response that
|
||||
is deemed necessary and appropriate to the circumstances. The project team is
|
||||
obligated to maintain confidentiality with regard to the reporter of an incident.
|
||||
Further details of specific enforcement policies may be posted separately.
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at contact@premid.app or by contacting a staff member on our [Discord server](https://discord.premid.app). All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
|
||||
|
||||
Project maintainers who do not follow or enforce the Code of Conduct in good
|
||||
faith may face temporary or permanent repercussions as determined by other
|
||||
members of the project's leadership.
|
||||
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
|
||||
|
||||
36
Dockerfile
Normal file
@@ -0,0 +1,36 @@
|
||||
FROM gplane/pnpm:node20-alpine AS base
|
||||
RUN corepack enable
|
||||
ARG SERVICE
|
||||
|
||||
FROM base AS build
|
||||
WORKDIR /app
|
||||
|
||||
COPY . /app
|
||||
|
||||
RUN pnpm i --frozen-lockfile
|
||||
|
||||
RUN if [ "$SERVICE" != "website" ]; then pnpm run -r codegen; fi
|
||||
RUN if [ "$SERVICE" != "website" ]; then pnpm run build; fi
|
||||
RUN if [ "$SERVICE" == "website" ]; then pnpm --filter @premid/website run build; fi
|
||||
RUN if [ "$SERVICE" != "website" ]; then pnpm --filter @premid/${SERVICE} deploy --prod /prod/${SERVICE}; fi
|
||||
|
||||
FROM node:20-alpine AS prod
|
||||
ARG SERVICE
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --from=build /prod/${SERVICE} ./
|
||||
ENV PORT=80
|
||||
EXPOSE 80
|
||||
|
||||
CMD ["npm", "start"]
|
||||
|
||||
FROM node:20-alpine AS website
|
||||
WORKDIR /app
|
||||
ENV PORT=80
|
||||
|
||||
COPY --from=build /app/apps/website/.output /app
|
||||
|
||||
EXPOSE 80
|
||||
|
||||
CMD ["node", "server/index.mjs"]
|
||||
68
README.md
@@ -1,46 +1,54 @@
|
||||
<div align="center">
|
||||
|
||||
<img src=".github/Logo.png" width="150px" draggable="false"><br>
|
||||
<img src="https://cdn.rcd.gg/PreMiD.png" width="150px" />
|
||||
|
||||
# PreMiD
|
||||
|
||||
## Your Rich Presence for web services!
|
||||
[](https://vscode.dev/redirect?url=vscode://ms-vscode-remote.remote-containers/cloneInVolume?url=https://github.com/PreMiD/PreMiD)
|
||||
[](https://crowdin.com/project/premid)
|
||||
|
||||

|
||||

|
||||

|
||||
[](https://chrome.google.com/webstore/detail/premid/agjnjboanicjcpenljmaaigopkgdnihi)
|
||||

|
||||
[](https://app.fossa.io/projects/git%2Bgithub.com%2FPreMiD%2FPreMiD?ref=badge_shield)
|
||||
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.
|
||||
|
||||
<img src=".github/example.png" draggable="false"><br>
|
||||
## Getting Started
|
||||
|
||||
# About
|
||||
**If you are a user looking to install PreMiD, please visit the [official website](https://premid.app).**
|
||||
|
||||
**PreMiD** is a simple, configurable utility that allows you to show what you're doing on the web in your Discord **now playing status**. It supports many different websites, and will support multiple users watching the same content simultaneously in an upcoming update.
|
||||
If you are a developer looking to contribute to PreMiD, read along.
|
||||
|
||||
# Features
|
||||
## Table of Contents
|
||||
|
||||
· Displays your current web service in Discord as your status.<br>
|
||||
· Grants full control over Presences.<br>
|
||||
· Supports over 1,000 web services, still rising!<br>
|
||||
· _Watch parties and more are coming soon!_
|
||||
- [Packages](#packages)
|
||||
- [License](#license)
|
||||
|
||||
# Installation/Troubleshooting
|
||||
## Packages
|
||||
|
||||
### Installation instructions, Troubleshooting guides etc. can be located at our [**docs**](https://docs.premid.app).
|
||||
This monorepo is split into multiple packages / projects. Here's a list of them:
|
||||
|
||||
# Support us
|
||||
- [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.
|
||||
|
||||
<div>
|
||||
<a target="_blank" href="https://www.patreon.com/bePatron?u=4610890" data-patreon-widget-type="become-patron-button" title="Support me on Patreon!">
|
||||
<img height="75px" draggable="false" src=".github/Patreon.png">
|
||||
</a>
|
||||
<a target="_blank" href="https://discord.premid.app/" title="Join our Discord!">
|
||||
<img src="https://discordapp.com/api/guilds/493130730549805057/widget.png?style=banner2" height="76px" draggable="false" alt="Join our Discord!">
|
||||
</a>
|
||||
</div>
|
||||
## Development
|
||||
|
||||
### Release
|
||||
|
||||
To release a new version of a package, run the following command:
|
||||
|
||||
```bash
|
||||
cd apps/<app>
|
||||
pnpm bumpp -y -t <app>-v
|
||||
```
|
||||
|
||||
Replace `<app>` with the name of the package you want to release. For example, to release a new version of the `schema-server` package, you would run:
|
||||
|
||||
```bash
|
||||
cd apps/schema-server
|
||||
pnpm bumpp -y -t schema-server-v
|
||||
```
|
||||
|
||||
This will use bumpp to bump the version of the package in the `package.json` file, create a tag for the new version, and push the changes to the remote repository.
|
||||
|
||||
## License
|
||||
|
||||
[](https://app.fossa.io/projects/git%2Bgithub.com%2FPreMiD%2FPreMiD?ref=badge_large)
|
||||
This project is licensed under the [MPL-2.0 License](LICENSE).
|
||||
|
||||
31
apps/api-master/package.json
Normal file
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"name": "@premid/api-master",
|
||||
"type": "module",
|
||||
"version": "0.0.18",
|
||||
"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 ."
|
||||
},
|
||||
"dependencies": {
|
||||
"@discordjs/rest": "^2.3.0",
|
||||
"@envelop/sentry": "^9.0.0",
|
||||
"@opentelemetry/api": "^1.9.0",
|
||||
"@opentelemetry/exporter-prometheus": "^0.52.1",
|
||||
"@opentelemetry/node": "^0.24.0",
|
||||
"@sentry/node": "^8.17.0",
|
||||
"cron": "^3.1.7",
|
||||
"debug": "^4.3.6",
|
||||
"ioredis": "^5.3.2",
|
||||
"p-limit": "^6.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/debug": "^4.1.12"
|
||||
}
|
||||
}
|
||||
117
apps/api-master/src/functions/clearOldSessions.ts
Normal file
@@ -0,0 +1,117 @@
|
||||
import { REST } from "@discordjs/rest";
|
||||
import pLimit from "p-limit";
|
||||
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();
|
||||
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 [nextCursor, result] = await redis.hscan("pmd-api.sessions", cursor, "COUNT", batchSize);
|
||||
cursor = nextCursor;
|
||||
totalSessions += result.length / 2;
|
||||
|
||||
const deletePromises = [];
|
||||
|
||||
for (let i = 0; i < result.length; i += 2) {
|
||||
const key = result[i];
|
||||
const value = result[i + 1];
|
||||
|
||||
if (!key || !value) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const session = JSON.parse(value) 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.hdel("pmd-api.sessions", ...keysToDelete);
|
||||
keysToDelete = [];
|
||||
}
|
||||
} while (cursor !== "0");
|
||||
|
||||
if (keysToDelete.length > 0) {
|
||||
await redis.hdel("pmd-api.sessions", ...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> {
|
||||
const abortController = new AbortController();
|
||||
const timeoutId = setTimeout(() => abortController.abort(), 5000); //* 5 second timeout
|
||||
|
||||
try {
|
||||
const discord = new REST({ version: "10", authPrefix: "Bearer" });
|
||||
discord.setToken(session.token);
|
||||
|
||||
await discord.post("/users/@me/headless-sessions/delete", {
|
||||
signal: abortController.signal,
|
||||
body: {
|
||||
token: session.session,
|
||||
},
|
||||
});
|
||||
|
||||
clearTimeout(timeoutId);
|
||||
return key;
|
||||
}
|
||||
catch (error) {
|
||||
clearTimeout(timeoutId);
|
||||
//* Log detailed error information
|
||||
mainLog(`Delete session error for key ${key}:`, {
|
||||
errorName: error instanceof Error ? error.name : "Unknown",
|
||||
errorMessage: error instanceof Error ? error.message : String(error),
|
||||
errorStack: error instanceof Error ? error.stack : "No stack trace",
|
||||
});
|
||||
|
||||
if (error instanceof Error && error.name === "AbortError") {
|
||||
mainLog(`Session deletion aborted due to timeout for key ${key}`);
|
||||
}
|
||||
else if (error instanceof Error) {
|
||||
mainLog(`Failed to delete session for key ${key}: ${error.message}`);
|
||||
}
|
||||
else {
|
||||
mainLog(`Failed to delete session for key ${key}: Unknown error`);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
}
|
||||
30
apps/api-master/src/functions/createRedis.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
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;
|
||||
}
|
||||
13
apps/api-master/src/functions/setCounter.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { redis } from "../index.js";
|
||||
import { counter } from "../tracing.js";
|
||||
|
||||
let activeActivities = 0;
|
||||
counter.add(0);
|
||||
export async function setCounter() {
|
||||
const length = await redis.hlen("pmd-api.sessions");
|
||||
if (length === activeActivities)
|
||||
return;
|
||||
const diff = length - activeActivities;
|
||||
activeActivities = length;
|
||||
counter.add(diff);
|
||||
}
|
||||
33
apps/api-master/src/index.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { CronJob } from "cron";
|
||||
|
||||
import debug from "debug";
|
||||
import { clearOldSessions } from "./functions/clearOldSessions.js";
|
||||
import createRedis from "./functions/createRedis.js";
|
||||
import { setCounter } from "./functions/setCounter.js";
|
||||
import "./tracing.js";
|
||||
|
||||
export const redis = createRedis();
|
||||
|
||||
export const mainLog = debug("api-master");
|
||||
|
||||
debug("Starting cron job to clear old sessions");
|
||||
|
||||
void new CronJob(
|
||||
// Every 5 seconds
|
||||
"*/5 * * * * *",
|
||||
() => {
|
||||
clearOldSessions();
|
||||
},
|
||||
undefined,
|
||||
true,
|
||||
);
|
||||
|
||||
void new CronJob(
|
||||
// Every second
|
||||
"* * * * * *",
|
||||
() => {
|
||||
setCounter();
|
||||
},
|
||||
undefined,
|
||||
true,
|
||||
);
|
||||
18
apps/api-master/src/tracing.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
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();
|
||||
9
apps/api-master/tsconfig.app.json
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"rootDir": "src",
|
||||
"outDir": "dist"
|
||||
},
|
||||
"include": ["src/**/*"]
|
||||
}
|
||||
8
apps/api-master/tsconfig.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "./tsconfig.app.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": ".",
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["environment.d.ts", "src", "codegen.ts"]
|
||||
}
|
||||
1
apps/api-worker/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
generated
|
||||
26
apps/api-worker/codegen.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
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;
|
||||
7
apps/api-worker/environment.d.ts
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
declare namespace NodeJS {
|
||||
export interface ProcessEnv {
|
||||
NODE_ENV?: "development" | "production" | "test";
|
||||
DATABASE_URL?: string;
|
||||
SESSION_KEEP_ALIVE_INTERVAL?: string;
|
||||
}
|
||||
}
|
||||
49
apps/api-worker/package.json
Normal file
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"name": "@premid/api-worker",
|
||||
"type": "module",
|
||||
"version": "0.0.8",
|
||||
"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.5.1"
|
||||
},
|
||||
"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"
|
||||
}
|
||||
}
|
||||
110
apps/api-worker/src/classes/Socket.ts
Normal file
@@ -0,0 +1,110 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
30
apps/api-worker/src/functions/createRedis.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
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;
|
||||
}
|
||||
25
apps/api-worker/src/functions/createServer.test.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
106
apps/api-worker/src/functions/createServer.ts
Normal file
@@ -0,0 +1,106 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import process from "node:process";
|
||||
import { useSentry } from "@envelop/sentry";
|
||||
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 { defu } from "defu";
|
||||
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 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) => {
|
||||
const disabledFlags = process.env.DISABLED_FEATURE_FLAGS?.split(",") ?? [];
|
||||
const flags = Object.fromEntries(disabledFlags.map(flag => [flag, false]));
|
||||
|
||||
const test = defu(flags, {
|
||||
WebSocketManager: true,
|
||||
SessionKeepAlive: true,
|
||||
});
|
||||
|
||||
void reply.send(test);
|
||||
});
|
||||
|
||||
app.post("/v5/session-keep-alive", sessionKeepAlive);
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
export const redis = createRedis();
|
||||
@@ -0,0 +1,32 @@
|
||||
import { type } from "arktype";
|
||||
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 Error(out.summary);
|
||||
|
||||
await redis.hset(
|
||||
"pmd-api.scienceUpdates",
|
||||
out.identifier,
|
||||
JSON.stringify(out),
|
||||
);
|
||||
|
||||
return {
|
||||
__typename: "AddScienceResult",
|
||||
...out,
|
||||
};
|
||||
};
|
||||
|
||||
export default mutation;
|
||||
@@ -0,0 +1,42 @@
|
||||
import { type } from "arktype";
|
||||
import type { MutationResolvers } from "../../../../generated/graphql-v5.js";
|
||||
|
||||
const heartbeatSchema = type({
|
||||
identifier: "string.uuid & string.lower",
|
||||
presences: {
|
||||
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) => {
|
||||
const out = heartbeatSchema(input);
|
||||
|
||||
if (out instanceof type.errors)
|
||||
throw new Error(out.summary);
|
||||
|
||||
// ! Disabled for now
|
||||
/* await redis.setex(
|
||||
`pmd-api.heartbeatUpdates.${data.identifier}`,
|
||||
// 5 minutes
|
||||
300,
|
||||
JSON.stringify(data)
|
||||
); */
|
||||
|
||||
return {
|
||||
__typename: "HeartbeatResult",
|
||||
...out,
|
||||
};
|
||||
};
|
||||
|
||||
export default mutation;
|
||||
@@ -0,0 +1,8 @@
|
||||
import type { MutationResolvers } from "../../../../generated/graphql-v5.js";
|
||||
import addScience from "./addScience.js";
|
||||
import heartbeat from "./heartbeat.js";
|
||||
|
||||
export const Mutation: MutationResolvers = {
|
||||
addScience,
|
||||
heartbeat,
|
||||
};
|
||||
6
apps/api-worker/src/graphql/resolvers/v5/Query/index.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import type { QueryResolvers } from "../../../../generated/graphql-v5.js";
|
||||
import presences from "./presences.js";
|
||||
|
||||
export const Query: QueryResolvers = {
|
||||
presences,
|
||||
};
|
||||
58
apps/api-worker/src/graphql/resolvers/v5/Query/presences.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
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;
|
||||
8
apps/api-worker/src/graphql/resolvers/v5/index.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
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,
|
||||
};
|
||||
19
apps/api-worker/src/graphql/schema/v5/addScience.gql
Normal file
@@ -0,0 +1,19 @@
|
||||
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!
|
||||
}
|
||||
21
apps/api-worker/src/graphql/schema/v5/availableLanguages.gql
Normal file
@@ -0,0 +1,21 @@
|
||||
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!
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
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!]!
|
||||
}
|
||||
49
apps/api-worker/src/graphql/schema/v5/heartbeat.gql
Normal file
@@ -0,0 +1,49 @@
|
||||
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!
|
||||
}
|
||||
62
apps/api-worker/src/graphql/schema/v5/presences.gql
Normal file
@@ -0,0 +1,62 @@
|
||||
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 {
|
||||
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: PresenceMetadataSettingsIf # serialize
|
||||
placeholder: String
|
||||
value: Scalar # serialize
|
||||
values: Scalar # serialize
|
||||
multiLanguage: Scalar # serialize
|
||||
}
|
||||
|
||||
type PresenceMetadataSettingsIf {
|
||||
propertyNames: String
|
||||
patternProperties: Scalar
|
||||
}
|
||||
1
apps/api-worker/src/graphql/schema/v5/scalar/Scalar.gql
Normal file
@@ -0,0 +1 @@
|
||||
scalar Scalar
|
||||
@@ -0,0 +1 @@
|
||||
scalar StringOrStringArray
|
||||
29
apps/api-worker/src/index.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable no-console */
|
||||
import process from "node:process";
|
||||
import * as Sentry from "@sentry/node";
|
||||
import { connect } from "mongoose";
|
||||
import "./tracing.js";
|
||||
|
||||
// eslint-disable-next-line perfectionist/sort-imports
|
||||
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" });
|
||||
|
||||
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}`);
|
||||
56
apps/api-worker/src/routes/sessionKeepAlive.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
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";
|
||||
|
||||
const schema = type({
|
||||
token: "string.trim",
|
||||
session: "string.trim",
|
||||
});
|
||||
|
||||
export async function sessionKeepAlive(request: FastifyRequest, reply: FastifyReply) {
|
||||
//* Get the 2 headers
|
||||
const out = schema({
|
||||
token: request.headers["x-token"],
|
||||
session: request.headers["x-session"],
|
||||
});
|
||||
|
||||
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" });
|
||||
|
||||
await redis.hset(
|
||||
"pmd-api.sessions",
|
||||
out.token,
|
||||
JSON.stringify({
|
||||
session: out.session,
|
||||
token: out.token,
|
||||
lastUpdated: Date.now(),
|
||||
}),
|
||||
);
|
||||
|
||||
const interval = Number.parseInt(process.env.SESSION_KEEP_ALIVE_INTERVAL ?? "5000");
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
18
apps/api-worker/src/tracing.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
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();
|
||||
10
apps/api-worker/tsconfig.app.json
Normal file
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"rootDir": "src",
|
||||
"types": ["@ark/schema"],
|
||||
"outDir": "dist"
|
||||
},
|
||||
"include": ["src/**/*"]
|
||||
}
|
||||
8
apps/api-worker/tsconfig.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "./tsconfig.app.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": ".",
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["environment.d.ts", "src", "codegen.ts"]
|
||||
}
|
||||
1
apps/docs/.vitepress/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
cache
|
||||
129
apps/docs/.vitepress/config.mts
Normal file
@@ -0,0 +1,129 @@
|
||||
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,
|
||||
});
|
||||
77
apps/docs/dev/creating-a-presence.md
Normal file
@@ -0,0 +1,77 @@
|
||||
# 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.
|
||||
50
apps/docs/dev/getting-started.md
Normal file
@@ -0,0 +1,50 @@
|
||||
# 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.
|
||||
0
apps/docs/dev/submitting-a-presence.md
Normal file
5
apps/docs/getting-started.md
Normal file
@@ -0,0 +1,5 @@
|
||||
# Getting Started
|
||||
|
||||
Welcome to the official documentation for PreMiD! This guide will help you get started with PreMiD.
|
||||
|
||||
## Installation
|
||||
51
apps/docs/index.md
Normal file
@@ -0,0 +1,51 @@
|
||||
---
|
||||
# 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>
|
||||
14
apps/docs/package.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
||||
1
apps/docs/public/logo.svg
Normal file
|
After Width: | Height: | Size: 288 KiB |
68
apps/docs/reference/presence.md
Normal file
@@ -0,0 +1,68 @@
|
||||
# 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.
|
||||
3
apps/pd/README.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# @premid/pd
|
||||
|
||||
A simple url shortener service to shorten urls longer than 256 characters.
|
||||
12
apps/pd/environment.d.ts
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
declare namespace NodeJS {
|
||||
export interface ProcessEnv {
|
||||
NODE_ENV?: "development" | "production" | "test";
|
||||
REDIS_URL?: string;
|
||||
MAX_FILE_SIZE?: string;
|
||||
PORT?: string;
|
||||
HOST?: string;
|
||||
RATELIMIT_MAX?: string;
|
||||
RATELIMIT_WINDOW?: string;
|
||||
BASE_URL?: string;
|
||||
}
|
||||
}
|
||||
BIN
apps/pd/fixtures/1x1.png
Normal file
|
After Width: | Height: | Size: 95 B |
BIN
apps/pd/fixtures/test.mp4
Normal file
34
apps/pd/package.json
Normal file
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"name": "@premid/pd",
|
||||
"type": "module",
|
||||
"version": "1.1.9",
|
||||
"private": true,
|
||||
"description": "A small service to shorten image urls to get around Discord's 256 character limit",
|
||||
"license": "MPL-2.0",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"start": "node --enable-source-maps .",
|
||||
"dev": "node --watch --enable-source-maps ."
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/cors": "^9.0.1",
|
||||
"@fastify/multipart": "^8.1.0",
|
||||
"@fastify/rate-limit": "^9.1.0",
|
||||
"@keyv/redis": "^2.8.4",
|
||||
"fastify": "^4.26.0",
|
||||
"file-type": "^19.0.0",
|
||||
"got": "^14.2.0",
|
||||
"ioredis": "^5.3.2",
|
||||
"ipaddr.js": "^2.1.0",
|
||||
"keyv": "^4.5.4",
|
||||
"mime-types": "^2.1.35",
|
||||
"nanoid": "^5.0.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/mime-types": "^2.1.4",
|
||||
"form-data": "^4.0.0"
|
||||
}
|
||||
}
|
||||
9
apps/pd/src/functions/createKeyv.test.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import createKeyv from "./createKeyv.js";
|
||||
|
||||
it("should return keyv instance", () => {
|
||||
const keyv = createKeyv();
|
||||
|
||||
expect(keyv).toStrictEqual(expect.any(Object));
|
||||
});
|
||||
28
apps/pd/src/functions/createKeyv.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import process from "node:process";
|
||||
import KeyvRedis from "@keyv/redis";
|
||||
import Keyv from "keyv";
|
||||
|
||||
import redis from "../redis.js";
|
||||
|
||||
export default function createKeyv() {
|
||||
let options: Keyv.Options<string> | undefined;
|
||||
|
||||
/* c8 ignore next 8 */
|
||||
if (process.env.REDIS_SENTINELS) {
|
||||
options = {
|
||||
namespace: "pd",
|
||||
store: new KeyvRedis(redis),
|
||||
};
|
||||
}
|
||||
|
||||
const keyv = new Keyv<string>(
|
||||
options,
|
||||
);
|
||||
|
||||
/* c8 ignore next 3 */
|
||||
keyv.on("error", (error) => {
|
||||
console.error("Keyv connection error:", error);
|
||||
});
|
||||
|
||||
return keyv;
|
||||
}
|
||||
30
apps/pd/src/functions/createRedis.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
/* eslint-disable no-console */
|
||||
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: `pd-${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 3 */
|
||||
redis.on("connect", () => {
|
||||
console.log("Redis connected");
|
||||
});
|
||||
|
||||
return redis;
|
||||
}
|
||||
10
apps/pd/src/functions/createServer.test.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createServer } from "../functions/createServer.js";
|
||||
|
||||
describe("createServer", () => {
|
||||
it("should return a fastify instance", async () => {
|
||||
const server = await createServer();
|
||||
expect(server).toBeDefined();
|
||||
});
|
||||
});
|
||||
62
apps/pd/src/functions/createServer.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import process from "node:process";
|
||||
import cors from "@fastify/cors";
|
||||
import fastifyMultipart from "@fastify/multipart";
|
||||
import ratelimit from "@fastify/rate-limit";
|
||||
import fastify from "fastify";
|
||||
import type { Redis } from "ioredis";
|
||||
|
||||
import createFromBase64 from "../routes/createFromBase64.js";
|
||||
import createFromImage from "../routes/createFromImage.js";
|
||||
import createShortenedLink from "../routes/createShortenedLink.js";
|
||||
import getFullLink from "../routes/getFullLink.js";
|
||||
|
||||
export async function createServer(redis?: Redis) {
|
||||
const server = fastify({
|
||||
trustProxy: true,
|
||||
});
|
||||
|
||||
await server.register(cors, {
|
||||
methods: ["GET"],
|
||||
origin: "*",
|
||||
});
|
||||
|
||||
await server.register(ratelimit, {
|
||||
max: Number.parseInt(process.env.RATELIMIT_MAX ?? "25"),
|
||||
nameSpace: "pd-ratelimit-",
|
||||
redis,
|
||||
timeWindow: process.env.RATELIMIT_WINDOW ?? "1 minute",
|
||||
});
|
||||
|
||||
await server.register(fastifyMultipart, {
|
||||
limits: {
|
||||
fileSize: Number.parseInt(process.env.MAX_FILE_SIZE ?? (5 * 1024 * 1024).toString()),
|
||||
files: 1,
|
||||
},
|
||||
});
|
||||
|
||||
server.post("/create/image", createFromImage);
|
||||
server.post("/create/base64", createFromBase64);
|
||||
server.get("/create/*", createShortenedLink);
|
||||
|
||||
server.get(
|
||||
"/*",
|
||||
{
|
||||
config: {
|
||||
rateLimit: false,
|
||||
},
|
||||
},
|
||||
getFullLink,
|
||||
);
|
||||
|
||||
server.get(
|
||||
"/health",
|
||||
{
|
||||
config: {
|
||||
rateLimit: false,
|
||||
},
|
||||
},
|
||||
(_, reply) => reply.status(204).send(),
|
||||
);
|
||||
|
||||
return server;
|
||||
}
|
||||
30
apps/pd/src/functions/getGoogleAddresses.test.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import got from "got";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
describe.concurrent("getGoogleAddresses", () => {
|
||||
it("should return an array of CIDR objects", async () => {
|
||||
const { default: getGoogleAddresses } = await import("./getGoogleAddresses.js");
|
||||
|
||||
vi.spyOn(got, "get").mockResolvedValue({
|
||||
body: JSON.stringify({
|
||||
prefixes: [
|
||||
{ ipv4Prefix: "0.0.0.0" },
|
||||
{ ipv6Prefix: "0000:0000:0000::/16" },
|
||||
],
|
||||
}),
|
||||
});
|
||||
|
||||
const result = await getGoogleAddresses();
|
||||
|
||||
expect(result).toMatchInlineSnapshot(`
|
||||
[
|
||||
{
|
||||
"ipv4Prefix": "0.0.0.0",
|
||||
},
|
||||
{
|
||||
"ipv6Prefix": "0000:0000:0000::/16",
|
||||
},
|
||||
]
|
||||
`);
|
||||
});
|
||||
});
|
||||
24
apps/pd/src/functions/getGoogleAddresses.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import got from "got";
|
||||
|
||||
import type { CIDR } from "./isInCidRange.js";
|
||||
|
||||
export default async function getGoogleAddresses(): Promise<CIDR> {
|
||||
const { body } = await got.get("https://www.gstatic.com/ipranges/cloud.json");
|
||||
const result = JSON.parse(body) as GoogleResult;
|
||||
return result.prefixes.map(({ ipv4Prefix, ipv6Prefix }) => {
|
||||
return ipv6Prefix ? { ipv6Prefix } : { ipv4Prefix };
|
||||
});
|
||||
}
|
||||
|
||||
interface GoogleResult {
|
||||
syncToken: string;
|
||||
creationTime: string;
|
||||
prefixes: GoogleIP[];
|
||||
}
|
||||
|
||||
interface GoogleIP {
|
||||
ipv6Prefix: string;
|
||||
ipv4Prefix: string;
|
||||
service: string;
|
||||
scope: string;
|
||||
}
|
||||
31
apps/pd/src/functions/isInCidRange.test.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import isInCIDRRange from "./isInCidRange.js";
|
||||
|
||||
it("isInCIDRRange - IPv4 - in range", () => {
|
||||
const CIDRs = [{ ipv4Prefix: "192.0.2.0/24" }];
|
||||
const ip = "192.0.2.123";
|
||||
const result = isInCIDRRange(CIDRs, ip);
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it("isInCIDRRange - IPv4 - not in range", () => {
|
||||
const CIDRs = [{ ipv4Prefix: "192.0.2.0/24" }];
|
||||
const ip = "192.0.3.123";
|
||||
const result = isInCIDRRange(CIDRs, ip);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it("isInCIDRRange - IPv6 - in range", () => {
|
||||
const CIDRs = [{ ipv6Prefix: "2001:db8::/32" }];
|
||||
const ip = "2001:db8::1234";
|
||||
const result = isInCIDRRange(CIDRs, ip);
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it("isInCIDRRange - IPv6 - not in range", () => {
|
||||
const CIDRs = [{ ipv6Prefix: "2001:db8::/32" }];
|
||||
const ip = "2001:db9::1234";
|
||||
const result = isInCIDRRange(CIDRs, ip);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
29
apps/pd/src/functions/isInCidRange.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import ipaddr from "ipaddr.js";
|
||||
|
||||
export default function isInCIDRRange(CIDRs: CIDR, ip: string) {
|
||||
const parsed = ipaddr.parse(ip);
|
||||
|
||||
for (const CIDR of CIDRs.filter((c) => {
|
||||
if (parsed.kind() === "ipv4" && "ipv4Prefix" in c)
|
||||
return true;
|
||||
else if (parsed.kind() === "ipv6" && "ipv6Prefix" in c)
|
||||
return true;
|
||||
else return false;
|
||||
})) {
|
||||
const check = parsed.match(ipaddr.parseCIDR("ipv4Prefix" in CIDR ? CIDR.ipv4Prefix : CIDR.ipv6Prefix));
|
||||
|
||||
if (check)
|
||||
return check;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export type CIDR = (
|
||||
| {
|
||||
ipv4Prefix: string;
|
||||
}
|
||||
| {
|
||||
ipv6Prefix: string;
|
||||
}
|
||||
)[];
|
||||
3
apps/pd/src/googleCIDRs.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import getGoogleAddresses from "./functions/getGoogleAddresses.js";
|
||||
|
||||
export default await getGoogleAddresses();
|
||||
14
apps/pd/src/index.test.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { createServer } from "./functions/createServer.js";
|
||||
|
||||
it("/health", async () => {
|
||||
const server = await createServer();
|
||||
const result = await server.inject({
|
||||
method: "GET",
|
||||
url: "/health",
|
||||
});
|
||||
|
||||
expect(result.statusCode).toBe(204);
|
||||
expect(result.body).toBe("");
|
||||
});
|
||||
20
apps/pd/src/index.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
/* eslint-disable no-console */
|
||||
/* c8 ignore start */
|
||||
import process from "node:process";
|
||||
import { createServer } from "./functions/createServer.js";
|
||||
import redis from "./redis.js";
|
||||
|
||||
if (!process.env.REDIS_SENTINELS)
|
||||
console.log("WARNING: No REDIS_SENTINELS environment variable set");
|
||||
if (process.env.NODE_ENV === "production" && !process.env.BASE_URL)
|
||||
throw new Error("BASE_URL environment variable is required in production");
|
||||
|
||||
export const server = await createServer(redis);
|
||||
|
||||
const url = await server.listen({
|
||||
host: process.env.HOST ?? "0.0.0.0",
|
||||
port: Number.parseInt(process.env.PORT ?? "80"),
|
||||
});
|
||||
|
||||
console.log(`Server listening at ${url}`);
|
||||
// TODO Make proper error codes & json responses
|
||||
3
apps/pd/src/keyv.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import createKeyv from "./functions/createKeyv.js";
|
||||
|
||||
export default createKeyv();
|
||||
3
apps/pd/src/redis.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import createRedis from "./functions/createRedis.js";
|
||||
|
||||
export default createRedis();
|
||||
94
apps/pd/src/routes/createFromBase64.test.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import { describe, it } from "vitest";
|
||||
|
||||
import { createServer } from "../functions/createServer.js";
|
||||
|
||||
describe.concurrent("createFromBase64", async () => {
|
||||
const server = await createServer();
|
||||
|
||||
it("should return a 400 when the body is not present", async ({ expect }) => {
|
||||
const result = await server.inject({
|
||||
method: "POST",
|
||||
url: "/create/base64",
|
||||
});
|
||||
|
||||
expect(result.statusCode).toBe(400);
|
||||
expect(result.body).toMatchInlineSnapshot("\"Invalid body\"");
|
||||
});
|
||||
|
||||
it("should return a 400 when the body is not a string", async ({ expect }) => {
|
||||
const result = await server.inject({
|
||||
method: "POST",
|
||||
payload: new Blob([]),
|
||||
url: "/create/base64",
|
||||
});
|
||||
|
||||
expect(result.statusCode).toBe(400);
|
||||
expect(result.body).toMatchInlineSnapshot("\"Invalid body\"");
|
||||
});
|
||||
|
||||
it("should return a 400 when the body is not a valid base64 string", async ({ expect }) => {
|
||||
const result = await server.inject({
|
||||
headers: {
|
||||
"Content-Type": "text/plain",
|
||||
},
|
||||
method: "POST",
|
||||
payload: "data:image/png;base64t",
|
||||
url: "/create/base64",
|
||||
});
|
||||
|
||||
expect(result.statusCode).toBe(400);
|
||||
expect(result.body).toMatchInlineSnapshot("\"Invalid base64 string\"");
|
||||
});
|
||||
|
||||
it("should return a 400 when the base64 string is not a valid image", async ({ expect }) => {
|
||||
const result = await server.inject({
|
||||
headers: {
|
||||
"Content-Type": "text/plain",
|
||||
},
|
||||
method: "POST",
|
||||
payload: "data:image/sv;base64,a",
|
||||
url: "/create/base64",
|
||||
});
|
||||
|
||||
expect(result.statusCode).toBe(400);
|
||||
expect(result.body).toMatchInlineSnapshot("\"Invalid base64 string\"");
|
||||
|
||||
const result2 = await server.inject({
|
||||
headers: {
|
||||
"Content-Type": "text/plain",
|
||||
},
|
||||
method: "POST",
|
||||
payload: "data:image/svg+xml;base64,s",
|
||||
url: "/create/base64",
|
||||
});
|
||||
|
||||
expect(result2.statusCode).toBe(400);
|
||||
expect(result2.body).toMatchInlineSnapshot("\"Supported types: png, jpeg, jpg, gif, webp\"");
|
||||
});
|
||||
|
||||
it("should return a 200 when the base64 string is valid", async ({ expect }) => {
|
||||
const result = await server.inject({
|
||||
headers: {
|
||||
"Content-Type": "text/plain",
|
||||
},
|
||||
method: "POST",
|
||||
payload: "data:image/png;base64,s",
|
||||
url: "/create/base64",
|
||||
});
|
||||
|
||||
expect(result.statusCode).toBe(200);
|
||||
expect(result.body).toStrictEqual(expect.any(String));
|
||||
|
||||
const result2 = await server.inject({
|
||||
headers: {
|
||||
"Content-Type": "text/plain",
|
||||
},
|
||||
method: "POST",
|
||||
payload: "data:image/png;base64,s",
|
||||
url: "/create/base64",
|
||||
});
|
||||
|
||||
expect(result2.statusCode).toBe(200);
|
||||
expect(result2.body).toStrictEqual(expect.any(String));
|
||||
});
|
||||
});
|
||||
49
apps/pd/src/routes/createFromBase64.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import crypto from "node:crypto";
|
||||
|
||||
import process from "node:process";
|
||||
import mime from "mime-types";
|
||||
import { nanoid } from "nanoid";
|
||||
import type { RouteHandlerMethod } from "fastify";
|
||||
|
||||
import keyv from "../keyv.js";
|
||||
|
||||
const handler: RouteHandlerMethod = async (request, reply) => {
|
||||
const { body } = request;
|
||||
|
||||
if (!body)
|
||||
return reply.status(400).send("Invalid body");
|
||||
|
||||
if (typeof body !== "string")
|
||||
return reply.status(400).send("Invalid body");
|
||||
|
||||
const matches = body.match(/^data:(.+);base64,(.+)/);
|
||||
|
||||
if (!matches || matches.length === 0)
|
||||
return reply.status(400).send("Invalid base64 string");
|
||||
|
||||
const type = mime.extension(matches.at(1)!);
|
||||
|
||||
if (!type)
|
||||
return reply.status(400).send("Invalid base64 string");
|
||||
|
||||
if (!["png", "jpeg", "jpg", "gif", "webp"].includes(type))
|
||||
return reply.status(400).send("Supported types: png, jpeg, jpg, gif, webp");
|
||||
|
||||
const hash = crypto.createHash("sha256").update(body).digest("hex");
|
||||
const existingUrl = await keyv.get(hash);
|
||||
|
||||
if (existingUrl) {
|
||||
void reply.header("Cache-control", `public, max-age=${(30 * 60).toString()}`);
|
||||
return reply.send(process.env.BASE_URL! + existingUrl);
|
||||
}
|
||||
|
||||
const uniqueId = `${nanoid(10)}.${type}`;
|
||||
|
||||
await keyv.set(hash, uniqueId, 30 * 60 * 1000);
|
||||
await keyv.set(uniqueId, body, 30 * 60 * 1000);
|
||||
|
||||
void reply.header("Cache-control", `public, max-age=${(30 * 60).toString()}`);
|
||||
return reply.send(process.env.BASE_URL! + uniqueId);
|
||||
};
|
||||
|
||||
export default handler;
|
||||