├── roms └── .gitkeep ├── public ├── .gitkeep ├── trigger.webp ├── index.html ├── css │ ├── style.css.map │ ├── style.css │ └── style.scss ├── client.html └── js │ └── main.js ├── .dockerignore ├── .prettierrc ├── src ├── declarations │ ├── config.interface.ts │ ├── structure.interface.ts │ └── readme-module.interface.ts ├── assets │ └── emojis │ │ ├── one.png │ │ ├── six.png │ │ ├── two.png │ │ ├── boom.png │ │ ├── eight.png │ │ ├── five.png │ │ ├── four.png │ │ ├── seven.png │ │ └── three.png ├── games │ ├── chess │ │ ├── assets │ │ │ ├── bb.png │ │ │ ├── bk.png │ │ │ ├── bn.png │ │ │ ├── bp.png │ │ │ ├── bq.png │ │ │ ├── br.png │ │ │ ├── wb.png │ │ │ ├── wk.png │ │ │ ├── wn.png │ │ │ ├── wp.png │ │ │ ├── wq.png │ │ │ └── wr.png │ │ ├── declarations.ts │ │ ├── classes │ │ │ ├── Piece.ts │ │ │ ├── Rook.ts │ │ │ ├── Bishop.ts │ │ │ ├── Knight.ts │ │ │ ├── Pawn.ts │ │ │ ├── Queen.ts │ │ │ ├── King.ts │ │ │ ├── utils.ts │ │ │ └── Chess.ts │ │ ├── chess.controller.ts │ │ └── chess.service.ts │ ├── sudoku │ │ ├── sudoku.service.ts │ │ ├── sudoku.module.ts │ │ └── sudoku.controller.ts │ ├── wordle │ │ ├── wordle.module.ts │ │ ├── wordle.controller.ts │ │ └── wordle.service.ts │ ├── gba │ │ ├── gba.module.ts │ │ ├── gba.controller.ts │ │ └── gba.service.ts │ ├── gameboy │ │ ├── gameboy.module.ts │ │ ├── gameboy.controller.ts │ │ ├── gameboy.gateway.ts │ │ └── gameboy.service.ts │ ├── minesweeper │ │ ├── classes │ │ │ ├── Cell.ts │ │ │ └── Minesweeper.ts │ │ ├── minesweeper.controller.ts │ │ └── minesweeper.service.ts │ └── games.module.ts ├── users │ ├── users.service.ts │ ├── users.module.ts │ └── users.service.spec.ts ├── declaration.ts ├── services │ ├── index.ts │ ├── ConfigService.ts │ ├── RequestService.ts │ └── ReadmeService.ts ├── trigger │ ├── trigger.module.ts │ └── trigger.controller.ts ├── redis │ ├── redis.module.ts │ └── redis.service.ts ├── auth │ ├── auth.service.ts │ ├── auth.service.spec.ts │ ├── auth.module.ts │ ├── auth.controller.spec.ts │ └── auth.controller.ts ├── modules │ ├── statics │ │ ├── raw.module.ts │ │ ├── greeting.module.ts │ │ ├── profile-views.module.ts │ │ ├── list.module.ts │ │ ├── socials.module.ts │ │ ├── lines.module.ts │ │ ├── element.module.ts │ │ ├── trigger.module.ts │ │ └── skills.module.ts │ ├── dynamics │ │ ├── generated.module.ts │ │ ├── followers.module.ts │ │ ├── wordle.module.ts │ │ ├── minesweeper.module.ts │ │ ├── chess.module.ts │ │ └── gba.module.ts │ ├── index.ts │ └── abstract.module.ts ├── app.controller.ts ├── app.service.ts ├── main.ts ├── app.controller.spec.ts ├── app.module.ts ├── State.ts └── zod.zodobject.ts ├── tsconfig.build.json ├── Dockerfile ├── nest-cli.json ├── .gitignore ├── test ├── jest-e2e.json └── app.e2e-spec.ts ├── .env.example ├── tsconfig.json ├── .eslintrc.js ├── docker-compose.prod.yml ├── docker-compose.dev.yml ├── config.example.json ├── package.json ├── config.md ├── README.md └── LICENSE /roms/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | .git 4 | 5 | .env* 6 | config*.json -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } -------------------------------------------------------------------------------- /src/declarations/config.interface.ts: -------------------------------------------------------------------------------- 1 | export default interface Config { 2 | [name: string]: any 3 | } -------------------------------------------------------------------------------- /public/trigger.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/main/public/trigger.webp -------------------------------------------------------------------------------- /src/assets/emojis/one.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/main/src/assets/emojis/one.png -------------------------------------------------------------------------------- /src/assets/emojis/six.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/main/src/assets/emojis/six.png -------------------------------------------------------------------------------- /src/assets/emojis/two.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/main/src/assets/emojis/two.png -------------------------------------------------------------------------------- /src/declarations/structure.interface.ts: -------------------------------------------------------------------------------- 1 | export default interface RendererStructure { 2 | [name: string]: any 3 | } -------------------------------------------------------------------------------- /src/assets/emojis/boom.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/main/src/assets/emojis/boom.png -------------------------------------------------------------------------------- /src/assets/emojis/eight.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/main/src/assets/emojis/eight.png -------------------------------------------------------------------------------- /src/assets/emojis/five.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/main/src/assets/emojis/five.png -------------------------------------------------------------------------------- /src/assets/emojis/four.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/main/src/assets/emojis/four.png -------------------------------------------------------------------------------- /src/assets/emojis/seven.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/main/src/assets/emojis/seven.png -------------------------------------------------------------------------------- /src/assets/emojis/three.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/main/src/assets/emojis/three.png -------------------------------------------------------------------------------- /src/games/chess/assets/bb.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/main/src/games/chess/assets/bb.png -------------------------------------------------------------------------------- /src/games/chess/assets/bk.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/main/src/games/chess/assets/bk.png -------------------------------------------------------------------------------- /src/games/chess/assets/bn.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/main/src/games/chess/assets/bn.png -------------------------------------------------------------------------------- /src/games/chess/assets/bp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/main/src/games/chess/assets/bp.png -------------------------------------------------------------------------------- /src/games/chess/assets/bq.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/main/src/games/chess/assets/bq.png -------------------------------------------------------------------------------- /src/games/chess/assets/br.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/main/src/games/chess/assets/br.png -------------------------------------------------------------------------------- /src/games/chess/assets/wb.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/main/src/games/chess/assets/wb.png -------------------------------------------------------------------------------- /src/games/chess/assets/wk.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/main/src/games/chess/assets/wk.png -------------------------------------------------------------------------------- /src/games/chess/assets/wn.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/main/src/games/chess/assets/wn.png -------------------------------------------------------------------------------- /src/games/chess/assets/wp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/main/src/games/chess/assets/wp.png -------------------------------------------------------------------------------- /src/games/chess/assets/wq.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/main/src/games/chess/assets/wq.png -------------------------------------------------------------------------------- /src/games/chess/assets/wr.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/main/src/games/chess/assets/wr.png -------------------------------------------------------------------------------- /src/users/users.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | 3 | @Injectable() 4 | export class UsersService {} 5 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:22 2 | WORKDIR /usr/src/app 3 | COPY package*.json ./ 4 | RUN npm install --silent 5 | COPY . . 6 | RUN npm run build 7 | -------------------------------------------------------------------------------- /src/declaration.ts: -------------------------------------------------------------------------------- 1 | import * as z from "zod"; 2 | import { ConfigSchema } from "./zod.zodobject"; 3 | 4 | export type AppConfig = z.infer 5 | -------------------------------------------------------------------------------- /src/declarations/readme-module.interface.ts: -------------------------------------------------------------------------------- 1 | export default interface IReadmeModule { 2 | toMd: (BASE_URL: string, data: any, options: any) => Promise 3 | } -------------------------------------------------------------------------------- /src/games/chess/declarations.ts: -------------------------------------------------------------------------------- 1 | export type ChessCoordinates = string 2 | 3 | export interface MoveInstruction { 4 | from: ChessCoordinates 5 | to: ChessCoordinates 6 | } 7 | -------------------------------------------------------------------------------- /src/services/index.ts: -------------------------------------------------------------------------------- 1 | export { AppConfigService } from './ConfigService' 2 | export { default as ReadmeService } from './ReadmeService' 3 | export { default as RequestService } from './RequestService' -------------------------------------------------------------------------------- /src/games/sudoku/sudoku.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | 3 | @Injectable() 4 | export class SudokuService { 5 | new() { 6 | console.log('New sudoku') 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/users/users.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { UsersService } from './users.service'; 3 | 4 | @Module({ 5 | providers: [UsersService] 6 | }) 7 | export class UsersModule {} 8 | -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/nest-cli", 3 | "collection": "@nestjs/schematics", 4 | "sourceRoot": "src", 5 | "compilerOptions": { 6 | "deleteOutDir": true 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/trigger/trigger.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { TriggerController } from './trigger.controller'; 3 | 4 | @Module({ 5 | controllers: [TriggerController], 6 | }) 7 | export class TriggerModule {} 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | .vscode 3 | 4 | dist/ 5 | 6 | .env 7 | .env* 8 | !.env.example 9 | 10 | config.json 11 | public/board.png 12 | public/minesweeper.gif 13 | 14 | roms/* 15 | !roms/.gitkeep 16 | 17 | package-lock.json -------------------------------------------------------------------------------- /src/redis/redis.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { RedisService } from './redis.service'; 3 | 4 | @Module({ 5 | providers: [RedisService], 6 | exports: [RedisService] 7 | }) 8 | export class RedisModule {} 9 | -------------------------------------------------------------------------------- /test/jest-e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "moduleFileExtensions": ["js", "json", "ts"], 3 | "rootDir": ".", 4 | "testEnvironment": "node", 5 | "testRegex": ".e2e-spec.ts$", 6 | "transform": { 7 | "^.+\\.(t|j)s$": "ts-jest" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Document 7 | 8 | 9 | Hello World ? 10 | 11 | -------------------------------------------------------------------------------- /src/games/sudoku/sudoku.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { SudokuService } from './sudoku.service'; 3 | import { SudokuController } from './sudoku.controller'; 4 | 5 | @Module({ 6 | providers: [SudokuService], 7 | controllers: [SudokuController] 8 | }) 9 | export class SudokuModule {} 10 | -------------------------------------------------------------------------------- /src/games/wordle/wordle.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { WordleService } from './wordle.service'; 3 | import { WordleController } from './wordle.controller'; 4 | 5 | @Module({ 6 | providers: [WordleService], 7 | controllers: [WordleController] 8 | }) 9 | export class WordleModule {} 10 | -------------------------------------------------------------------------------- /src/auth/auth.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { JwtService } from '@nestjs/jwt'; 3 | 4 | @Injectable() 5 | export class AuthService { 6 | constructor(private jwtService: JwtService){} 7 | 8 | async verify(token: string) { 9 | return this.jwtService.verifyAsync(token) 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/modules/statics/raw.module.ts: -------------------------------------------------------------------------------- 1 | import { AbstractStaticModule } from "../abstract.module"; 2 | 3 | interface Data { 4 | content: string 5 | } 6 | 7 | interface Options { 8 | } 9 | 10 | export class RawStaticModule extends AbstractStaticModule { 11 | public render(): string | Promise { 12 | return this.data.content 13 | } 14 | } -------------------------------------------------------------------------------- /src/games/gba/gba.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { GbaService } from './gba.service'; 3 | import { GbaController } from './gba.controller'; 4 | import { AuthModule } from 'src/auth/auth.module'; 5 | 6 | @Module({ 7 | imports: [AuthModule], 8 | providers: [GbaService], 9 | controllers: [GbaController] 10 | }) 11 | export class GbaModule {} 12 | -------------------------------------------------------------------------------- /src/modules/statics/greeting.module.ts: -------------------------------------------------------------------------------- 1 | import { AbstractStaticModule } from "../abstract.module"; 2 | 3 | interface Data { 4 | firstName: string 5 | lastName: string 6 | } 7 | 8 | interface Options { 9 | } 10 | 11 | export class GreetingStaticModule extends AbstractStaticModule { 12 | public render(): string | Promise { 13 | return `

I'm ${this.data.firstName} ${this.data.lastName} !

\n` 14 | } 15 | } -------------------------------------------------------------------------------- /src/app.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get } from '@nestjs/common'; 2 | import { AppService } from './app.service'; 3 | 4 | @Controller() 5 | export class AppController { 6 | constructor( 7 | private readonly appService: AppService, 8 | ) {} 9 | 10 | @Get() 11 | async getHello(): Promise { 12 | return this.appService.getHello(); 13 | } 14 | 15 | @Get('render') 16 | render() { 17 | return this.appService.render() 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/games/gameboy/gameboy.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { GameboyService } from './gameboy.service'; 3 | import { GameboyController } from './gameboy.controller'; 4 | import { GameboyGateway } from './gameboy.gateway'; 5 | import { AuthModule } from 'src/auth/auth.module'; 6 | 7 | @Module({ 8 | imports: [AuthModule], 9 | providers: [GameboyService, GameboyGateway], 10 | controllers: [GameboyController] 11 | }) 12 | export class GameboyModule {} 13 | -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | GH_TOKEN="" 2 | GH_ACTION_TRUST="" 3 | GH_APP_CLIENT_ID="" 4 | GH_APP_CLIENT_SECRET_ID="" 5 | 6 | JWT_SECRET="" 7 | 8 | OCTO_COMMITTER_NAME="" 9 | OCTO_COMMITTER_EMAIL="" 10 | 11 | APP_IP= 12 | 13 | APP_PROTOCOL="" 14 | APP_SUB_DOMAIN="" 15 | APP_DOMAIN="" 16 | APP_PORT=80 17 | APP_URL=${APP_PROTOCOL}://${APP_SUB_DOMAIN}.${APP_DOMAIN}:${APP_PORT} 18 | 19 | REDIS_URL=redis://redis:6379 20 | DOCKER_LOCAL_PORT=3000 21 | 22 | EMU_BACKUP_CRON="0 */5 * * * *" 23 | 24 | ROM_NAME="" 25 | ROM_GBA_NAME="" -------------------------------------------------------------------------------- /src/auth/auth.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { AuthService } from './auth.service'; 3 | 4 | describe('AuthService', () => { 5 | let service: AuthService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | providers: [AuthService], 10 | }).compile(); 11 | 12 | service = module.get(AuthService); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(service).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/games/chess/classes/Piece.ts: -------------------------------------------------------------------------------- 1 | export class Piece { 2 | x; // lettres 0 = A, 7 = h 3 | y; // /!\ blanc pov 0 c'est en bas 4 | uniqueInitial; 5 | color; 6 | moved = false; 7 | legalMoves = []; 8 | constructor(x, y, color) { 9 | this.x = x 10 | this.y = y 11 | this.color = color 12 | } 13 | 14 | updateCoords(coords) { 15 | this.x = coords.x; 16 | this.y = coords.y; 17 | this.moved = true 18 | } 19 | 20 | public getImage(): string { 21 | return this.color.charAt(0) + this.uniqueInitial 22 | } 23 | } -------------------------------------------------------------------------------- /src/auth/auth.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { AuthController } from './auth.controller'; 3 | import { AuthService } from './auth.service'; 4 | import { JwtModule } from '@nestjs/jwt'; 5 | import { RedisModule } from 'src/redis/redis.module'; 6 | 7 | 8 | @Module({ 9 | imports: [JwtModule.register({ secret: process.env.JWT_SECRET, signOptions: { expiresIn: '1h' } }), RedisModule], 10 | controllers: [AuthController], 11 | providers: [AuthService], 12 | exports: [AuthService] 13 | }) 14 | export class AuthModule {} 15 | -------------------------------------------------------------------------------- /src/users/users.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { UsersService } from './users.service'; 3 | 4 | describe('UsersService', () => { 5 | let service: UsersService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | providers: [UsersService], 10 | }).compile(); 11 | 12 | service = module.get(UsersService); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(service).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/modules/statics/profile-views.module.ts: -------------------------------------------------------------------------------- 1 | import { AbstractStaticModule } from "../abstract.module"; 2 | 3 | interface Data { 4 | username: string 5 | } 6 | 7 | interface Options { 8 | align: "start" | "center" | "end" 9 | } 10 | 11 | export class ProfileViewsStaticModule extends AbstractStaticModule { 12 | public render(): string | Promise { 13 | return `

\n ${this.data.username}'s profile view count\n

\n` 14 | } 15 | } -------------------------------------------------------------------------------- /src/auth/auth.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { AuthController } from './auth.controller'; 3 | 4 | describe('AuthController', () => { 5 | let controller: AuthController; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | controllers: [AuthController], 10 | }).compile(); 11 | 12 | controller = module.get(AuthController); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(controller).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/redis/redis.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, Logger } from '@nestjs/common'; 2 | import { RedisClientType, createClient } from 'redis'; 3 | 4 | @Injectable() 5 | export class RedisService { 6 | public client: RedisClientType; 7 | private readonly logger = new Logger('DB') 8 | constructor() { 9 | this.client = createClient({ 10 | url: process.env.REDIS_URL 11 | }); 12 | (async () => { 13 | await this.client.connect(); 14 | if(await this.client.ping() === 'PONG') this.logger.log('Connection established to the database') 15 | })() 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /public/css/style.css.map: -------------------------------------------------------------------------------- 1 | {"version":3,"sourceRoot":"","sources":["style.scss"],"names":[],"mappings":"AAAA;EACE;EACA;EACA;EACA;;;AAGF;EACE;EACA;EACA;EACA;EACA;EACA;;AAEA;EACE;EACA;EACA;EACA;;AAGF;EACE;EACA;EACA;EACA;EACA;;AAEA;EACE;EACA;EACA;EACA;EACA;EACA;;AAEA;EACE;EACA;EACA;EACA;EACA;EACA;;AAEA;EACE;EACA;EACA;;AAEF;EACE;EACA;EACA;;AAEF;EACE;EACA;EACA;;AAEF;EACE;EACA;EACA;;AAKN;EACE;EACA;EACA;EACA;EACA;EACA;;AAEA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AAEA;EACE;EACA;;AAEF;EACE;EACA;;AAKN;EACE;EACA;EACA;EACA;EACA;EACA;;AAEA;EACE;EACA;EACA;EACA;EACA;;;AAMR;EACE;IACE;IACA;;;AAKJ;EACE;IACE;;EAGF;IACE","file":"style.css"} -------------------------------------------------------------------------------- /src/app.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import State from './State'; 3 | 4 | @Injectable() 5 | export class AppService { 6 | 7 | constructor() {} 8 | 9 | getHello(): string { 10 | return 'Hello World!'; 11 | } 12 | 13 | async render() { 14 | const content = await State.render() 15 | 16 | return ` 17 | 18 | 19 | 20 | 21 | Document 22 | 23 | 24 | ${content} 25 | 26 | ` 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/games/minesweeper/classes/Cell.ts: -------------------------------------------------------------------------------- 1 | export class Cell { 2 | x: number; 3 | y: number; 4 | value: number; 5 | constructor(x: number, y: number, value: number, public hidden: boolean = true){ 6 | this.x = x; 7 | this.y = y; 8 | this.value = value; 9 | } 10 | 11 | revealCell(){ 12 | this.hidden = false 13 | } 14 | 15 | toEmoji(){ 16 | let values = [":white_large_square:", ":one:", ":two:", ":three:", ":four:", ":five:", ":six:", ":seven:", ":eight:", ":boom:"] 17 | if(this.hidden) return ":black_large_square:" 18 | return values[this.value] 19 | } 20 | } -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { NestFactory } from '@nestjs/core'; 2 | import { AppModule } from './app.module'; 3 | import { NestExpressApplication } from '@nestjs/platform-express'; 4 | 5 | async function bootstrap() { 6 | const app = await NestFactory.create(AppModule, { 7 | logger: process.env.NODE_ENV === "development" 8 | ? ['log', 'debug', 'verbose', 'warn', 'error', 'fatal'] 9 | : ['log', 'warn', 'error', 'fatal'] 10 | }); 11 | app.useBodyParser('json', { limit: '100mb' }); 12 | app.enableCors() 13 | await app.listen(process.env.APP_PORT); 14 | console.log(`Application is running on: ${await app.getUrl()}`) 15 | } 16 | bootstrap(); 17 | -------------------------------------------------------------------------------- /src/app.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { AppController } from './app.controller'; 3 | import { AppService } from './app.service'; 4 | 5 | describe('AppController', () => { 6 | let appController: AppController; 7 | 8 | beforeEach(async () => { 9 | const app: TestingModule = await Test.createTestingModule({ 10 | controllers: [AppController], 11 | providers: [AppService], 12 | }).compile(); 13 | 14 | appController = app.get(AppController); 15 | }); 16 | 17 | describe('root', () => { 18 | it('should return "Hello World!"', () => { 19 | expect(appController.getHello()).toBe('Hello World!'); 20 | }); 21 | }); 22 | }); 23 | -------------------------------------------------------------------------------- /test/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { INestApplication } from '@nestjs/common'; 3 | import * as request from 'supertest'; 4 | import { AppModule } from './../src/app.module'; 5 | 6 | describe('AppController (e2e)', () => { 7 | let app: INestApplication; 8 | 9 | beforeEach(async () => { 10 | const moduleFixture: TestingModule = await Test.createTestingModule({ 11 | imports: [AppModule], 12 | }).compile(); 13 | 14 | app = moduleFixture.createNestApplication(); 15 | await app.init(); 16 | }); 17 | 18 | it('/ (GET)', () => { 19 | return request(app.getHttpServer()) 20 | .get('/') 21 | .expect(200) 22 | .expect('Hello World!'); 23 | }); 24 | }); 25 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "declaration": true, 5 | "removeComments": true, 6 | "emitDecoratorMetadata": true, 7 | "experimentalDecorators": true, 8 | "allowSyntheticDefaultImports": true, 9 | "target": "es2017", 10 | "sourceMap": true, 11 | "outDir": "./dist", 12 | "baseUrl": "./", 13 | "incremental": true, 14 | "skipLibCheck": true, 15 | "strictNullChecks": false, 16 | "noImplicitAny": false, 17 | "strictBindCallApply": false, 18 | "forceConsistentCasingInFileNames": false, 19 | "noFallthroughCasesInSwitch": false, 20 | "resolveJsonModule": true, 21 | "paths": { 22 | "~public/*": ["./public/*"] 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/modules/statics/list.module.ts: -------------------------------------------------------------------------------- 1 | import { AppConfigService } from "src/services"; 2 | import { AbstractStaticModule } from "../abstract.module"; 3 | 4 | interface Data { 5 | field: string 6 | } 7 | 8 | interface Options { 9 | } 10 | 11 | export class ListStaticModule extends AbstractStaticModule { 12 | public render(): string | Promise { 13 | 14 | const path = this.data.field.split('.') 15 | let list: any = AppConfigService.getOrThrow('config.datas'); 16 | 17 | for (let i = 0; i < path.length; i++) { 18 | list = list[path[i]]; 19 | } 20 | 21 | const {title, content} = list 22 | 23 | return `${title ? `

${title}

\n` : ''}
    \n${content.map(l => `
  • ${l}
  • \n`).join('')}
\n` 24 | } 25 | } -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@typescript-eslint/parser', 3 | parserOptions: { 4 | project: 'tsconfig.json', 5 | tsconfigRootDir: __dirname, 6 | sourceType: 'module', 7 | }, 8 | plugins: ['@typescript-eslint/eslint-plugin'], 9 | extends: [ 10 | 'plugin:@typescript-eslint/recommended', 11 | 'plugin:prettier/recommended', 12 | ], 13 | root: true, 14 | env: { 15 | node: true, 16 | jest: true, 17 | }, 18 | ignorePatterns: ['.eslintrc.js'], 19 | rules: { 20 | '@typescript-eslint/interface-name-prefix': 'off', 21 | '@typescript-eslint/explicit-function-return-type': 'off', 22 | '@typescript-eslint/explicit-module-boundary-types': 'off', 23 | '@typescript-eslint/no-explicit-any': 'off', 24 | }, 25 | }; 26 | -------------------------------------------------------------------------------- /src/games/wordle/wordle.controller.ts: -------------------------------------------------------------------------------- 1 | import { Body, 2 | Controller, 3 | Post, 4 | Res 5 | } from '@nestjs/common'; 6 | import { WordleService } from './wordle.service'; 7 | import { Response } from 'express'; 8 | 9 | @Controller('wordle') 10 | export class WordleController { 11 | constructor( 12 | private readonly wordleService: WordleService 13 | ) {} 14 | 15 | @Post('guess') 16 | async guess( 17 | @Res() res: Response, 18 | @Body('guess') guess: string, 19 | @Body('GH_ACTION_TRUST') GH_ACTION_TRUST: string, 20 | @Body('issuer') issuer: string, 21 | @Body('issuerId') issuerId: number 22 | ) { 23 | 24 | return this.wordleService.guess( 25 | GH_ACTION_TRUST, 26 | guess, 27 | issuer, 28 | issuerId, 29 | res 30 | ) 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /docker-compose.prod.yml: -------------------------------------------------------------------------------- 1 | services: 2 | dynamic-readme-prod: 3 | container_name: dr-prod-app 4 | restart: unless-stopped 5 | build: 6 | context: . 7 | dockerfile: Dockerfile 8 | env_file: 9 | - .env 10 | environment: 11 | - NODE_ENV=production 12 | command: npm run start:prod 13 | ports: 14 | - ${DOCKER_LOCAL_PORT}:${APP_PORT} 15 | networks: 16 | - app-network-prod 17 | volumes: 18 | - ./config.json:/usr/src/app/config.json 19 | depends_on: 20 | - redis-prod 21 | redis-prod: 22 | container_name: dr-prod-redis 23 | restart: unless-stopped 24 | image: redis:alpine 25 | ports: 26 | - 6379:6379 27 | volumes: 28 | - redis-data-prod:/data 29 | networks: 30 | - app-network-prod 31 | 32 | volumes: 33 | redis-data-prod: 34 | networks: 35 | app-network-prod: -------------------------------------------------------------------------------- /src/modules/dynamics/generated.module.ts: -------------------------------------------------------------------------------- 1 | import { AbstractDynamicModule } from "../abstract.module"; 2 | import State from "src/State"; 3 | 4 | interface Data { 5 | } 6 | 7 | interface Options { 8 | } 9 | 10 | export class GeneratedDynamicModule extends AbstractDynamicModule { 11 | ALWAYS_RERENDER = true 12 | 13 | public render(): string | Promise { 14 | let currentDate = new Date(); 15 | const days = [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] 16 | const months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep" , "Oct", "Nov", "Dec"] 17 | return `

Generated in ${(Date.now() - State.startRenderDTimestamp) / 1000}s on ${days[currentDate.getDay()]} ${months[currentDate.getMonth()]} ${currentDate.getDate()} at ${currentDate.getHours()}:${currentDate.getMinutes().toString().padStart(2, '0')}

\n`; 18 | } 19 | } -------------------------------------------------------------------------------- /src/modules/statics/socials.module.ts: -------------------------------------------------------------------------------- 1 | import { AppConfigService } from "src/services"; 2 | import { AbstractStaticModule } from "../abstract.module"; 3 | import { AppConfig } from "src/declaration"; 4 | 5 | interface Data { 6 | } 7 | 8 | interface Options { 9 | align: "start" | "center" | "end" 10 | } 11 | 12 | export class SocialsStaticModule extends AbstractStaticModule { 13 | public render(): string | Promise { 14 | const socials = AppConfigService.getOrThrow('config.datas.perso.socials'); 15 | 16 | const socialsStr = socials.map((social) => { 17 | return ` \n ${social.name}\n \n`; 18 | }).join(''); 19 | 20 | return `

Reach Me

\n

\n${socialsStr}

\n`; 21 | } 22 | } -------------------------------------------------------------------------------- /src/modules/statics/lines.module.ts: -------------------------------------------------------------------------------- 1 | import { AppConfigService } from "src/services"; 2 | import { AbstractStaticModule } from "../abstract.module"; 3 | 4 | interface Data { 5 | field: string 6 | range: string 7 | } 8 | 9 | interface Options { 10 | } 11 | 12 | export class LinesStaticModule extends AbstractStaticModule { 13 | public render(): string | Promise { 14 | 15 | const path = this.data.field.split('.') 16 | let lines: any = AppConfigService.getOrThrow('config.datas'); 17 | 18 | for (let i = 0; i < path.length; i++) { 19 | lines = lines[path[i]]; 20 | } 21 | 22 | if(!this.data.range.includes('-')) lines = [lines[+this.data.range - 1]] 23 | else { 24 | const [start, end] = this.data.range.split('-').map((r: string) => +r) 25 | lines = lines.slice(start - 1, end) 26 | } 27 | 28 | const md = lines.map(l => `

${l}

\n`).join('') 29 | 30 | return md 31 | } 32 | } -------------------------------------------------------------------------------- /docker-compose.dev.yml: -------------------------------------------------------------------------------- 1 | services: 2 | dynamic-readme: 3 | container_name: dr-dev-app 4 | restart: unless-stopped 5 | develop: 6 | watch: 7 | - action: sync 8 | path: . 9 | target: /usr/src/app 10 | volumes: 11 | - ./config.json:/usr/src/app/config.json 12 | build: 13 | context: . 14 | dockerfile: Dockerfile 15 | env_file: 16 | - .env.dev 17 | environment: 18 | - NODE_ENV=development 19 | # - NO_COMMIT=true 20 | command: npm run start:dev 21 | ports: 22 | - 3000:${APP_PORT} 23 | networks: 24 | - app-network 25 | depends_on: 26 | - redis-dev 27 | redis-dev: 28 | container_name: dr-dev-redis 29 | restart: unless-stopped 30 | image: redis:alpine 31 | ports: 32 | - 6379:6379 33 | volumes: 34 | - redis-data:/data 35 | networks: 36 | - app-network 37 | 38 | volumes: 39 | redis-data: 40 | networks: 41 | app-network: -------------------------------------------------------------------------------- /src/modules/index.ts: -------------------------------------------------------------------------------- 1 | export { 2 | AbstractModule, 3 | AbstractDynamicModule, 4 | AbstractStaticModule, 5 | } from "./abstract.module" 6 | 7 | export { GbaDynamicModule } from "./dynamics/gba.module" 8 | export { FollowersDynamicModule } from "./dynamics/followers.module" 9 | export { GeneratedDynamicModule } from "./dynamics/generated.module" 10 | export { WordleDynamicModule } from "./dynamics/wordle.module" 11 | export { ChessDynamicModule } from "./dynamics/chess.module" 12 | 13 | export { ElementStaticModule } from "./statics/element.module" 14 | export { GreetingStaticModule } from "./statics/greeting.module" 15 | export { LinesStaticModule } from "./statics/lines.module" 16 | export { ListStaticModule } from "./statics/list.module" 17 | export { ProfileViewsStaticModule } from "./statics/profile-views.module" 18 | export { RawStaticModule } from "./statics/raw.module" 19 | export { SkillsStaticModule } from "./statics/skills.module" 20 | export { SocialsStaticModule } from "./statics/socials.module" 21 | export { TriggerStaticModule } from "./statics/trigger.module" -------------------------------------------------------------------------------- /public/client.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Document 7 | 8 | 9 | 10 | 11 |
12 |
13 | 14 | 15 | 16 | 17 |
18 |
19 | 20 | 21 |
22 |
23 | 24 | 25 |
26 |
27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /src/games/sudoku/sudoku.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get, Res } from '@nestjs/common'; 2 | import { SudokuService } from './sudoku.service'; 3 | import { Response } from 'express'; 4 | import { ConfigService } from '@nestjs/config'; 5 | 6 | @Controller('sudoku') 7 | export class SudokuController { 8 | constructor( 9 | private configService: ConfigService, 10 | private sudokuService: SudokuService 11 | ) {} 12 | 13 | @Get('new') 14 | new(@Res() res: Response) { 15 | const config = this.configService.getOrThrow('config') 16 | this.sudokuService.new() 17 | // await this.readmeService.commit(':1234: Reset sudoku') 18 | res.status(200) 19 | res.redirect(config.datas.repo.url + '#a-classic-sudoku') 20 | } 21 | 22 | @Get('number') 23 | number(@Res() res: Response) { 24 | const config = this.configService.getOrThrow('config') 25 | this.sudokuService.new() 26 | // await this.readmeService.commit(':1234: Update sudoku') 27 | res.status(200) 28 | res.redirect(config.datas.repo.url + '#a-classic-sudoku') 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/games/minesweeper/minesweeper.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, 2 | Get, 3 | Header, 4 | Param, 5 | Query, 6 | Res 7 | } from '@nestjs/common'; 8 | import { Response } from 'express'; 9 | import { MinesweeperService } from './minesweeper.service'; 10 | 11 | @Controller('minesweeper') 12 | export class MinesweeperController { 13 | constructor( 14 | private minesweeperService: MinesweeperService 15 | ) {} 16 | @Get(':id/new') 17 | async new( 18 | @Param('id') id: string, 19 | @Res() res: Response 20 | ) { 21 | return this.minesweeperService.new(id, res) 22 | } 23 | 24 | @Get(':id/click') 25 | async click( 26 | @Param('id') id: string, 27 | @Query('x') x: string, 28 | @Query('y') y: string, 29 | @Res() res: Response 30 | ){ 31 | return this.minesweeperService.click(id, +x, +y, res) 32 | } 33 | 34 | @Get(':id/gif') 35 | @Header('Cache-Control', 'public, max-age=0') 36 | @Header('Content-Type', 'image/gif') 37 | async gif( 38 | @Param('id') id: string, 39 | @Res() res: Response 40 | ){ 41 | return this.minesweeperService.gif(id, res) 42 | } 43 | } -------------------------------------------------------------------------------- /src/services/ConfigService.ts: -------------------------------------------------------------------------------- 1 | import { ConfigService } from '@nestjs/config' 2 | import { Injectable } from '@nestjs/common' 3 | import { RedisService } from '../redis/redis.service' 4 | 5 | @Injectable() 6 | export class AppConfigService { 7 | public static instance: ConfigService 8 | public static redis: RedisService 9 | public static APP_BASE_URL: string 10 | 11 | constructor( 12 | public readonly configService: ConfigService, 13 | public readonly redis: RedisService 14 | ) { 15 | AppConfigService.instance = configService 16 | AppConfigService.redis = redis 17 | AppConfigService.APP_BASE_URL = AppConfigService.getOrThrow("APP_BASE_URL") 18 | } 19 | 20 | static get(key: string): T { 21 | if (!AppConfigService.instance) { 22 | throw new Error('ConfigService not initialized yet') 23 | } 24 | return AppConfigService.instance.get(key) 25 | } 26 | 27 | static getOrThrow(key: string): T { 28 | if (!AppConfigService.instance) { 29 | throw new Error('ConfigService not initialized yet') 30 | } 31 | return AppConfigService.instance.getOrThrow(key) 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/games/chess/chess.controller.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Controller, 3 | Get, 4 | Header, 5 | Param, 6 | Query, 7 | Res 8 | } from '@nestjs/common'; 9 | import { ChessService } from './chess.service'; 10 | import { Response } from 'express' 11 | import { ChessCoordinates } from './declarations'; 12 | 13 | @Controller('chess') 14 | export class ChessController { 15 | constructor( 16 | private chessService: ChessService 17 | ) { } 18 | @Get(':id/new') 19 | async new( 20 | @Param('id') id: string, 21 | @Res() res: Response 22 | ) { 23 | return this.chessService.new(id, res) 24 | } 25 | 26 | @Get(':id/move') 27 | async move( 28 | @Param('id') id: string, 29 | @Query('from') from: ChessCoordinates, 30 | @Query('to') to: ChessCoordinates, 31 | @Res() res: Response, 32 | ) { 33 | return this.chessService.move(id, { from, to }, res) 34 | } 35 | 36 | @Get(':id/board') 37 | @Header('Content-Type', 'image/png') 38 | @Header('Cache-Control', 'public, max-age=0') 39 | board( 40 | @Param('id') id: string, 41 | @Res() res: Response 42 | ) { 43 | return this.chessService.board(id, res) 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/trigger/trigger.controller.ts: -------------------------------------------------------------------------------- 1 | import * as fs from 'fs/promises' 2 | import { Controller, 3 | Get, 4 | Header, 5 | OnModuleInit, 6 | Res 7 | } from '@nestjs/common'; 8 | import { Response } from 'express'; 9 | import { 10 | ReadmeService, 11 | RequestService 12 | } from 'src/services'; 13 | 14 | @Controller('trigger') 15 | export class TriggerController implements OnModuleInit { 16 | private triggerImageBuffer: Buffer 17 | async onModuleInit() { 18 | this.triggerImageBuffer = await fs.readFile('./public/trigger.webp') 19 | } 20 | 21 | @Get() 22 | @Header('Content-Type', 'image/webp') 23 | @Header('Cache-Control', 'public, max-age=0') 24 | trigger(@Res() res: Response) { 25 | // return as soon as possible 26 | RequestService.getFollowers(3).then((followers) => { 27 | if(JSON.stringify(followers) !== JSON.stringify(RequestService.lastFollowers)) { 28 | RequestService.lastFollowers = followers 29 | ReadmeService.renderCommitAndPush(':alarm_clock: Update followers table') 30 | } 31 | }) 32 | return res.send(this.triggerImageBuffer) 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/games/wordle/wordle.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpException, HttpStatus, Injectable } from '@nestjs/common'; 2 | import { WordleDynamicModule } from 'src/modules'; 3 | import State from 'src/State'; 4 | import { ReadmeService } from 'src/services'; 5 | import { Response } from 'express'; 6 | 7 | @Injectable() 8 | export class WordleService { 9 | 10 | async guess( 11 | GH_ACTION_TRUST: string, 12 | guess: string, 13 | issuer: string, 14 | issuerId: number, 15 | res: Response 16 | ) { 17 | 18 | if(GH_ACTION_TRUST !== process.env.GH_ACTION_TRUST) throw new HttpException('Bad Request', HttpStatus.BAD_REQUEST); 19 | if(!guess || guess.length !== 5) throw new HttpException('Bad Request', HttpStatus.BAD_REQUEST); 20 | if(!issuer) throw new HttpException('Bad Request', HttpStatus.BAD_REQUEST); 21 | if(!issuerId) throw new HttpException('Bad Request', HttpStatus.BAD_REQUEST); 22 | console.log('passed') 23 | 24 | const module = State.modules.find( 25 | m => m instanceof WordleDynamicModule 26 | ) 27 | 28 | await module.guess(guess, issuer, issuerId); 29 | 30 | await ReadmeService.updateReadmeAndRedirect(':book: Update wordle', res, "#a-classic-wordle") 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/modules/statics/element.module.ts: -------------------------------------------------------------------------------- 1 | import { AbstractStaticModule } from "../abstract.module"; 2 | 3 | type HTMLParentElement = 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' 4 | type HTMLVoidElement = 'area' | 'base' | 'br' | 'col' | 'embed' | 'hr' | 'img' | 'input' | 'link' | 'meta' | 'param' | 'source' | 'track' | 'wbr' 5 | type HTMLElement = HTMLParentElement | HTMLVoidElement 6 | 7 | function isVoidElement(element: HTMLElement): element is HTMLVoidElement { 8 | const voidElements: HTMLVoidElement[] = [ 9 | 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 10 | 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr' 11 | ] 12 | return voidElements.includes(element as HTMLVoidElement) 13 | } 14 | 15 | interface Data { 16 | element: HTMLElement 17 | content: string 18 | } 19 | 20 | interface Options { 21 | align: 'start' | 'center' | 'end' | 'justify' 22 | } 23 | 24 | export class ElementStaticModule extends AbstractStaticModule { 25 | public render(): string | Promise { 26 | let md = isVoidElement(this.data.element) 27 | ? `<${this.data.element} />` 28 | : `<${this.data.element}${this.options?.align ? ` align="${this.options?.align}"` : `` }>${this.data.content}\n` 29 | this.md = md 30 | return md 31 | } 32 | } -------------------------------------------------------------------------------- /src/games/gameboy/gameboy.controller.ts: -------------------------------------------------------------------------------- 1 | import { Body, Controller, Get, Param, Post, Query, Res } from '@nestjs/common'; 2 | import { Response } from 'express'; 3 | import { GameboyService } from './gameboy.service'; 4 | import { ConfigService } from '@nestjs/config'; 5 | 6 | @Controller('gameboy') 7 | export class GameboyController { 8 | 9 | constructor( 10 | private configService: ConfigService, 11 | private gameboyService: GameboyService 12 | ){} 13 | 14 | @Get('/input') 15 | input(@Query('input') input: string, @Res() res: Response) { 16 | const config = this.configService.getOrThrow('config') 17 | if(input) this.gameboyService.input(input) 18 | res.status(200) 19 | res.redirect(config.datas.repo.url + '#github-plays-pokemon-') 20 | } 21 | 22 | @Get('/save') 23 | save(@Res() res: Response) { 24 | return this.gameboyService.save(res) 25 | } 26 | 27 | @Post('/load') 28 | load(@Body() save) { 29 | this.gameboyService.load(save) 30 | } 31 | 32 | @Get('/doframe') 33 | frame(@Res() res: Response) { 34 | return this.gameboyService.frame(res) 35 | } 36 | 37 | @Get('/dogif') 38 | gif(@Res() res: Response) { 39 | if(!this.gameboyService.lastInputFrames.length) return this.gameboyService.frame(res) 40 | return this.gameboyService.gif(res) 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/games/chess/chess.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { Response } from 'express'; 3 | import { MoveInstruction } from './declarations'; 4 | import State from 'src/State'; 5 | import ReadmeService from 'src/services/ReadmeService'; 6 | import { ChessDynamicModule } from 'src/modules'; 7 | 8 | @Injectable() 9 | export class ChessService { 10 | 11 | async new(id: string, res?: Response) { 12 | const module = State.modules.find( 13 | m => m.data['uuid'] === id 14 | ) as ChessDynamicModule 15 | 16 | await module.new() 17 | 18 | await ReadmeService.updateReadmeAndRedirect(':chess_pawn: Reset chess', res, '#a-classic-chess') 19 | } 20 | 21 | async move(id: string, move: MoveInstruction, res: Response) { 22 | 23 | const module = State.modules.find( 24 | m => m.data['uuid'] === id 25 | ) as ChessDynamicModule 26 | 27 | if(await module.move(move)) 28 | await ReadmeService.updateReadmeAndRedirect(':chess_pawn: Update chess', res, '#a-classic-chess') 29 | else ReadmeService.doNothingAndRedirect(res, '#a-classic-chess') 30 | } 31 | 32 | async board(id: string, res: Response) { 33 | const module = State.modules.find( 34 | m => m.data['uuid'] === id 35 | ) as ChessDynamicModule 36 | 37 | return res.send(await module.getBoardBuffer()) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/modules/statics/trigger.module.ts: -------------------------------------------------------------------------------- 1 | import { AppConfigService } from "src/services"; 2 | import { AbstractStaticModule } from "../abstract.module"; 3 | import { AppConfig } from "src/declaration"; 4 | 5 | interface Data { 6 | } 7 | 8 | interface Options { 9 | } 10 | 11 | export class TriggerStaticModule extends AbstractStaticModule { 12 | public render(): string | Promise { 13 | const owner = AppConfigService.getOrThrow('config.datas.repo.owner'); 14 | const env = AppConfigService.getOrThrow('NODE_ENV'); 15 | const BASE_URL = env === 'production' 16 | ? AppConfigService.APP_BASE_URL 17 | : "http://localhost:3000" 18 | let md = '' 19 | md += `

Work in progress

\n`; 20 | md += `

Other features are in progress, feel free to follow me to discover them.

\n`; 21 | md += `

To understand how it works, take a look here

\n`; 22 | md += `

\n work in progress\n

\n`; 23 | md += `

\n See ya <3\n

\n`; 24 | return md 25 | } 26 | } -------------------------------------------------------------------------------- /src/games/gba/gba.controller.ts: -------------------------------------------------------------------------------- 1 | import { Response } from 'express'; 2 | import { 3 | Controller, 4 | Get, 5 | Header, 6 | Param, 7 | Post, 8 | Query, 9 | Req, 10 | Res, 11 | UploadedFile, 12 | UseInterceptors 13 | } from '@nestjs/common'; 14 | import { GbaService } from './gba.service'; 15 | import { FileInterceptor } from '@nestjs/platform-express'; 16 | 17 | @Controller('gba') 18 | export class GbaController { 19 | 20 | constructor( 21 | private gbaService: GbaService, 22 | ){} 23 | 24 | @Get(':id/input') 25 | input( 26 | @Param('id') id: string, 27 | @Query('input') input: string, 28 | @Res() res: Response, 29 | ) { 30 | return this.gbaService.input(id, +input, res) 31 | } 32 | 33 | @Get(':id/save') 34 | async save( 35 | @Param() id: string, 36 | @Res() res: Response 37 | ) { 38 | return await this.gbaService.save(id, res) 39 | } 40 | 41 | @Post(':id/load') 42 | @UseInterceptors(FileInterceptor('file')) 43 | async load( 44 | @Param('id') id: string, 45 | @UploadedFile() file: any, 46 | ) { 47 | return await this.gbaService.load(id, file) 48 | } 49 | 50 | @Get('/:id/gif') 51 | @Header('Cache-Control', 'public, max-age=0') 52 | @Header('Content-Type', 'image/gif') 53 | gif( 54 | @Param('id') id: string 55 | ) { 56 | return this.gbaService.gif(id) 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/games/minesweeper/minesweeper.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable} from '@nestjs/common'; 2 | import { MinesweeperDynamicModule } from 'src/modules/dynamics/minesweeper.module'; 3 | import State from 'src/State'; 4 | import ReadmeService from 'src/services/ReadmeService'; 5 | import { Response } from 'express'; 6 | 7 | @Injectable() 8 | export class MinesweeperService { 9 | 10 | async new(id: string, res: Response) { 11 | 12 | const module = State.modules.find( 13 | m => m.data['uuid'] === id 14 | ) as MinesweeperDynamicModule 15 | 16 | await module.new() 17 | await ReadmeService.updateReadmeAndRedirect(':boom: Reset minesweeper', res, '#a-classic-minesweeper') 18 | } 19 | 20 | async click(id: string, x: number, y:number, res: Response) { 21 | const module = State.modules.find( 22 | m => m.data['uuid'] === id 23 | ) as MinesweeperDynamicModule 24 | 25 | const shouldCommit = await module.click(x, y) 26 | if(shouldCommit) await ReadmeService.updateReadmeAndRedirect(':boom: Update minesweeper', res, '#a-classic-minesweeper') 27 | else ReadmeService.doNothingAndRedirect(res, '#a-classic-minesweeper') 28 | } 29 | 30 | async gif(id: string, res: Response) { 31 | const module = State.modules.find( 32 | m => m.data['uuid'] === id 33 | ) as MinesweeperDynamicModule 34 | 35 | return res.send(await module.gif()) 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/auth/auth.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get, Param, Query } from '@nestjs/common'; 2 | import { JwtService } from '@nestjs/jwt'; 3 | import axios from 'axios'; 4 | import { RedisService } from 'src/redis/redis.service'; 5 | 6 | @Controller('auth') 7 | export class AuthController { 8 | 9 | constructor(private jwtService: JwtService, private redis: RedisService){} 10 | 11 | @Get('/auth') 12 | async auth(@Query('code') code: string) { 13 | const access = await axios.get(`https://github.com/login/oauth/access_token?client_id=${process.env.GH_APP_CLIENT_ID}&client_secret=${process.env.GH_APP_CLIENT_SECRET_ID}&code=${code}`, { headers: { Accept: "application/json" } }) 14 | const user = await axios.get("https://api.github.com/user", { headers: { Authorization: `Bearer ${access.data.access_token}` } }) 15 | console.log(user.data) 16 | 17 | const { id, login, avatar_url } = user.data 18 | 19 | const userData = { 20 | id, 21 | login, 22 | avatar_url, 23 | created_at: new Date().toISOString() 24 | } 25 | 26 | try { 27 | const existingUser = await this.redis.client.hGet(`user:${id}`, 'id') 28 | 29 | if(!existingUser) await this.redis.client.hSet(`user:${id}`, userData) 30 | } catch(e) { 31 | console.log(e) 32 | } 33 | 34 | return { 35 | access_token: await this.jwtService.signAsync(userData), 36 | }; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/modules/dynamics/followers.module.ts: -------------------------------------------------------------------------------- 1 | import { RequestService } from "src/services"; 2 | import { AbstractDynamicModule } from "../abstract.module"; 3 | 4 | interface Data { 5 | } 6 | 7 | interface Options { 8 | } 9 | 10 | export class FollowersDynamicModule extends AbstractDynamicModule { 11 | ALWAYS_RERENDER = true 12 | 13 | public render(): string | Promise { 14 | 15 | const followers = RequestService.lastFollowers 16 | 17 | let returnString = ''; 18 | returnString += `\n \n \n \n \n \n \n`; 19 | returnString += JSON.parse(JSON.stringify(followers.lastFollowers)).reverse().map((follower, index) => { 20 | return ` \n \n \n \n \n`; 21 | }).join(''); 22 | returnString += ` \n \n \n `; 23 | returnString += `\n \n
Last Followers
${followers.followerCount - (followers.lastFollowers.length - index - 1)}\n \n ${follower.login}\n \n \n ${follower.login}\n
${followers.followerCount + 1}Maybe You ? (can take a few minutes to update)
\n`; 24 | 25 | return returnString 26 | } 27 | } -------------------------------------------------------------------------------- /src/games/games.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { MinesweeperService } from './minesweeper/minesweeper.service'; 3 | import { MinesweeperController } from './minesweeper/minesweeper.controller'; 4 | import { ChessService } from './chess/chess.service'; 5 | import { ChessController } from './chess/chess.controller'; 6 | import { WordleService } from './wordle/wordle.service'; 7 | import { WordleController } from './wordle/wordle.controller'; 8 | import { RedisModule } from 'src/redis/redis.module'; 9 | import { GameboyController } from './gameboy/gameboy.controller'; 10 | import { GameboyService } from './gameboy/gameboy.service'; 11 | import { GameboyGateway } from './gameboy/gameboy.gateway'; 12 | import { AuthModule } from 'src/auth/auth.module'; 13 | 14 | import { GbaService } from './gba/gba.service'; 15 | import { GbaController } from './gba/gba.controller'; 16 | import { AppConfigService } from 'src/services'; 17 | 18 | @Module({ 19 | imports: [ 20 | RedisModule, 21 | AuthModule 22 | ], 23 | controllers: [ 24 | MinesweeperController, 25 | ChessController, 26 | WordleController, 27 | // GameboyController, 28 | GbaController 29 | ], 30 | providers: [ 31 | MinesweeperService, 32 | ChessService, 33 | WordleService, 34 | // GameboyService, 35 | // GameboyGateway, 36 | GbaService, 37 | AppConfigService, 38 | ], 39 | exports: [ 40 | MinesweeperService, 41 | ChessService, 42 | WordleService, 43 | // GameboyService, 44 | GbaService 45 | ] 46 | }) 47 | export class GamesModule {} 48 | -------------------------------------------------------------------------------- /src/app.module.ts: -------------------------------------------------------------------------------- 1 | import * as fs from 'fs/promises' 2 | import { join } from 'path'; 3 | import { Module, OnModuleInit } from '@nestjs/common'; 4 | import { ServeStaticModule } from '@nestjs/serve-static'; 5 | import { ConfigModule } from '@nestjs/config'; 6 | import { AppController } from './app.controller'; 7 | import { AppService } from './app.service'; 8 | import { GamesModule } from './games/games.module'; 9 | import { TriggerModule } from './trigger/trigger.module'; 10 | import { ScheduleModule } from '@nestjs/schedule'; 11 | import { RedisModule } from './redis/redis.module'; 12 | import { AuthModule } from './auth/auth.module'; 13 | import { UsersModule } from './users/users.module'; 14 | import State from './State'; 15 | import { ConfigSchema } from './zod.zodobject'; 16 | import { AppConfigService, RequestService } from './services'; 17 | 18 | @Module({ 19 | imports: [ 20 | ConfigModule.forRoot({ 21 | isGlobal: true, 22 | cache: true, 23 | load: [ 24 | async () => { 25 | const unsafe_config = JSON.parse((await fs.readFile('./config.json')).toString()) 26 | const config = ConfigSchema.parse(unsafe_config) 27 | return { config } 28 | } 29 | ] 30 | }), 31 | ScheduleModule.forRoot(), 32 | GamesModule, 33 | TriggerModule, 34 | ServeStaticModule.forRoot({ 35 | rootPath: join(__dirname, '..', 'public'), 36 | }), 37 | RedisModule, 38 | AuthModule, 39 | UsersModule, 40 | ], 41 | controllers: [AppController], 42 | providers: [ 43 | AppService, 44 | AppConfigService, 45 | ], 46 | }) 47 | export class AppModule implements OnModuleInit { 48 | async onModuleInit() { 49 | await Promise.all([ 50 | RequestService.init(), 51 | State.init(), 52 | ]) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/games/chess/classes/Rook.ts: -------------------------------------------------------------------------------- 1 | import { utils } from './utils'; 2 | import { Piece } from './Piece'; 3 | 4 | export class Rook extends Piece { 5 | type = 'Rook' 6 | uniqueInitial= 'r'; 7 | 8 | computeLegalMoves(chessInstance, board) { 9 | this.legalMoves = []; 10 | // TODO Check discover check 11 | // TODO Check borders 12 | // TODO Check piece devant 13 | for(let x = this.x - 1; x >= 0; x--) { 14 | if(board[this.y][x]?.color === (this.color === 'white' ? 'white' : 'black')) break; 15 | this.legalMoves.push({x: x, y: this.y}) 16 | if(board[this.y][x]?.color === (this.color === 'white' ? 'black' : 'white')) break; 17 | } 18 | for(let x = this.x + 1; x <= 7; x++) { 19 | if(board[this.y][x]?.color === (this.color === 'white' ? 'white' : 'black')) break; 20 | this.legalMoves.push({x: x, y: this.y}) 21 | if(board[this.y][x]?.color === (this.color === 'white' ? 'black' : 'white')) break; 22 | } 23 | 24 | for(let y = this.y - 1; y >= 0; y--) { 25 | if(board[y][this.x]?.color === (this.color === 'white' ? 'white' : 'black')) break; 26 | this.legalMoves.push({x: this.x, y: y}) 27 | if(board[y][this.x]?.color === (this.color === 'white' ? 'black' : 'white')) break; 28 | } 29 | for(let y = this.y + 1; y <= 7; y++) { 30 | if(board[y][this.x]?.color === (this.color === 'white' ? 'white' : 'black')) break; 31 | this.legalMoves.push({x: this.x, y: y}) 32 | if(board[y][this.x]?.color === (this.color === 'white' ? 'black' : 'white')) break; 33 | } 34 | 35 | if(chessInstance.simulationState) return 36 | chessInstance.simulationState = true 37 | this.legalMoves = utils.filterPin(this.legalMoves, {x: this.x, y: this.y}, board, chessInstance) 38 | chessInstance.simulationState = false 39 | } 40 | } -------------------------------------------------------------------------------- /src/services/RequestService.ts: -------------------------------------------------------------------------------- 1 | import axios from 'axios'; 2 | import { AppConfigService } from './ConfigService'; 3 | 4 | class RequestService { 5 | public lastFollowers: {followerCount: number, lastFollowers: {login: string, avatarUrl: string}[]} = {followerCount: 0, lastFollowers: []} 6 | 7 | constructor() {} 8 | 9 | async init() { 10 | this.lastFollowers = await this.getFollowers(3) 11 | } 12 | 13 | async getFollowers(limit: number): Promise<{followerCount: number, lastFollowers: {login: string, avatarUrl: string}[]}> { 14 | const config = AppConfigService.getOrThrow('config') 15 | try { 16 | const query = ` 17 | query { 18 | user(login: "${config.datas.repo.owner}") { 19 | totalCount: followers { 20 | totalCount 21 | } 22 | followers(first: ${limit}) { 23 | nodes { 24 | login 25 | avatarUrl 26 | } 27 | } 28 | } 29 | }`; 30 | const response = await axios.post('https://api.github.com/graphql', { query }, { 31 | headers: { 32 | Authorization: `Bearer ${process.env.GH_TOKEN}`, 33 | }, 34 | }); 35 | return { 36 | followerCount: response.data.data.user.totalCount.totalCount, 37 | lastFollowers: response.data.data.user.followers.nodes 38 | } 39 | } catch (error) { 40 | console.error(error) 41 | return {followerCount: 0, lastFollowers: []} 42 | } 43 | } 44 | } 45 | 46 | export default new RequestService() -------------------------------------------------------------------------------- /src/modules/abstract.module.ts: -------------------------------------------------------------------------------- 1 | import { Logger } from "@nestjs/common" 2 | import { randomUUID } from "crypto" 3 | import { AppConfigService } from "src/services" 4 | 5 | export abstract class AbstractModule, Options = Record> { 6 | public data: Data 7 | protected options: Options 8 | protected md: string 9 | constructor(data: Data, options: Options = {} as Options) { 10 | this.data = data 11 | this.options = options 12 | } 13 | public abstract render(): string | Promise 14 | public abstract toMd(): Promise 15 | } 16 | 17 | export abstract class AbstractStaticModule, Options = Record> extends AbstractModule{ 18 | public async toMd(): Promise { 19 | if(this.md) return this.md 20 | const md = await this.render() 21 | this.md = md 22 | return md 23 | } 24 | } 25 | 26 | export abstract class AbstractDynamicModule, Options = Record> extends AbstractModule{ 27 | ALWAYS_RERENDER = false 28 | 29 | needsRender: boolean = true 30 | id: string 31 | protected readonly logger: Logger 32 | 33 | constructor(data: Data, options?: Options) { 34 | super(data, options) 35 | this.id = randomUUID() 36 | this.logger = new Logger(`${this.constructor.name}`) 37 | } 38 | 39 | public init(): Promise { 40 | return 41 | } 42 | 43 | public async toMd() { 44 | if(this.ALWAYS_RERENDER) { 45 | if(AppConfigService.getOrThrow('NODE_ENV') === "development") 46 | this.logger.verbose(`Rendering (always) module ${this.id}`) 47 | 48 | return await this.render() 49 | } 50 | if(!this.needsRender && this.md) return this.md 51 | if(AppConfigService.getOrThrow('NODE_ENV') === "development") 52 | this.logger.verbose(`Rendering module ${this.id}`) 53 | const md = await this.render() 54 | this.md = md 55 | this.needsRender = false 56 | return md 57 | } 58 | } -------------------------------------------------------------------------------- /src/games/chess/classes/Bishop.ts: -------------------------------------------------------------------------------- 1 | import { Piece } from './Piece' 2 | import { utils } from './utils' 3 | 4 | export class Bishop extends Piece { 5 | type = 'Bishop' 6 | uniqueInitial= 'b'; 7 | 8 | computeLegalMoves(chessInstance, board) { 9 | this.legalMoves = []; 10 | // TODO Check discover check 11 | // TODO Check borders 12 | // TODO Check piece devant 13 | let caseCoords = {x: this.x, y: this.y} 14 | // top left 15 | while(--caseCoords.x >= 0 && --caseCoords.y >= 0) { 16 | if(board[caseCoords.y][caseCoords.x]?.color === (this.color === 'white' ? 'white' : 'black')) break; 17 | this.legalMoves.push({...caseCoords}) 18 | if(board[caseCoords.y][caseCoords.x]?.color === (this.color === 'white' ? 'black' : 'white')) break; 19 | } 20 | 21 | caseCoords = {x: this.x, y: this.y} 22 | // bottom right 23 | while(++caseCoords.x <= 7 && ++caseCoords.y <= 7) { 24 | if(board[caseCoords.y][caseCoords.x]?.color === (this.color === 'white' ? 'white' : 'black')) break; 25 | this.legalMoves.push({...caseCoords}) 26 | if(board[caseCoords.y][caseCoords.x]?.color === (this.color === 'white' ? 'black' : 'white')) break; 27 | } 28 | 29 | 30 | caseCoords = {x: this.x, y: this.y} 31 | // top right 32 | while(++caseCoords.x <= 7 && --caseCoords.y >= 0) { 33 | if(board[caseCoords.y][caseCoords.x]?.color === (this.color === 'white' ? 'white' : 'black')) break; 34 | this.legalMoves.push({...caseCoords}) 35 | if(board[caseCoords.y][caseCoords.x]?.color === (this.color === 'white' ? 'black' : 'white')) break; 36 | } 37 | 38 | caseCoords = {x: this.x, y: this.y} 39 | // bottom left 40 | while(--caseCoords.x >= 0 && ++caseCoords.y <= 7) { 41 | if(board[caseCoords.y][caseCoords.x]?.color === (this.color === 'white' ? 'white' : 'black')) break; 42 | this.legalMoves.push({...caseCoords}) 43 | if(board[caseCoords.y][caseCoords.x]?.color === (this.color === 'white' ? 'black' : 'white')) break; 44 | } 45 | 46 | if(chessInstance.simulationState) return 47 | chessInstance.simulationState = true 48 | this.legalMoves = utils.filterPin(this.legalMoves, {x: this.x, y: this.y}, board, chessInstance) 49 | chessInstance.simulationState = false 50 | } 51 | } -------------------------------------------------------------------------------- /src/modules/statics/skills.module.ts: -------------------------------------------------------------------------------- 1 | import { AppConfigService } from "src/services"; 2 | import { AbstractStaticModule } from "../abstract.module"; 3 | import { AppConfig } from "src/declaration"; 4 | 5 | interface Data { 6 | } 7 | 8 | interface Options { 9 | align: "start" | "center" | "end" 10 | } 11 | 12 | export class SkillsStaticModule extends AbstractStaticModule { 13 | public render(): string | Promise { 14 | const skills = AppConfigService.getOrThrow('config.datas.skills'); 15 | let md = '' 16 | 17 | md += `

Technical skills

\n`; 18 | if(skills.learning) { 19 | md += `

Currently learning:\n`; 20 | md += skills.learning.list.map((skill) => { 21 | return ` \n ${skill.alt}\n \n`; 22 | }).join(''); 23 | md += `

\n`; 24 | } 25 | 26 | // Front 27 | md += `

Front-end technologies

\n

\n`; 28 | md += skills.front.list.map((skill) => { 29 | return ` \n ${skill.alt}\n \n`; 30 | }).join(''); 31 | md += `

\n`; 32 | 33 | // Back 34 | md += `

Back-end technologies

\n

\n`; 35 | md += skills.back.list.map((skill) => { 36 | return ` \n ${skill.alt}\n \n`; 37 | }).join(''); 38 | md += `

\n`; 39 | 40 | // Notions 41 | md += `

Other technologies where I have notions

\n

\n`; 42 | md += skills.notions.list.map((skill) => { 43 | return ` \n ${skill.alt}\n \n`; 44 | }).join(''); 45 | md += `

\n`; 46 | 47 | // Tools 48 | md += `

Tools

\n

\n`; 49 | md += skills.tools.list.map((skill) => { 50 | return ` \n ${skill.alt}\n \n`; 51 | }).join(''); 52 | md += `

\n`; 53 | 54 | return md 55 | } 56 | } -------------------------------------------------------------------------------- /src/games/chess/classes/Knight.ts: -------------------------------------------------------------------------------- 1 | import { Piece } from './Piece'; 2 | import { utils } from './utils'; 3 | 4 | export class Knight extends Piece { 5 | type = 'Knight' 6 | uniqueInitial = 'n' 7 | 8 | computeLegalMoves(chessInstance, board) { 9 | this.legalMoves = []; 10 | // TODO Check discover check 11 | // TODO Check borders 12 | // TODO Check piece devant 13 | if(this.y + 2 <= 7) { 14 | if(this.x - 1 >= 0) { 15 | if(!(utils.getPiece({x: this.x - 1, y: this.y + 2}, board)?.color === this.color)) this.legalMoves.push({x: this.x - 1, y: this.y + 2}) 16 | } 17 | if(this.x + 1 <= 7) { 18 | if(!(utils.getPiece({x: this.x + 1, y: this.y + 2}, board)?.color === this.color)) this.legalMoves.push({x: this.x + 1, y: this.y + 2}) 19 | } 20 | } 21 | 22 | if(this.y - 2 >= 0) { 23 | if(this.x - 1 >= 0) { 24 | if(!(utils.getPiece({x: this.x - 1, y: this.y - 2}, board)?.color === this.color)) this.legalMoves.push({x: this.x - 1, y: this.y - 2}) 25 | } 26 | if(this.x + 1 <= 7) { 27 | if(!(utils.getPiece({x: this.x + 1, y: this.y - 2}, board)?.color === this.color)) this.legalMoves.push({x: this.x + 1, y: this.y - 2}) 28 | } 29 | } 30 | 31 | if(this.x - 2 >= 0) { 32 | if(this.y - 1 >= 0) { 33 | if(!(utils.getPiece({x: this.x - 2, y: this.y - 1}, board)?.color === this.color)) this.legalMoves.push({x: this.x - 2, y: this.y - 1}) 34 | } 35 | if(this.y + 1 <= 7) { 36 | if(!(utils.getPiece({x: this.x - 2, y: this.y + 1}, board)?.color === this.color)) this.legalMoves.push({x: this.x - 2, y: this.y + 1}) 37 | } 38 | } 39 | 40 | if(this.x + 2 <= 7) { 41 | if(this.y - 1 >= 0) { 42 | if(!(utils.getPiece({x: this.x + 2, y: this.y - 1}, board)?.color === this.color)) this.legalMoves.push({x: this.x + 2, y: this.y - 1}) 43 | } 44 | if(this.y + 1 <= 7) { 45 | if(!(utils.getPiece({x: this.x + 2, y: this.y + 1}, board)?.color === this.color)) this.legalMoves.push({x: this.x + 2, y: this.y + 1}) 46 | } 47 | } 48 | 49 | if(chessInstance.simulationState) return 50 | chessInstance.simulationState = true 51 | this.legalMoves = utils.filterPin(this.legalMoves, {x: this.x, y: this.y}, board, chessInstance) 52 | chessInstance.simulationState = false 53 | } 54 | } -------------------------------------------------------------------------------- /public/css/style.css: -------------------------------------------------------------------------------- 1 | * { 2 | margin: 0; 3 | padding: 0; 4 | box-sizing: border-box; 5 | font-family: sans-serif; 6 | } 7 | 8 | body { 9 | display: flex; 10 | flex-flow: column; 11 | flex-direction: column; 12 | align-items: center; 13 | height: 100vh; 14 | background-color: #9c98af; 15 | } 16 | body #mainCanvas { 17 | image-rendering: pixelated; 18 | background-color: #000; 19 | aspect-ratio: 160/144; 20 | width: 100%; 21 | } 22 | body .controls { 23 | flex: 1 1 auto; 24 | background-color: #d9d9d9; 25 | position: relative; 26 | padding: 2rem; 27 | width: 100%; 28 | } 29 | body .controls .cross { 30 | position: absolute; 31 | left: 2rem; 32 | top: 50%; 33 | transform: translateY(-50%); 34 | width: 192px; 35 | aspect-ratio: 1; 36 | } 37 | body .controls .cross button { 38 | position: absolute; 39 | height: 64px; 40 | aspect-ratio: 1; 41 | border: none; 42 | background-color: #222222; 43 | border-radius: 50%; 44 | } 45 | body .controls .cross button.up { 46 | top: 0; 47 | left: 50%; 48 | transform: translateX(-50%); 49 | } 50 | body .controls .cross button.down { 51 | bottom: 0; 52 | left: 50%; 53 | transform: translateX(-50%); 54 | } 55 | body .controls .cross button.left { 56 | top: 50%; 57 | left: 0; 58 | transform: translateY(-50%); 59 | } 60 | body .controls .cross button.right { 61 | top: 50%; 62 | right: 0; 63 | transform: translateY(-50%); 64 | } 65 | body .controls .ab { 66 | position: absolute; 67 | right: 2rem; 68 | top: 50%; 69 | transform: translateY(-50%); 70 | height: 128px; 71 | aspect-ratio: 1; 72 | } 73 | body .controls .ab button { 74 | width: 64px; 75 | aspect-ratio: 1; 76 | border: none; 77 | background-color: #71011a; 78 | border-radius: 50%; 79 | font-size: 20px; 80 | font-weight: bold; 81 | color: white; 82 | position: absolute; 83 | } 84 | body .controls .ab button.a { 85 | top: 0; 86 | right: 0; 87 | } 88 | body .controls .ab button.b { 89 | bottom: 0; 90 | left: 0; 91 | } 92 | body .controls .ss { 93 | position: absolute; 94 | bottom: 2rem; 95 | right: 50%; 96 | transform: translateX(50%); 97 | display: flex; 98 | gap: 1rem; 99 | } 100 | body .controls .ss button { 101 | padding: 0.5rem; 102 | background-color: #9c98af; 103 | color: #373442; 104 | border: none; 105 | border-radius: 4px; 106 | } 107 | 108 | @media screen and (max-width: 480px) { 109 | #mainCanvas { 110 | width: 100%; 111 | height: auto; 112 | } 113 | } 114 | @media screen and (min-width: 480px) { 115 | #mainCanvas { 116 | max-width: 720px; 117 | } 118 | .controls { 119 | max-width: 720px; 120 | } 121 | } 122 | 123 | /*# sourceMappingURL=style.css.map */ 124 | -------------------------------------------------------------------------------- /src/games/gba/gba.service.ts: -------------------------------------------------------------------------------- 1 | import { Readable } from 'stream'; 2 | import { Response } from 'express'; 3 | import { ConfigService } from '@nestjs/config'; 4 | import { Injectable, StreamableFile } from '@nestjs/common'; 5 | import { RedisService } from 'src/redis/redis.service'; 6 | import State from 'src/State'; 7 | import { GbaDynamicModule } from 'src/modules'; 8 | import { ReadmeService } from 'src/services'; 9 | 10 | @Injectable() 11 | export class GbaService { 12 | 13 | constructor( 14 | private readonly redis: RedisService, 15 | private configService: ConfigService 16 | ) {} 17 | 18 | input(id: string, input: number, res: Response) { 19 | const module: GbaDynamicModule = State.modules.find(m => m.data['uuid'] === id) as GbaDynamicModule 20 | module.input(input) 21 | 22 | ReadmeService.doNothingAndRedirect(res, '#f-zodiac-signs-lets-play-pokemon-together') 23 | } 24 | 25 | save(id: string, res: Response) { 26 | const module: GbaDynamicModule = State.modules.find(m => m.data['uuid'] === id) as GbaDynamicModule 27 | return module.save(res) 28 | } 29 | 30 | async load(id: string, file: any) { 31 | const module: GbaDynamicModule = State.modules.find(m => m.data['uuid'] === id) as GbaDynamicModule 32 | return module.load(file.buffer) 33 | } 34 | 35 | gif(id: string) { 36 | const module: GbaDynamicModule = State.modules.find(m => m.data['uuid'] === id) as GbaDynamicModule 37 | return new StreamableFile(Readable.from(module.gifBuffer)); 38 | } 39 | 40 | async renderInputBoard() { 41 | let str = `\n \n` 42 | str += ' \n \n \n' 43 | str += ` \n \n \n \n \n \n \n` 44 | const playersIds = await this.redis.client.keys("gameboy:players:*") 45 | const players = await Promise.all(playersIds.map(player => this.redis.client.hGetAll(player))) 46 | const users = await Promise.all(players.map(player => this.redis.client.hGetAll(`user:${player.id}`))) 47 | const rowsDatas = players.map((player, index) => ({...player, ...users[index]})).sort((a, b) => +b.inputCount - +a.inputCount) 48 | str += rowsDatas.map((row, i) => ` \n \n \n \n \n \n`).join('') 49 | str += ` \n \n \n` 50 | str += ` \n
Game Contributions
RankPlayerInputs
${i + 1}profil picture@${row.login}${row.inputCount}
Play with your Github account here !
\n\n` 51 | 52 | return str 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/games/chess/classes/Pawn.ts: -------------------------------------------------------------------------------- 1 | import { utils } from './utils'; 2 | import { Piece } from './Piece'; 3 | 4 | export class Pawn extends Piece { 5 | type = 'Pawn'; 6 | uniqueInitial = 'p'; 7 | 8 | constructor(x: number, y: number, color: 'black' | 'white', public moved = false, public enPassantPossible = false) { 9 | super(x, y, color) 10 | } 11 | 12 | computeLegalMoves(chessInstance, board) { 13 | this.legalMoves = []; 14 | // TODO Check discover check 15 | // TODO Check borders 16 | // TODO Check en passant 17 | // TODO Check prise de piece 18 | // TODO Check promotion 19 | 20 | // TODO refactor avec direction = +/-1 21 | let direction = this.color === 'white' ? - 1 : 1 22 | 23 | if(!this.moved && !utils.getPiece({x: this.x, y: this.color === 'white' ? this.y - 1 : this.y + 1}, board)) { 24 | if(!utils.getPiece({x: this.x, y: this.color === 'white' ? this.y - 2 : this.y + 2}, board))this.legalMoves.push({x: this.x, y: this.color === 'white' ? this.y - 2 : this.y + 2}) // 'white' = directions des pions 25 | } 26 | if(!utils.getPiece({x: this.x, y: this.color === 'white' ? this.y - 1 : this.y + 1}, board)) this.legalMoves.push({x: this.x, y: this.color === 'white' ? this.y - 1 : this.y + 1}) 27 | if(utils.getPiece({x: this.x + 1, y: this.color === 'white' ? this.y - 1 : this.y + 1}, board)) { 28 | if(utils.getPiece({x: this.x + 1, y: this.color === 'white' ? this.y - 1 : this.y + 1}, board).color !== this.color) this.legalMoves.push({x: this.x + 1, y: this.color === 'white' ? this.y - 1 : this.y + 1}) 29 | } 30 | if(utils.getPiece({x: this.x - 1, y: this.color === 'white' ? this.y - 1 : this.y + 1}, board)) { 31 | if(utils.getPiece({x: this.x - 1, y: this.color === 'white' ? this.y - 1 : this.y + 1}, board).color !== this.color) this.legalMoves.push({x: this.x - 1, y: this.color === 'white' ? this.y - 1 : this.y + 1}) 32 | } 33 | 34 | let enPassantPieceToCheck = utils.getPiece({x: this.x - 1, y: this.y}, board) 35 | if(enPassantPieceToCheck?.type === 'Pawn' && enPassantPieceToCheck?.enPassantPossible && enPassantPieceToCheck?.color !== this.color) { 36 | this.legalMoves.push({x: this.x - 1, y: this.y + direction}) 37 | } 38 | 39 | enPassantPieceToCheck = utils.getPiece({x: this.x + 1, y: this.y}, board) 40 | if(enPassantPieceToCheck?.type === 'Pawn' && enPassantPieceToCheck?.enPassantPossible && enPassantPieceToCheck?.color !== this.color) { 41 | this.legalMoves.push({x: this.x + 1, y: this.y + direction}) 42 | } 43 | 44 | if(chessInstance.simulationState) return 45 | chessInstance.simulationState = true 46 | this.legalMoves = utils.filterPin(this.legalMoves, {x: this.x, y: this.y}, board, chessInstance) 47 | chessInstance.simulationState = false 48 | } 49 | } -------------------------------------------------------------------------------- /public/css/style.scss: -------------------------------------------------------------------------------- 1 | * { 2 | margin: 0; 3 | padding: 0; 4 | box-sizing: border-box; 5 | font-family: sans-serif; 6 | } 7 | 8 | body { 9 | display: flex; 10 | flex-flow: column; 11 | flex-direction: column; 12 | align-items: center; 13 | height: 100vh; 14 | background-color: #9c98af; 15 | 16 | #mainCanvas { 17 | image-rendering: pixelated; 18 | background-color: #000; 19 | aspect-ratio: 160/144; 20 | width: 100%; 21 | } 22 | 23 | .controls { 24 | flex: 1 1 auto; 25 | background-color: #d9d9d9; 26 | position: relative; 27 | padding: 2rem; 28 | width: 100%; 29 | 30 | .cross { 31 | position: absolute; 32 | left: 2rem; 33 | top: 50%; 34 | transform: translateY(-50%); 35 | width: 192px; 36 | aspect-ratio: 1; 37 | 38 | button { 39 | position: absolute; 40 | height: 64px; 41 | aspect-ratio: 1; 42 | border: none; 43 | background-color: #222222; 44 | border-radius: 50%; 45 | 46 | &.up { 47 | top: 0; 48 | left: 50%; 49 | transform: translateX(-50%); 50 | } 51 | &.down { 52 | bottom: 0; 53 | left: 50%; 54 | transform: translateX(-50%); 55 | } 56 | &.left { 57 | top: 50%; 58 | left: 0; 59 | transform: translateY(-50%); 60 | } 61 | &.right { 62 | top: 50%; 63 | right: 0; 64 | transform: translateY(-50%); 65 | } 66 | } 67 | } 68 | 69 | .ab { 70 | position: absolute; 71 | right: 2rem; 72 | top: 50%; 73 | transform: translateY(-50%); 74 | height: 128px; 75 | aspect-ratio: 1; 76 | 77 | button { 78 | width: 64px; 79 | aspect-ratio: 1; 80 | border: none; 81 | background-color: #71011a; 82 | border-radius: 50%; 83 | font-size: 20px; 84 | font-weight: bold; 85 | color: white; 86 | position: absolute; 87 | 88 | &.a { 89 | top: 0; 90 | right: 0; 91 | } 92 | &.b { 93 | bottom: 0; 94 | left: 0; 95 | } 96 | } 97 | } 98 | 99 | .ss { 100 | position: absolute; 101 | bottom: 2rem; 102 | right: 50%; 103 | transform: translateX(50%); 104 | display: flex; 105 | gap: 1rem; 106 | 107 | button { 108 | padding: 0.5rem; 109 | background-color: #9c98af; 110 | color: #373442; 111 | border: none; 112 | border-radius: 4px; 113 | } 114 | } 115 | } 116 | } 117 | 118 | @media screen and (max-width: 480px) { 119 | #mainCanvas { 120 | width: 100%; 121 | height: auto; 122 | } 123 | 124 | } 125 | 126 | @media screen and (min-width: 480px) { 127 | #mainCanvas { 128 | max-width: 720px; 129 | } 130 | 131 | .controls { 132 | max-width: 720px; 133 | } 134 | } -------------------------------------------------------------------------------- /config.example.json: -------------------------------------------------------------------------------- 1 | { 2 | "structure": [ 3 | { 4 | "id": "static/element", 5 | "data": { 6 | "element": "h3", 7 | "content": "Hi there 👋" 8 | } 9 | }, 10 | { 11 | "id": "static/list", 12 | "data": { 13 | "field": "perso.facts" 14 | } 15 | } 16 | ], 17 | "datas": { 18 | "repo": { 19 | "name": "Charles-Chrismann", 20 | "owner": "Charles-Chrismann", 21 | "url": "https://github.com/Charles-Chrismann/Charles-Chrismann/", 22 | "readme": { 23 | "path": "README.md" 24 | }, 25 | "commit": { 26 | "message": ":building_construction: UPDATE README.md" 27 | } 28 | }, 29 | "perso": { 30 | "homepage": "https://github.com/Charles-Chrismann", 31 | "username": "charles-chrismann", 32 | "vueCount": "https://komarev.com/ghpvc/?username=Charles-Chrismann", 33 | "firstname": "Charles", 34 | "lastname": "Chrismann", 35 | "description": [ 36 | "I'm a french student in 2nd year in web development at IIM DigitalSchool in Paris.", 37 | [ 38 | "My list item #1", 39 | "My list item #2" 40 | ] 41 | ], 42 | "facts": { 43 | "content": [ 44 | "🔭 I’m currently working on something cool!", 45 | "🌱 I’m currently learning with help from docs.github.com", 46 | "💬 Ask me about GitHub" 47 | ] 48 | }, 49 | "socials": [ 50 | { 51 | "name": "linkedin", 52 | "profile_url": "https://www.linkedin.com/in/charles-chrismann/", 53 | "icon_url": "https://raw.githubusercontent.com/rahuldkjain/github-profile-readme-generator/master/src/images/icons/Social/linked-in-alt.svg" 54 | } 55 | ] 56 | } 57 | }, 58 | "skills": { 59 | "learning": [], 60 | "front": [ 61 | { 62 | "name": "JavaScript", 63 | "url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript", 64 | "src": "https://raw.githubusercontent.com/devicons/devicon/master/icons/javascript/javascript-original.svg", 65 | "alt": "javascript" 66 | } 67 | ], 68 | "back": [ 69 | { 70 | "name": "Node Js", 71 | "url": "https://nodejs.org", 72 | "src": "https://raw.githubusercontent.com/devicons/devicon/master/icons/nodejs/nodejs-original-wordmark.svg", 73 | "alt": "nodejs" 74 | } 75 | ], 76 | "notions": [ 77 | { 78 | "name": "Nest Js", 79 | "url": "https://nestjs.com/", 80 | "src": "https://raw.githubusercontent.com/devicons/devicon/master/icons/nestjs/nestjs-plain.svg", 81 | "alt": "nestjs" 82 | } 83 | ], 84 | "tools": [ 85 | { 86 | "name": "Git", 87 | "url": "https://git-scm.com/", 88 | "src": "https://www.vectorlogo.zone/logos/git-scm/git-scm-icon.svg", 89 | "alt": "git" 90 | } 91 | ] 92 | } 93 | } -------------------------------------------------------------------------------- /src/State.ts: -------------------------------------------------------------------------------- 1 | import * as fs from 'fs/promises' 2 | import { ConfigSchema } from './zod.zodobject'; 3 | import { 4 | AbstractModule, 5 | ElementStaticModule, 6 | RawStaticModule, 7 | GreetingStaticModule, 8 | ProfileViewsStaticModule, 9 | GbaDynamicModule, 10 | FollowersDynamicModule, 11 | LinesStaticModule, 12 | ListStaticModule, 13 | SkillsStaticModule, 14 | SocialsStaticModule, 15 | GeneratedDynamicModule, 16 | TriggerStaticModule, 17 | WordleDynamicModule, 18 | } from './modules'; 19 | import { MinesweeperDynamicModule } from './modules/dynamics/minesweeper.module'; 20 | import { ChessDynamicModule } from './modules/dynamics/chess.module'; 21 | import { AppConfigService } from './services'; 22 | 23 | type ModuleConstructor = new (data: TData, options?: TOptions) => AbstractModule; 24 | 25 | class State { 26 | public modules: AbstractModule[] = [] 27 | public startRenderDTimestamp: number 28 | 29 | async init(conf?: Record) { 30 | const unsafe_config = conf ?? JSON.parse((await fs.readFile('./config.json')).toString()) 31 | const config = ConfigSchema.parse(unsafe_config) 32 | 33 | const modules = new Map([ 34 | ["static/element", ElementStaticModule], 35 | ["static/raw", RawStaticModule], 36 | ["static/greeting", GreetingStaticModule], 37 | ["static/profile-views", ProfileViewsStaticModule], 38 | ["static/lines", LinesStaticModule], 39 | ["static/list", ListStaticModule], 40 | ["static/socials", SocialsStaticModule], 41 | ["static/skills", SkillsStaticModule], 42 | ["static/trigger", TriggerStaticModule], 43 | ["dynamic/gba", GbaDynamicModule], 44 | ["dynamic/followers", FollowersDynamicModule], 45 | ["dynamic/generated", GeneratedDynamicModule], 46 | ["dynamic/wordle", WordleDynamicModule], 47 | ["dynamic/minesweeper", MinesweeperDynamicModule], 48 | ["dynamic/chess", ChessDynamicModule], 49 | ]) 50 | 51 | const moduleInitPromises = [] 52 | 53 | for(const element of config.structure) { 54 | if("disabled" in element && element.disabled) continue 55 | 56 | const module = modules.get(element.id) 57 | if(!module) { 58 | console.log(`Unknown module: ${element.id}`) 59 | continue 60 | throw new Error(`Unknown module: ${element.id}`) 61 | } 62 | 63 | const data = "data" in element ? element.data : {}; 64 | const options = "options" in element ? element.options : {}; 65 | const createdModule = new module(data, options) 66 | 67 | if("init" in createdModule) moduleInitPromises.push((createdModule.init as Function)()) 68 | 69 | this.modules.push(createdModule) 70 | } 71 | await Promise.all(moduleInitPromises) 72 | } 73 | 74 | async render() { 75 | this.startRenderDTimestamp = Date.now() 76 | const renderPromises: (string | Promise)[] = [] 77 | 78 | for(const module of this.modules) { 79 | renderPromises.push(module.toMd()) 80 | } 81 | 82 | const moduleStr = await Promise.all(renderPromises) 83 | 84 | return moduleStr.join('') 85 | } 86 | } 87 | 88 | export default new State() -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "dynamic-readme-nest", 3 | "version": "0.0.1", 4 | "description": "", 5 | "author": "", 6 | "private": true, 7 | "license": "UNLICENSED", 8 | "scripts": { 9 | "dev": "docker compose -f docker-compose.dev.yml --env-file .env.dev up --watch", 10 | "dk:app:down": "docker compose -f docker-compose.dev.yml --env-file .env.dev down dynamic-readme", 11 | "prod": "docker compose -f docker-compose.prod.yml up --build -d", 12 | "build": "nest build", 13 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", 14 | "start": "nest start", 15 | "start:dev": "nest start --watch", 16 | "start:debug": "nest start --debug --watch", 17 | "start:prod": "node dist/main", 18 | "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", 19 | "test": "jest", 20 | "test:watch": "jest --watch", 21 | "test:cov": "jest --coverage", 22 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", 23 | "test:e2e": "jest --config ./test/jest-e2e.json", 24 | "sass:watch": "sass --watch public/css/style.scss:public/css/style.css" 25 | }, 26 | "dependencies": { 27 | "@napi-rs/canvas": "^0.1.53", 28 | "@nestjs/common": "^10.2.7", 29 | "@nestjs/config": "^3.1.1", 30 | "@nestjs/core": "^10.2.7", 31 | "@nestjs/jwt": "^10.1.1", 32 | "@nestjs/platform-express": "^10.2.7", 33 | "@nestjs/platform-socket.io": "^10.2.7", 34 | "@nestjs/schedule": "^3.0.4", 35 | "@nestjs/serve-static": "^4.0.0", 36 | "@skyra/gifenc": "^1.0.1", 37 | "axios": "^1.4.0", 38 | "chess.js": "^1.4.0", 39 | "compress-json": "^2.1.2", 40 | "cron": "^3.1.6", 41 | "gbats": "^1.0.9", 42 | "lodash-es": "^4.17.21", 43 | "octokit": "^2.0.14", 44 | "redis": "^4.6.10", 45 | "rxjs": "^7.2.0", 46 | "serverboy": "gitlab:piglet-plays/serverboy.js", 47 | "zod": "^4.1.8" 48 | }, 49 | "devDependencies": { 50 | "@nestjs/cli": "^9.0.0", 51 | "@nestjs/schematics": "^9.0.0", 52 | "@nestjs/testing": "^10.2.7", 53 | "@types/express": "^4.17.13", 54 | "@types/gifencoder": "^2.0.1", 55 | "@types/jest": "29.2.4", 56 | "@types/lodash": "^4.14.194", 57 | "@types/lodash-es": "^4.17.7", 58 | "@types/multer": "^2.0.0", 59 | "@types/node": "^18.11.18", 60 | "@types/supertest": "^2.0.11", 61 | "@typescript-eslint/eslint-plugin": "^5.0.0", 62 | "@typescript-eslint/parser": "^5.0.0", 63 | "eslint": "^8.0.1", 64 | "eslint-config-prettier": "^8.3.0", 65 | "eslint-plugin-prettier": "^4.0.0", 66 | "jest": "29.3.1", 67 | "prettier": "^2.3.2", 68 | "source-map-support": "^0.5.20", 69 | "supertest": "^6.1.3", 70 | "ts-jest": "29.0.3", 71 | "ts-loader": "^9.2.3", 72 | "ts-node": "^10.0.0", 73 | "tsconfig-paths": "4.1.1", 74 | "typescript": "^5.9.2" 75 | }, 76 | "jest": { 77 | "moduleFileExtensions": [ 78 | "js", 79 | "json", 80 | "ts" 81 | ], 82 | "rootDir": "src", 83 | "testRegex": ".*\\.spec\\.ts$", 84 | "transform": { 85 | "^.+\\.(t|j)s$": "ts-jest" 86 | }, 87 | "collectCoverageFrom": [ 88 | "**/*.(t|j)s" 89 | ], 90 | "coverageDirectory": "../coverage", 91 | "testEnvironment": "node" 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/games/chess/classes/Queen.ts: -------------------------------------------------------------------------------- 1 | import { utils } from './utils'; 2 | import { Piece } from './Piece'; 3 | 4 | export class Queen extends Piece { 5 | type = 'Queen' 6 | uniqueInitial= 'q'; 7 | 8 | computeLegalMoves(chessInstance, board) { 9 | this.legalMoves = []; 10 | // TODO Check discover check 11 | // TODO Check borders 12 | // TODO Check piece devant 13 | 14 | 15 | for(let x = this.x - 1; x >= 0; x--) { 16 | if(board[this.y][x]?.color === (this.color === 'white' ? 'white' : 'black')) break; 17 | this.legalMoves.push({x: x, y: this.y}) 18 | if(board[this.y][x]?.color === (this.color === 'white' ? 'black' : 'white')) break; 19 | } 20 | for(let x = this.x + 1; x <= 7; x++) { 21 | if(board[this.y][x]?.color === (this.color === 'white' ? 'white' : 'black')) break; 22 | this.legalMoves.push({x: x, y: this.y}) 23 | if(board[this.y][x]?.color === (this.color === 'white' ? 'black' : 'white')) break; 24 | } 25 | 26 | for(let y = this.y - 1; y >= 0; y--) { 27 | if(board[y][this.x]?.color === (this.color === 'white' ? 'white' : 'black')) break; 28 | this.legalMoves.push({x: this.x, y: y}) 29 | if(board[y][this.x]?.color === (this.color === 'white' ? 'black' : 'white')) break; 30 | } 31 | for(let y = this.y + 1; y <= 7; y++) { 32 | if(board[y][this.x]?.color === (this.color === 'white' ? 'white' : 'black')) break; 33 | this.legalMoves.push({x: this.x, y: y}) 34 | if(board[y][this.x]?.color === (this.color === 'white' ? 'black' : 'white')) break; 35 | } 36 | 37 | let caseCoords = {x: this.x, y: this.y} 38 | // top left 39 | while(--caseCoords.x >= 0 && --caseCoords.y >= 0) { 40 | if(board[caseCoords.y][caseCoords.x]?.color === (this.color === 'white' ? 'white' : 'black')) break; 41 | this.legalMoves.push({...caseCoords}) 42 | if(board[caseCoords.y][caseCoords.x]?.color === (this.color === 'white' ? 'black' : 'white')) break; 43 | } 44 | 45 | caseCoords = {x: this.x, y: this.y} 46 | // bottom right 47 | while(++caseCoords.x <= 7 && ++caseCoords.y <= 7) { 48 | if(board[caseCoords.y][caseCoords.x]?.color === (this.color === 'white' ? 'white' : 'black')) break; 49 | this.legalMoves.push({...caseCoords}) 50 | if(board[caseCoords.y][caseCoords.x]?.color === (this.color === 'white' ? 'black' : 'white')) break; 51 | } 52 | 53 | 54 | caseCoords = {x: this.x, y: this.y} 55 | // top right 56 | while(++caseCoords.x <= 7 && --caseCoords.y >= 0) { 57 | if(board[caseCoords.y][caseCoords.x]?.color === (this.color === 'white' ? 'white' : 'black')) break; 58 | this.legalMoves.push({...caseCoords}) 59 | if(board[caseCoords.y][caseCoords.x]?.color === (this.color === 'white' ? 'black' : 'white')) break; 60 | } 61 | 62 | caseCoords = {x: this.x, y: this.y} 63 | // bottom left 64 | while(--caseCoords.x >= 0 && ++caseCoords.y <= 7) { 65 | if(board[caseCoords.y][caseCoords.x]?.color === (this.color === 'white' ? 'white' : 'black')) break; 66 | this.legalMoves.push({...caseCoords}) 67 | if(board[caseCoords.y][caseCoords.x]?.color === (this.color === 'white' ? 'black' : 'white')) break; 68 | } 69 | 70 | if(chessInstance.simulationState) return 71 | chessInstance.simulationState = true 72 | this.legalMoves = utils.filterPin(this.legalMoves, {x: this.x, y: this.y}, board, chessInstance) 73 | chessInstance.simulationState = false 74 | } 75 | } -------------------------------------------------------------------------------- /src/services/ReadmeService.ts: -------------------------------------------------------------------------------- 1 | import { Octokit } from "octokit"; 2 | import { AppConfigService } from "./ConfigService"; 3 | import { AppConfig } from "../declaration"; 4 | import State from "../State"; 5 | import { Response } from "express"; 6 | import { Logger } from "@nestjs/common"; 7 | 8 | class ReadmeService { 9 | currentContentSha: string | null = null; 10 | startDateRender: number; 11 | private logger = new Logger("ReadmeService") 12 | 13 | async push(octokit: Octokit, message: string, content: string, sha: string): Promise { 14 | const config = AppConfigService.getOrThrow('config') 15 | return (await octokit.request( 16 | `PUT /repos/${config.datas.repo.owner}/${config.datas.repo.name}/contents/${config.datas.repo.readme.path}`, 17 | { 18 | owner: config.datas.repo.owner, 19 | repo: config.datas.repo.name, 20 | path: config.datas.repo.readme.path, 21 | message, 22 | committer: { 23 | name: process.env.OCTO_COMMITTER_NAME, 24 | email: process.env.OCTO_COMMITTER_EMAIL, 25 | }, 26 | content, 27 | sha, 28 | }, 29 | )).data.content.sha 30 | } 31 | 32 | async renderCommitAndPush(commitMessage: string) { 33 | const readmeContent = await State.render() 34 | 35 | if(AppConfigService.getOrThrow('NODE_ENV') === "production") { 36 | await this.commitAndPush(commitMessage, readmeContent) 37 | } else { 38 | this.logger.debug(`Commiting: ${commitMessage}`) 39 | } 40 | } 41 | 42 | async commitAndPush(commitMessage: string, readmeContent: string) { 43 | const config = AppConfigService.getOrThrow('config') 44 | this.startDateRender = Date.now(); 45 | const octokit = new Octokit({ auth: process.env.GH_TOKEN }); 46 | 47 | let sha: string | any = this.currentContentSha 48 | if(!this.currentContentSha) { 49 | sha = (await octokit.request( 50 | `GET /repos/${config.datas.repo.owner}/${config.datas.repo.name}/contents/${config.datas.repo.readme.path}`, 51 | )).data.sha; 52 | } 53 | 54 | const buffer = Buffer.from(readmeContent); 55 | const base64 = buffer.toString('base64'); 56 | let pushRespSha: string 57 | try { 58 | pushRespSha = await this.push(octokit, commitMessage, base64, sha) 59 | } catch (e) { 60 | this.currentContentSha = (await octokit.request(`GET /repos/${config.datas.repo.owner}/${config.datas.repo.name}/contents/${config.datas.repo.readme.path}`)).data.sha 61 | pushRespSha = await this.push(octokit, commitMessage, base64, this.currentContentSha) 62 | } 63 | this.currentContentSha = pushRespSha; 64 | } 65 | 66 | async updateReadmeAndRedirect( 67 | commitMessage: string, 68 | res: Response, 69 | redirectUrlFragment?: string, 70 | ) { 71 | if(redirectUrlFragment && !redirectUrlFragment.startsWith('#')) 72 | throw new Error(`redirectUrlFragment should start with #, received: ${redirectUrlFragment}`) 73 | 74 | await this.renderCommitAndPush(commitMessage) 75 | 76 | const url = AppConfigService.getOrThrow('config.datas.repo.url') 77 | if(AppConfigService.getOrThrow('NODE_ENV') === "production") res.redirect(url + redirectUrlFragment) 78 | else res.redirect(`${AppConfigService.APP_BASE_URL}/render${redirectUrlFragment}`) 79 | } 80 | 81 | doNothingAndRedirect( 82 | res: Response, 83 | redirectUrlFragment?: string, 84 | ) { 85 | 86 | this.logger.debug("Do nothing and redirect") 87 | 88 | if(redirectUrlFragment && !redirectUrlFragment.startsWith('#')) 89 | throw new Error(`redirectUrlFragment should start with #, received: ${redirectUrlFragment}`) 90 | 91 | const url = AppConfigService.getOrThrow('config.datas.repo.url') 92 | if(AppConfigService.getOrThrow('NODE_ENV') === "production") res.redirect(url + redirectUrlFragment) 93 | else res.redirect(`${AppConfigService.APP_BASE_URL}/render${redirectUrlFragment}`) 94 | } 95 | } 96 | 97 | export default new ReadmeService() -------------------------------------------------------------------------------- /src/games/chess/classes/King.ts: -------------------------------------------------------------------------------- 1 | import { Piece } from './Piece' 2 | import { Rook } from './Rook' 3 | import { utils } from './utils' 4 | 5 | export class King extends Piece { 6 | type = 'King' 7 | uniqueInitial = 'k' 8 | 9 | constructor(x: number, y: number, color: 'black' | 'white', public moved = false) { 10 | super(x, y, color) 11 | } 12 | 13 | computeLegalMoves(chessInstance, board) { 14 | this.legalMoves = []; 15 | 16 | let cases = [ 17 | {x: this.x - 1, y: this.y - 1}, 18 | {x: this.x, y: this.y - 1}, 19 | {x: this.x + 1, y: this.y - 1}, 20 | {x: this.x - 1, y: this.y}, 21 | {x: this.x + 1, y: this.y}, 22 | {x: this.x - 1, y: this.y + 1}, 23 | {x: this.x, y: this.y + 1}, 24 | {x: this.x + 1, y: this.y + 1}, 25 | ] 26 | 27 | cases.forEach(caseSingle => { 28 | if(caseSingle.x < 0 || caseSingle.x > 7 || caseSingle.y < 0 || caseSingle.y > 7) return 29 | let antiKingCases = [ 30 | {x: caseSingle.x - 1, y: caseSingle.y - 1}, 31 | {x: caseSingle.x, y: caseSingle.y - 1}, 32 | {x: caseSingle.x + 1, y: caseSingle.y - 1}, 33 | {x: caseSingle.x - 1, y: caseSingle.y}, 34 | {x: caseSingle.x + 1, y: caseSingle.y}, 35 | {x: caseSingle.x - 1, y: caseSingle.y + 1}, 36 | {x: caseSingle.x, y: caseSingle.y + 1}, 37 | {x: caseSingle.x + 1, y: caseSingle.y + 1}, 38 | ] 39 | let antiKingCasesStatus = true 40 | 41 | antiKingCases.forEach(antiKingCase => { 42 | if(utils.getPiece({x: antiKingCase.x, y: antiKingCase.y}, board) instanceof King && utils.getPiece({x: antiKingCase.x, y: antiKingCase.y}, board).color !== this.color) { 43 | antiKingCasesStatus = false 44 | return 45 | } 46 | }) 47 | if(!antiKingCasesStatus) return 48 | if(!(board[caseSingle.y][caseSingle.x]?.color === (this.color === 'white' ? 'white' : 'black'))) this.legalMoves.push(caseSingle) 49 | }) 50 | 51 | if(chessInstance.simulationState) return 52 | chessInstance.simulationState = true 53 | // check castle 54 | if(!this.moved) { 55 | if( 56 | !board[this.y][this.x + 1] 57 | && utils.whoControlsThisCase({x: this.x + 1, y: this.y}, board).filter(piece => piece.color !== this.color).length === 0 58 | && !board[this.y][this.x + 2] 59 | && utils.whoControlsThisCase({x: this.x + 2, y: this.y}, board).filter(piece => piece.color !== this.color).length === 0 60 | && !board[this.y][this.x + 3]?.moved 61 | && utils.whoControlsThisCase({x: this.x + 3, y: this.y}, board).filter(piece => piece.color !== this.color).length === 0 62 | ) this.legalMoves.push({x: this.x + 2, y: this.y}) 63 | // long castle 64 | if( 65 | !board[this.y][this.x + 1] 66 | && utils.whoControlsThisCase({x: this.x - 1, y: this.y}, board).filter(piece => piece.color !== this.color).length === 0 67 | && !board[this.y][this.x + 2] 68 | && utils.whoControlsThisCase({x: this.x - 2, y: this.y}, board).filter(piece => piece.color !== this.color).length === 0 69 | && !board[this.y][this.x - 3] 70 | && utils.whoControlsThisCase({x: this.x - 3, y: this.y}, board).filter(piece => piece.color !== this.color).length === 0 71 | && !board[this.y][this.x - 4]?.moved 72 | && utils.whoControlsThisCase({x: this.x - 4, y: this.y}, board).filter(piece => piece.color !== this.color).length === 0 73 | ) this.legalMoves.push({x: this.x + 2, y: this.y}) 74 | 75 | 76 | if(!board[this.y][this.x - 1] && !board[this.y][this.x - 2] && !board[this.y][this.x - 3] && !board[this.y][this.x - 4]?.moved && board[this.y][this.x - 4] instanceof Rook) this.legalMoves.push({x: this.x - 2, y: this.y}) 77 | } 78 | 79 | this.legalMoves = utils.filterPin(this.legalMoves, {x: this.x, y: this.y}, board, chessInstance) 80 | chessInstance.simulationState = false 81 | } 82 | } -------------------------------------------------------------------------------- /src/games/chess/classes/utils.ts: -------------------------------------------------------------------------------- 1 | import { cloneDeep } from 'lodash'; 2 | 3 | export class utils { 4 | static getAllPieces(board) { 5 | return board.flat().filter(piece => piece) 6 | } 7 | 8 | static getPiece(targetCoords, board) { 9 | return this.getAllPieces(board).find(piece => piece.x === targetCoords.x && piece.y === targetCoords.y) 10 | } 11 | 12 | static filterPin(legalMoves, currentPosition, board, chessInstance) { 13 | return legalMoves.filter(move => { 14 | let nextPosition = this.computeNextPosition(currentPosition, move, board) 15 | this.defineAllLegalMoves(chessInstance, nextPosition) 16 | return this.isKingChecked(this.getMyKing(this.getPiece(move, nextPosition), nextPosition), nextPosition).length === 0 17 | }) 18 | } 19 | 20 | static getMyKing(pieceInstance, board) { 21 | return this.getAllPieces(board).find(piece => piece.color === pieceInstance.color && piece.type === 'King') 22 | } 23 | 24 | static getKingOfColor(color, board) { 25 | return this.getAllPieces(board).find(piece => piece.color === color && piece.type === 'King') 26 | } 27 | 28 | static isKingChecked(king, board) { 29 | return this.getAllPieces(board).filter(piece => piece.legalMoves.filter(move => move.x === king.x && move.y === king.y).length !== 0 && piece.color !== king.color) 30 | } 31 | 32 | static whoControlsThisCase(CaseCoords, board) { 33 | return this.getAllPieces(board).filter(piece => piece.legalMoves.filter(move => move.x === CaseCoords.x && move.y === CaseCoords.y).length > 0) 34 | } 35 | 36 | static computeNextPosition(pieceToMoveCoords, destinationCoords, board) { 37 | board = cloneDeep(board) 38 | let pieceToMove = board[pieceToMoveCoords.y][pieceToMoveCoords.x] 39 | pieceToMove.x = destinationCoords.x 40 | pieceToMove.y = destinationCoords.y 41 | board[pieceToMoveCoords.y][pieceToMoveCoords.x] = null 42 | board[destinationCoords.y][destinationCoords.x] = pieceToMove 43 | return board 44 | } 45 | 46 | static defineAllLegalMoves(chessInstance, board) { 47 | let enPassant = this.getAllPieces(board).find(piece => piece?.enPassantPossible && piece.color === chessInstance.playerTurn) 48 | if(enPassant) enPassant.enPassantPossible = false 49 | 50 | this.getAllPieces(board).forEach(piece => { 51 | if(piece.type === 'King') return 52 | piece.computeLegalMoves(chessInstance, board) 53 | }); 54 | this.getAllPieces(board).filter(piece => piece.type === 'King').forEach(king => { 55 | king.computeLegalMoves(chessInstance, board) 56 | }); 57 | } 58 | 59 | static getPlayerMovesCount(chessInstance) { 60 | return this.getAllPieces(chessInstance.board) 61 | .filter(piece => piece.color === chessInstance.playerTurn) 62 | .map(piece => piece.legalMoves) 63 | .flat().length 64 | } 65 | 66 | static toString(board) { 67 | console.log("---------------------------------") 68 | board.forEach(row => { 69 | row = row.map(item => item ? item.type : " ") 70 | let str = "| " 71 | row.forEach(item => { 72 | str += item.charAt(0) + " | " 73 | }) 74 | console.log(str) 75 | console.log("---------------------------------") 76 | }) 77 | return 78 | } 79 | 80 | static coordsToBoardCoards(coords){ 81 | let alphabet = "abcdefgh" 82 | return `${alphabet[coords.x]}${8 - coords.y}` 83 | } 84 | 85 | static getletterFromNumber(number) { 86 | let numbers = [ 87 | ":eight:", 88 | ":seven:", 89 | ":six:", 90 | ":five:", 91 | ":four:", 92 | ":three:", 93 | ":two:", 94 | ":one:", 95 | ] 96 | return numbers[number] 97 | } 98 | } 99 | 100 | 101 | 102 | 103 | 104 | -------------------------------------------------------------------------------- /public/js/main.js: -------------------------------------------------------------------------------- 1 | "use strict" 2 | 3 | let socket 4 | 5 | const canvas = document.getElementById('mainCanvas'); 6 | const ctx = canvas.getContext('2d'); 7 | const ctx_data = ctx.createImageData(160, 144); 8 | 9 | 10 | 11 | 12 | const keys = { 13 | "37":"left", 14 | "39":"right", 15 | "38":"up", 16 | "40":"down", 17 | "90":"a", 18 | "88":"b", 19 | "13":"start", 20 | "32":"select" 21 | }; 22 | 23 | let pressed = [] 24 | 25 | window.addEventListener("contextmenu", e => e.preventDefault()); 26 | 27 | document.querySelectorAll('.controls button').forEach(btn => { 28 | btn.addEventListener('touchstart', (e) => { 29 | console.log(e.target.classList) 30 | pressed.push(e.target.classList[0]) 31 | }) 32 | 33 | btn.addEventListener('touchend', (e) => { 34 | const index = pressed.indexOf(e.target.classList[0]); 35 | pressed.splice(index, 1); 36 | if(!pressed.length) { 37 | console.log('sending empty', pressed) 38 | socket.emit('input', pressed); 39 | } 40 | }) 41 | 42 | btn.addEventListener('mousedown', (e) => { 43 | console.log(e.target.classList) 44 | pressed.push(e.target.classList[0]) 45 | }) 46 | 47 | btn.addEventListener('mouseup', (e) => { 48 | const index = pressed.indexOf(e.target.classList[0]); 49 | pressed.splice(index, 1); 50 | if(!pressed.length) { 51 | console.log('sending empty', pressed) 52 | socket.emit('input', pressed); 53 | } 54 | }) 55 | }) 56 | 57 | window.onkeydown = function(e) { 58 | if(keys[e.keyCode] != undefined) { 59 | if(!pressed.find(k => k === keys[e.keyCode])) pressed.push(keys[e.keyCode]) 60 | } 61 | } 62 | 63 | window.onkeyup = function(e) { 64 | if(keys[e.keyCode] != undefined) { 65 | // socket.emit('keyup', { key: keys[e.keyCode] }); 66 | // console.log(index) 67 | const index = pressed.indexOf(keys[e.keyCode]); 68 | pressed.splice(index, 1); 69 | if(!pressed.length) { 70 | console.log('sending empty', pressed) 71 | socket.emit('input', pressed); 72 | } 73 | } 74 | } 75 | 76 | setInterval(() => { 77 | // console.log(pressed) 78 | if(pressed.length) socket.emit('input', pressed); 79 | }, 100) 80 | 81 | ;(async () => { 82 | const token = localStorage.getItem('token') 83 | let isExpired = true 84 | if(token) { 85 | const base64Url = token.split('.')[1]; 86 | const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/'); 87 | const jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function(c) { 88 | return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); 89 | }).join('')); 90 | const payload = JSON.parse(jsonPayload); 91 | isExpired = payload.exp < (Date.now() / 1000) 92 | } 93 | if(isExpired) { 94 | const urlParams = new URLSearchParams(window.location.search); 95 | const codeParam = urlParams.get('code'); 96 | 97 | if(!codeParam) { 98 | location.href = location.origin === "http://localhost:3000" ? 99 | "https://github.com/login/oauth/authorize?client_id=8d7a9d49582f3e342dac&redirect_uri=http://localhost:3000/client.html" : 100 | "https://github.com/login/oauth/authorize?client_id=91c84824bc7ffaace9d5&redirect_uri=http://aws-v.charles-chrismann.fr/client.html" 101 | } else { 102 | const token = await (await fetch(`/auth/auth?code=${codeParam}`)).json() 103 | if(token.statusCode && token.statusCode === 500) { 104 | location.href = location.origin === "http://localhost:3000" ? 105 | "https://github.com/login/oauth/authorize?client_id=8d7a9d49582f3e342dac&redirect_uri=http://localhost:3000/client.html" : 106 | "https://github.com/login/oauth/authorize?client_id=91c84824bc7ffaace9d5&redirect_uri=http://aws-v.charles-chrismann.fr/client.html" 107 | } else localStorage.setItem('token', token.access_token) 108 | } 109 | } 110 | window.history.pushState({}, document.title, window.location.pathname); 111 | 112 | socket = io('/gameboy', { 113 | transportOptions: { 114 | polling: { 115 | extraHeaders: { 116 | 'Authorization': `Bearer ${localStorage.getItem('token')}`, 117 | }, 118 | }, 119 | }, 120 | }); 121 | 122 | socket.on('frame', (data) => { 123 | for (let i = 0; i < data.length; i++){ 124 | ctx_data.data[i] = data[i]; 125 | } 126 | 127 | ctx.putImageData(ctx_data, 0, 0); 128 | }) 129 | 130 | socket.on('diff', (data) => { 131 | for (let i = 0; i < data.length; i+= 2){ 132 | for(let j = 0; j < data[i + 1].length; j++) { 133 | ctx_data.data[data[i + 1][j]] = data[i]; 134 | } 135 | } 136 | 137 | ctx.putImageData(ctx_data, 0, 0); 138 | }) 139 | 140 | })() -------------------------------------------------------------------------------- /src/games/chess/classes/Chess.ts: -------------------------------------------------------------------------------- 1 | import cloneDeep from 'lodash/cloneDeep'; 2 | import { utils } from './utils'; 3 | 4 | import { Pawn } from './Pawn'; 5 | import { Bishop } from './Bishop'; 6 | import { Knight } from './Knight'; 7 | import { Rook } from './Rook'; 8 | import { Queen } from './Queen'; 9 | import { King } from './King'; 10 | 11 | export class Chess { 12 | board; // white pov 13 | playerTurn = 'white' 14 | simulationState = false 15 | status = null // null: game en cours | pat: tie | white/black: winner 16 | constructor(chessJson?: Record) { 17 | if(!chessJson) { 18 | this.createBoard() 19 | utils.defineAllLegalMoves(this, this.board) 20 | return this 21 | } 22 | Object.assign(this, chessJson) 23 | this.board = chessJson.board.map(row => row.map(piece => { 24 | if(!piece) return null 25 | switch(piece.type) { 26 | case 'King': return new King(piece.x, piece.y, piece.color, piece.moved) 27 | case 'Pawn': return new Pawn(piece.x, piece.y, piece.color, piece.moved, piece.enPassantPossible) 28 | case 'Rook': return new Rook(piece.x, piece.y, piece.color) // fix Rook should not move before roke 29 | case 'Knight': return new Knight(piece.x, piece.y, piece.color) 30 | case 'Bishop': return new Bishop(piece.x, piece.y, piece.color) 31 | case 'Queen': return new Queen(piece.x, piece.y, piece.color) 32 | } 33 | })) 34 | return this 35 | } 36 | 37 | createBoard() { 38 | this.board = [ 39 | [ 40 | new Rook(0, 0, 'black'), 41 | new Knight(1, 0, 'black'), 42 | new Bishop(2, 0, 'black'), 43 | new Queen(3, 0, 'black'), 44 | new King(4, 0, 'black'), 45 | new Bishop(5, 0, 'black'), 46 | new Knight(6, 0, 'black'), 47 | new Rook(7, 0, 'black'), 48 | ], 49 | [ 50 | new Pawn(0, 1, 'black'), 51 | new Pawn(1, 1, 'black'), 52 | new Pawn(2, 1, 'black'), 53 | new Pawn(3, 1, 'black'), 54 | new Pawn(4, 1, 'black'), 55 | new Pawn(5, 1, 'black'), 56 | new Pawn(6, 1, 'black'), 57 | new Pawn(7, 1, 'black'), 58 | ], 59 | new Array(8).fill(null), 60 | new Array(8).fill(null), 61 | new Array(8).fill(null), 62 | new Array(8).fill(null), 63 | [ 64 | new Pawn(0, 6, 'white'), 65 | new Pawn(1, 6, 'white'), 66 | new Pawn(2, 6, 'white'), 67 | new Pawn(3, 6, 'white'), 68 | new Pawn(4, 6, 'white'), 69 | new Pawn(5, 6, 'white'), 70 | new Pawn(6, 6, 'white'), 71 | new Pawn(7, 6, 'white'), 72 | ], 73 | [ 74 | new Rook(0, 7, 'white'), 75 | new Knight(1, 7, 'white'), 76 | new Bishop(2, 7, 'white'), 77 | new Queen(3, 7, 'white'), 78 | new King(4, 7, 'white'), 79 | new Bishop(5, 7, 'white'), 80 | new Knight(6, 7, 'white'), 81 | new Rook(7, 7, 'white'), 82 | ], 83 | ] 84 | } 85 | 86 | /** 87 | * @param pieceToMoveCoords 88 | * @param destinationCoords 89 | * @returns true if the board has been updated false otherwise 90 | */ 91 | updateBoard(pieceToMoveCoords, destinationCoords): boolean { 92 | if(this.status) return false 93 | let pieceToMove = utils.getPiece(pieceToMoveCoords, this.board) 94 | if(!pieceToMove) return false 95 | if(pieceToMove.color !== this.playerTurn) return false 96 | if(!pieceToMove.legalMoves) return false 97 | this.board = utils.computeNextPosition(pieceToMoveCoords, destinationCoords, this.board) 98 | if(pieceToMove.type === 'Pawn') { 99 | if(Math.abs(pieceToMoveCoords.y - destinationCoords.y) === 2) this.board[destinationCoords.y][destinationCoords.x].enPassantPossible = true 100 | if(Math.abs(pieceToMoveCoords.x - destinationCoords.x) === 1) this.board[pieceToMoveCoords.y][destinationCoords.x] = null 101 | } 102 | if(pieceToMove.type === 'King') { 103 | if(pieceToMoveCoords.x - destinationCoords.x === - 2) { // short castle 104 | this.board[pieceToMoveCoords.y][5] = this.board[pieceToMoveCoords.y][7] 105 | this.board[pieceToMoveCoords.y][7] = null 106 | this.board[pieceToMoveCoords.y][5].updateCoords({x: 5, y: pieceToMoveCoords.y}) 107 | } 108 | if(pieceToMoveCoords.x - destinationCoords.x === 2) { // long castle 109 | this.board[pieceToMoveCoords.y][3] = this.board[pieceToMoveCoords.y][0] 110 | this.board[pieceToMoveCoords.y][0] = null 111 | this.board[pieceToMoveCoords.y][3].updateCoords({x: 3, y: pieceToMoveCoords.y}) 112 | } 113 | } 114 | 115 | this.board[destinationCoords.y][destinationCoords.x].updateCoords(destinationCoords) 116 | this.playerTurn = this.playerTurn === 'white' ? 'black' : 'white' 117 | utils.defineAllLegalMoves(this, this.board); 118 | 119 | // game status check 120 | if(utils.getPlayerMovesCount(this) === 0) { 121 | if(utils.isKingChecked(utils.getKingOfColor(this.playerTurn, this.board), this.board)) this.status = this.playerTurn === 'black' ? 'white' : 'black' 122 | else this.status = 'pat' 123 | } 124 | 125 | return true 126 | } 127 | } -------------------------------------------------------------------------------- /config.md: -------------------------------------------------------------------------------- 1 | # Configuration 2 | 3 | This project is fully configurable from a `config.json` file. 4 | 5 | > A starter config file can be obtained by copying and renaming the `config.example.json` file. 6 | 7 | For now (can change) the json structure is as follow: 8 | 9 | - `structure`: define the final structure of the README file. 10 | - `id`: first part (static, element, games...) describe the category of the block, the last element describe the module responsible for the render 11 | - `datas`: The personal datas of the user. 12 | - `skills`: should be in datas 13 | 14 | ## Modules 15 | 16 | The readme file is separated into small chunks that are called modules. 17 | 18 | The structure of the file can be edited in the `structure` property of the `config.json` file. 19 | 20 | The `structure` property is a list of modules, as follow: 21 | 22 | ```jsonc 23 | // config.json 24 | { 25 | "structure": [ 26 | { 27 | "id": "module/1", 28 | "data": {}, 29 | "options": { 30 | "title": "module 1" 31 | } 32 | }, 33 | { 34 | "id": "module/2", 35 | "disabled": true // modules can be disabled this way 36 | // `data` key might not be required for some modules 37 | // `options` key is always optional, each options is intended to have a default value 38 | }, 39 | ... 40 | ], 41 | "datas": {...}, 42 | "skils": {...} 43 | }, 44 | ``` 45 | 46 | ### Static modules 47 | 48 | Static modules are only calculated once (on first commit after start up), they are for informations that are not intended to change like your name, description... 49 | 50 | #### Element 51 | 52 | Represents an html element. 53 | 54 | ```jsonc 55 | { 56 | "id": "static/element", 57 | "data": { 58 | "element": "h1", 59 | "content": "👋 - Hi visitor" 60 | } 61 | } 62 | ``` 63 | 64 | #### Greeting 65 | 66 | Represents a simple greeting as follow: `

I'm Firstname Lastname !

` 67 | 68 | ```jsonc 69 | { 70 | "id": "static/greeting", 71 | // no data is required for this element, the datas taken from config.json under datas.perso.firstname 72 | } 73 | ``` 74 | 75 | #### Lines 76 | 77 | Represents multiples lines, an alternative to avoid using multiple `static/element`. 78 | 79 | ```jsonc 80 | { 81 | "id": "static/lines", 82 | "data": { 83 | "field": "perso.description", // should be an array 84 | "range": "1-2" // currently supports a single line ("3") or a simple range ("1-3"), not even a combination of the two. 85 | // index for range starts at 1. 86 | } 87 | } 88 | ``` 89 | 90 | #### List 91 | 92 | Represents an unordered list such as: 93 | 94 | ``` 95 |
    96 |
  • ...
  • 97 |
  • ...
  • 98 |
  • ...
  • 99 |
100 | ``` 101 | 102 | ```jsonc 103 | { 104 | "id": "static/list", 105 | "data": { 106 | "field": "perso.facts" // should be an array 107 | } 108 | } 109 | ``` 110 | 111 | #### Socials 112 | 113 | Displays the list of socials in `datas.perso.socials` 114 | 115 | ```jsonc 116 | { 117 | "id": "static/socials", 118 | "options": { 119 | "align": "left" // position of the icons 120 | } 121 | } 122 | ``` 123 | 124 | #### Skills 125 | 126 | Displays the list of skills in `skills` 127 | 128 | ```jsonc 129 | { 130 | "id": "static/skills" 131 | } 132 | ``` 133 | 134 | #### Trigger 135 | 136 | Displays an image that triggers the / controller in the trigger module each time someone visits the readme page. 137 | 138 | > currently required for the followers module to work 139 | 140 | ```jsonc 141 | { 142 | "id": "static/trigger" 143 | } 144 | ``` 145 | 146 | ### Dynamic modules 147 | 148 | #### Followers 149 | 150 | Dislays the last followers. 151 | 152 | ```jsonc 153 | { 154 | "id": "dynamic/followers", 155 | "options": { 156 | "last": 3 // not working for now 157 | } 158 | }, 159 | ``` 160 | 161 | #### Generated 162 | 163 | Displays the date of the last update with the duration of the generation at the end of the file. 164 | 165 | ```jsonc 166 | { 167 | "id": "dynamic/generated" 168 | } 169 | ``` 170 | 171 | ### Games modules 172 | 173 | #### GBA 174 | 175 | Displays a gba game. 176 | 177 | ```jsonc 178 | { 179 | "id": "games/gba", 180 | "data": { 181 | "title": "Github plays pokemon" 182 | }, 183 | "options": { 184 | "scoreboard": false // not implemented 185 | } 186 | } 187 | ``` 188 | 189 | #### Minesweeper 190 | 191 | Displays a minesweeper. 192 | 193 | ```jsonc 194 | { 195 | "id": "games/minesweeper", 196 | "data": { 197 | "title": "A classic Minesweeper", 198 | "reset": "Reset Game" // Text for the reset button 199 | }, 200 | "options": { 201 | "gif": true, // gif of the progress of the game 202 | } 203 | }, 204 | ``` 205 | 206 | #### Chess 207 | 208 | Display a chess game. 209 | 210 | ```jsonc 211 | { 212 | "id": "games/chess", 213 | "data": { 214 | "title": "A classic Chess", 215 | "reset": "Reset Game" // Text for the reset button 216 | }, 217 | "options": { 218 | "reset": true // not implemented 219 | } 220 | } 221 | ``` 222 | 223 | #### Wordle 224 | 225 | Displays a wordle game, reset each day at midnight. 226 | 227 | ```jsonc 228 | { 229 | "id": "games/wordle", 230 | "data": { 231 | "title": "A classic Wordle" 232 | }, 233 | "options": { 234 | "scoreboard": true // not implmented 235 | } 236 | } 237 | ``` 238 | 239 | ### 3rdParty modules 240 | 241 | #### Profil Views 242 | 243 | Displays the profile views image configured in `datas.perso.vueCount` 244 | 245 | ```jsonc 246 | { 247 | "id": "3rdParty/profileViews" 248 | } 249 | ``` -------------------------------------------------------------------------------- /src/games/gameboy/gameboy.gateway.ts: -------------------------------------------------------------------------------- 1 | import { 2 | SubscribeMessage, 3 | WebSocketGateway, 4 | OnGatewayConnection, 5 | WebSocketServer, 6 | OnGatewayDisconnect, 7 | OnGatewayInit 8 | } from '@nestjs/websockets'; 9 | import { Socket, Server } from 'socket.io'; 10 | import { GameboyService } from './gameboy.service'; 11 | import { AuthService } from 'src/auth/auth.service'; 12 | import { CronJob } from 'cron' 13 | import { RedisService } from 'src/redis/redis.service'; 14 | import { ReadmeService } from 'src/services'; 15 | 16 | @WebSocketGateway({ 17 | namespace: 'gameboy' 18 | }) 19 | export class GameboyGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect { 20 | renderInterval: NodeJS.Timer | null 21 | sessionFrames = 0 22 | connected = 0 23 | clients = new Map() 24 | users = new Map() 25 | saveJob = new CronJob('0 * * * * *', async () => { 26 | await this.saveUsers(this); 27 | if (this.needCommit) ReadmeService.renderCommitAndPush(":joystick: Update Gameboy Contributions"); 28 | this.needCommit = false 29 | }) 30 | needCommit = false 31 | lastSendedFrame!: number[] 32 | constructor( 33 | private gameboyService: GameboyService, 34 | private authService: AuthService, 35 | ){ 36 | this.saveJob.start() 37 | } 38 | 39 | @WebSocketServer() 40 | server: Server; 41 | 42 | async afterInit(io: Server) { 43 | 44 | io.use(async (socket, next) => { 45 | try { 46 | const payload = await this.authService.verify(socket.handshake.headers.authorization.split(' ')[1]) 47 | if(payload) { 48 | this.clients.set(socket.id, payload.id) 49 | this.users.set(String(payload.id), { id: payload.id, inputCount: 0, pressed: [], connectetd: true }) 50 | next() 51 | } else next(new Error('authentication error')) 52 | } catch (e) { 53 | console.log(e) 54 | next(new Error('authentication error')) 55 | } 56 | }) 57 | } 58 | 59 | computeFrameDiff(newFrame: number[]) { 60 | const startArray: number[][] = Array.from({ length: 256 }, e => Array() ) 61 | for(let i = 0; i < newFrame.length; i++) { 62 | if(newFrame[i] !== this.lastSendedFrame[i]) { 63 | startArray[newFrame[i]].push(i) 64 | } 65 | } 66 | 67 | const returnArray = [] as (number | number[])[] 68 | for(let i = 0; i < startArray.length; i+= 1) { 69 | if(startArray[i].length) { 70 | returnArray.push(i) 71 | returnArray.push(startArray[i]) 72 | } 73 | } 74 | return returnArray 75 | } 76 | 77 | handleConnection(socket: Socket): void { 78 | this.lastSendedFrame = this.gameboyService.gameboy_instance.doFrame() 79 | this.server.emit('frame', this.lastSendedFrame) 80 | if(++this.connected > 1) return 81 | this.saveJob.start() 82 | 83 | this.gameboyService.stopRenderSession() 84 | this.renderInterval = setInterval(() => { 85 | if(++this.sessionFrames % 10 === 0) { 86 | const newFrame = this.gameboyService.gameboy_instance.doFrame() 87 | const diff = this.computeFrameDiff(newFrame) 88 | if(diff.length) this.server.emit('diff', diff) 89 | this.lastSendedFrame = newFrame 90 | } else { 91 | if(this.gameboyService.lastInputFrames.length >= 80) { 92 | this.gameboyService.lastInputFrames.splice(0, this.gameboyService.lastInputFrames.length - 80 + 1) 93 | } 94 | if(this.sessionFrames % 4 === 0) this.gameboyService.lastInputFrames.push(this.gameboyService.gameboy_instance.doFrame()) 95 | else this.gameboyService.gameboy_instance.doFrame() 96 | } 97 | }, 5) 98 | } 99 | 100 | handleDisconnect(socket: Socket) { 101 | const user = this.users.get(String(this.clients.get(socket.id))) 102 | if(user) user.connectetd = false 103 | this.clients.delete(socket.id) 104 | if(--this.connected === 0) { 105 | this.saveUsers(this) 106 | this.saveJob.stop() 107 | this.sessionFrames = 0 108 | clearInterval(this.renderInterval as NodeJS.Timeout) 109 | this.renderInterval = null 110 | this.gameboyService.setRenderSession() 111 | } 112 | } 113 | 114 | @SubscribeMessage('input') 115 | async handleMessage(client: any, payload: string[]) { 116 | this.needCommit = true 117 | let userId = this.clients.get(client.id) 118 | if(!userId) return 119 | let userAction = this.users.get(String(userId)) ?? { id: userId, inputCount: 0, pressed: [] as string[], connectetd: true } 120 | const validatedInputs = userAction.pressed.filter(input => !payload.find(v => input === v)) 121 | userAction.inputCount += validatedInputs.length 122 | userAction.pressed = payload 123 | this.users.set(String(userId), userAction) 124 | for(let i = 0; i < 2; i++) { 125 | this.gameboyService.gameboy_instance.pressKeys(payload) 126 | this.gameboyService.gameboy_instance.doFrame() 127 | } 128 | } 129 | 130 | async saveUsers(that) { 131 | for(const [key, user] of that.users) { 132 | const isSaved = await that.redis.client.hGet(`gameboy:players:${user.id}`, 'id') 133 | if(!isSaved) await that.redis.client.hSet(`gameboy:players:${user.id}`, {id: user.id, inputCount: user.inputCount}) 134 | else { 135 | const userInputCount = await that.redis.client.hGet(`gameboy:players:${user.id}`, 'inputCount') 136 | that.redis.client.hSet(`gameboy:players:${user.id}`, 'inputCount', +userInputCount + user.inputCount) 137 | } 138 | user.inputCount = 0 139 | if(!user.connected) that.users.delete(user.id) 140 | } 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /src/zod.zodobject.ts: -------------------------------------------------------------------------------- 1 | 2 | import * as z from "zod"; 3 | 4 | export const ConfigSchema = z.object({ 5 | structure: z.array( 6 | z.discriminatedUnion("id", [ 7 | z.object({ 8 | id: z.literal("static/element"), 9 | data: z.object({ 10 | element: z.enum([ 11 | 'h1', 12 | 'h2', 13 | 'h3', 14 | 'h4', 15 | 'h5', 16 | 'h6', 17 | // void elements 18 | 'area', 19 | 'base', 20 | 'br', 21 | 'col', 22 | 'embed', 23 | 'hr', 24 | 'img', 25 | 'input', 26 | 'link', 27 | 'meta', 28 | 'param', 29 | 'source', 30 | 'track', 31 | 'wbr' 32 | ]), 33 | content: z.string(), 34 | }), 35 | options: z.object({ 36 | align: z.enum(["left", "right", "center"]).optional() 37 | }).optional(), 38 | disabled: z.boolean().optional(), 39 | }), 40 | z.object({ 41 | id: z.literal("static/raw"), 42 | data: z.object({ 43 | content: z.string() 44 | }), 45 | disabled: z.boolean().optional(), 46 | }), 47 | z.object({ 48 | id: z.literal("static/greeting"), 49 | disabled: z.boolean().optional(), 50 | }), 51 | z.object({ 52 | id: z.literal("static/profile-views"), 53 | data: z.object({ 54 | username: z.string() 55 | }), 56 | disabled: z.boolean().optional(), 57 | }), 58 | z.object({ 59 | id: z.literal("static/lines"), 60 | data: z.object({ 61 | field: z.string(), 62 | range: z.string() 63 | }), 64 | disabled: z.boolean().optional(), 65 | }), 66 | z.object({ 67 | id: z.literal("static/skills"), 68 | disabled: z.boolean().optional(), 69 | }), 70 | z.object({ 71 | id: z.literal("static/list"), 72 | data: z.object({ 73 | field: z.string(), 74 | }), 75 | disabled: z.boolean().optional(), 76 | }), 77 | z.object({ 78 | id: z.literal("dynamic/followers"), 79 | options: z.object({ 80 | last: z.number(), 81 | }), 82 | disabled: z.boolean().optional(), 83 | }), 84 | z.object({ 85 | id: z.literal("static/socials"), 86 | options: z.object({ 87 | align: z.enum(["left", "right", "center"]), 88 | }), 89 | disabled: z.boolean().optional(), 90 | }), 91 | z.object({ 92 | id: z.literal("dynamic/gba"), 93 | data: z.object({ 94 | uuid: z.string(), 95 | title: z.string(), 96 | }), 97 | options: z.object({ 98 | scoreboard: z.boolean() 99 | }), 100 | disabled: z.boolean().optional(), 101 | }), 102 | z.object({ 103 | id: z.literal("dynamic/minesweeper"), 104 | data: z.object({ 105 | uuid: z.string(), 106 | title: z.string(), 107 | reset: z.string(), 108 | }), 109 | options: z.object({ 110 | gif: z.boolean() 111 | }), 112 | disabled: z.boolean().optional(), 113 | }), 114 | z.object({ 115 | id: z.literal("dynamic/chess"), 116 | data: z.object({ 117 | uuid: z.string(), 118 | title: z.string(), 119 | reset: z.string(), 120 | }), 121 | options: z.object({ 122 | reset: z.boolean() 123 | }), 124 | disabled: z.boolean().optional(), 125 | }), 126 | z.object({ 127 | id: z.literal("dynamic/wordle"), 128 | data: z.object({ 129 | title: z.string(), 130 | }), 131 | options: z.object({ 132 | scoreboard: z.boolean() 133 | }), 134 | disabled: z.boolean().optional(), 135 | }), 136 | z.object({ 137 | id: z.literal("static/trigger"), 138 | disabled: z.boolean().optional(), 139 | }), 140 | z.object({ 141 | id: z.literal("dynamic/generated"), 142 | disabled: z.boolean().optional(), 143 | }), 144 | 145 | ]), 146 | ), 147 | datas: z.object({ 148 | repo: z.object({ 149 | name: z.string(), 150 | owner: z.string(), 151 | url: z.url({ 152 | protocol: /^https$/, 153 | hostname: /^github.com$/ 154 | }), 155 | readme: z.object({ 156 | path: z.string() 157 | }) 158 | }), 159 | perso: z.object({ 160 | homepage: z.url({ 161 | protocol: /^https$/, 162 | hostname: /^github.com$/ 163 | }), 164 | username: z.string(), 165 | firstname: z.string(), 166 | lastname: z.string(), 167 | description: z.array( 168 | z.string() 169 | ), 170 | facts: z.object({ 171 | title: z.string(), 172 | content: z.array( 173 | z.string() 174 | ), 175 | }), 176 | socials: z.array( 177 | z.object({ 178 | name: z.enum([ 179 | 'linkedin', 180 | 'instagram', 181 | ]), 182 | profile_url: z.url(), 183 | icon_url: z.url(), 184 | }) 185 | ) 186 | }), 187 | skills: z.record( 188 | z.string(), z.object({ 189 | title: z.string(), 190 | direction: z.enum(['row', 'column']).default('column'), 191 | list: z.array( 192 | z.object({ 193 | name: z.string(), 194 | url: z.string(), 195 | src: z.string(), 196 | alt: z.string() 197 | }) 198 | ) 199 | }) 200 | ), 201 | "3rdParty": z.object({ 202 | views_count: z.url(), 203 | }).optional() 204 | }) 205 | }) -------------------------------------------------------------------------------- /src/modules/dynamics/wordle.module.ts: -------------------------------------------------------------------------------- 1 | import { AbstractDynamicModule } from "../abstract.module"; 2 | import { FIVE_CHAR_WORDS } from "src/games/wordle/word_list"; 3 | import { CronJob } from "cron"; 4 | import ReadmeService from "src/services/ReadmeService"; 5 | import { AppConfigService } from "src/services"; 6 | 7 | interface Data { 8 | } 9 | 10 | interface Options { 11 | } 12 | 13 | export class WordleDynamicModule extends AbstractDynamicModule { 14 | 15 | todayWordle: { 16 | word: string, 17 | guessed: boolean, 18 | guesses: { 19 | username: string, 20 | userId: number, 21 | guess: { 22 | valid: boolean, 23 | letters: { value: string, status: "correct" | "present" | "absent" }[] 24 | } 25 | }[] 26 | }; 27 | 28 | scoreBoard: { 29 | users: { 30 | username: string, 31 | userId: number, 32 | guesses: number 33 | }[] 34 | } 35 | 36 | createWordleCron = new CronJob('0 0 22 * * *', async () => { 37 | await this.wordle() 38 | this.needsRender = true 39 | await ReadmeService.renderCommitAndPush(':book: set today\'s wordle') 40 | }, null, true) 41 | 42 | public async init(): Promise { 43 | if(!await AppConfigService.redis.client.get('wordle')) await this.wordle() 44 | if(!await AppConfigService.redis.client.get('wordle-scoreBoard')) { 45 | await AppConfigService.redis.client.set( 46 | 'wordle-scoreBoard', 47 | JSON.stringify({ 48 | users: [] as { 49 | username: string, 50 | userId: number, 51 | guesses: number 52 | }[] 53 | } 54 | ) 55 | ) 56 | } 57 | } 58 | 59 | async wordle() { 60 | const word = FIVE_CHAR_WORDS[Math.floor(Math.random() * FIVE_CHAR_WORDS.length)] 61 | const wordle = { 62 | word, 63 | guessed: false, 64 | guesses: [] 65 | } 66 | await AppConfigService.redis.client.set('wordle', JSON.stringify(wordle)) 67 | 68 | return 'wordle'; 69 | } 70 | 71 | async guess(guess: string, issuer: string, issuerId: number) { 72 | guess = guess.toUpperCase(); 73 | if(!guess.length || guess.length > 5) return 74 | const guessContainsOnlyLetters = /^[A-Z]+$/.test(guess); 75 | if(!guessContainsOnlyLetters) return 76 | const wordle = JSON.parse(await AppConfigService.redis.client.get('wordle')); 77 | if(!wordle || wordle.guessed) return 78 | this.needsRender = true 79 | const guessObj = { 80 | username: issuer, 81 | userId: issuerId, 82 | guess: { 83 | valid: FIVE_CHAR_WORDS.includes(guess), 84 | letters: [] as { value: string, status: "correct" | "present" | "absent" }[] 85 | } 86 | } 87 | for(let i = 0; i < 5; i++) { 88 | const value = guess[i]; 89 | if(value === wordle.word[i]) { 90 | guessObj.guess.letters.push({ value, status: "correct" }) 91 | } else if(wordle.word.includes(value)) { 92 | guessObj.guess.letters.push({ value, status: "present" }) 93 | } else { 94 | guessObj.guess.letters.push({ value, status: "absent" }) 95 | } 96 | } 97 | 98 | wordle.guessed = guess === wordle.word; 99 | wordle.guesses.push(guessObj); 100 | await AppConfigService.redis.client.set('wordle', JSON.stringify(wordle)) 101 | this.todayWordle = wordle; 102 | 103 | let scoreBoard = JSON.parse(await AppConfigService.redis.client.get('wordle-scoreBoard')) 104 | if(wordle.guessed) { 105 | if(!scoreBoard) scoreBoard = { users: [] }; 106 | const userIndex = scoreBoard.users.findIndex(user => user.username === issuer); 107 | if(userIndex === -1) { 108 | scoreBoard.users.push({ username: issuer, userId: issuerId, guesses: 1}); 109 | } else { 110 | scoreBoard.users[userIndex].guesses += 1; 111 | } 112 | scoreBoard.users.sort((a, b) => b.guesses - a.guesses); 113 | await AppConfigService.redis.client.set('wordle-scoreBoard', JSON.stringify(scoreBoard)) 114 | } 115 | } 116 | 117 | public async render(): Promise { 118 | const config = AppConfigService.getOrThrow('config') 119 | const todayWordle = JSON.parse(await AppConfigService.redis.client.get('wordle')) 120 | const scoreBoard = JSON.parse(await AppConfigService.redis.client.get('wordle-scoreBoard')) 121 | let md = `

A classic Wordle

\n` 122 | md += `\n \n \n \n \n \n \n` 123 | md += todayWordle.guesses.map(guess => { 124 | let letterTds 125 | if(!guess.guess.valid) letterTds = guess.guess.letters.map(letter => ` \n`).join('') 126 | else letterTds = guess.guess.letters.map(letter => ` \n`).join('') 127 | return ` \n${letterTds} \n \n` 128 | }).join('') 129 | 130 | md += ` \n \n \n \n \n \n \n \n` 131 | md += ` \n
WordlePlayer
$\\text{\\color{red}{${letter.value}}}$${letter.status === 'correct' ? `$\\text{\\color{lightgreen}{${letter.value}}}$` : (letter.status === 'present' ? `$\\text{\\color{orange}{${letter.value}}}$` : `$\\text{\\color{white}{${letter.value}}}$`)}
\n @${guess.username}\n
\n Submit a word\n
\n` 132 | 133 | md += `\n \n \n \n \n \n \n \n \n \n \n \n` 134 | md += scoreBoard.users.map((user, index) => ` \n \n \n \n \n \n`).join('') 135 | md += ` \n
Scoreboard
RankPlayerWins
${index + 1}\n \n \n \n \n @${user.username}\n ${user.guesses}
\n\n` 136 | 137 | md += `
\n\n` 138 | return md 139 | } 140 | } -------------------------------------------------------------------------------- /src/modules/dynamics/minesweeper.module.ts: -------------------------------------------------------------------------------- 1 | import { commandOptions } from "redis"; 2 | import { GifEncoder } from "@skyra/gifenc"; 3 | import { createCanvas, loadImage } from "@napi-rs/canvas"; 4 | import { AbstractDynamicModule } from "../abstract.module"; 5 | import { Minesweeper } from "src/games/minesweeper/classes/Minesweeper"; 6 | import { AppConfigService } from "src/services"; 7 | import { buffer } from "stream/consumers"; 8 | 9 | interface Data { 10 | uuid: string 11 | } 12 | 13 | interface Options { 14 | } 15 | 16 | export class MinesweeperDynamicModule extends AbstractDynamicModule { 17 | 18 | redisKey: string 19 | redisImagesKey: string 20 | gifBuffer: Buffer 21 | 22 | async init() { 23 | this.redisKey = `msw:${this.data['uuid']}` 24 | this.redisImagesKey = `msw:${this.data['uuid']}:images` 25 | if(!await AppConfigService.redis.client.get(this.redisKey)) await this.new() 26 | else { 27 | await this.generatehistoryGif() 28 | } 29 | } 30 | 31 | async new() { 32 | const minesweeper = new Minesweeper(18, 14, 24) 33 | await Promise.all([ 34 | AppConfigService.redis.client.set(this.redisKey, JSON.stringify(minesweeper)), 35 | AppConfigService.redis.client.unlink(this.redisImagesKey) 36 | ]) 37 | await this.renderGameImageCtx(true, minesweeper) 38 | this.gifBuffer = null 39 | this.needsRender = true 40 | return minesweeper 41 | } 42 | 43 | /** 44 | * @param x 45 | * @param y 46 | * @returns true if the map has been updated false otherwise 47 | */ 48 | async click(x: number, y: number): Promise { 49 | const minesweeperData: Record = JSON.parse(await AppConfigService.redis.client.get(this.redisKey)) 50 | const minesweeper = minesweeperData ? new Minesweeper(minesweeperData) : await this.new() 51 | if(minesweeper.gameStatus === "Ended") return false 52 | if(!minesweeper.HandleClick({x: x, y: y})) return false 53 | if(minesweeper.map.flat().filter(cell => cell.hidden).length === minesweeper.bombsCount) minesweeper.gameStatus = "Endend" 54 | await this.renderGameImageCtx(false, minesweeper) 55 | await AppConfigService.redis.client.set(this.redisKey, JSON.stringify(minesweeper)) 56 | this.needsRender = true 57 | this.generatehistoryGif() 58 | return true 59 | } 60 | 61 | async renderGameImageCtx(isFirst: boolean = false, minesweeperData: Record) { 62 | const tileSize = 16; 63 | const canvas = createCanvas(tileSize * minesweeperData.width, tileSize * minesweeperData.height) 64 | const ctx = canvas.getContext('2d') 65 | ctx.fillStyle = "#000000" 66 | ctx.fillRect(0, 0, tileSize * minesweeperData.width, tileSize * minesweeperData.height) 67 | 68 | if(isFirst) { 69 | AppConfigService.redis.client.hSet(this.redisImagesKey, 0, ctx.canvas.toBuffer('image/png')) 70 | return 71 | } 72 | 73 | const emojis = {} 74 | const emojiList = ["one", "two", "three", "four", "five", "six", "seven", "eight", "boom"] 75 | for(let i = 0; i < minesweeperData.width; i++) { 76 | for(let j = 0; j < minesweeperData.height; j++) { 77 | const cell = minesweeperData.map[j][i] 78 | if(cell.hidden) continue 79 | if(!cell.value) { 80 | ctx.fillStyle = "#ffffff" 81 | ctx.fillRect(i * tileSize, j * tileSize, tileSize, tileSize) 82 | continue 83 | } 84 | const emojiImage = await (emojis[emojiList[cell.value - 1]] ?? (async () => { 85 | const emoji = emojiList[cell.value - 1] 86 | emojis[emoji] = await loadImage(`./src/assets/emojis/${emoji}.png`) 87 | return emojis[emoji] 88 | })()) 89 | ctx.drawImage(emojiImage, cell.x * tileSize, cell.y * tileSize, tileSize, tileSize) 90 | } 91 | } 92 | const savedImages = await AppConfigService.redis.client.hGetAll(this.redisImagesKey) 93 | AppConfigService.redis.client.hSet(this.redisImagesKey, Object.keys(savedImages).length, ctx.canvas.toBuffer('image/png')) 94 | } 95 | 96 | async generatehistoryGif() { 97 | const minesweeperData: Record = JSON.parse(await AppConfigService.redis.client.get(this.redisKey)) 98 | const imagesPromises = Object.values(await AppConfigService.redis.client.hGetAll(commandOptions({ returnBuffers: true }), this.redisImagesKey)).map(async buffer => await loadImage(buffer)) 99 | const images = await Promise.all(imagesPromises) 100 | 101 | const tileSize = 16; 102 | const canvasWidth = minesweeperData.width * tileSize 103 | const canvasHeight = minesweeperData.height * tileSize 104 | const gifEncoder = new GifEncoder(canvasWidth, canvasHeight) 105 | .setRepeat(0) 106 | .setDelay(Math.floor(5000 / images.length || 1)) 107 | .setQuality(10) 108 | const stream = gifEncoder.createReadStream(); 109 | gifEncoder.start() 110 | 111 | for(let i = 0; i < images.length; i++) { 112 | const image = images[i] 113 | const canvas = createCanvas(canvasWidth, canvasHeight) 114 | const ctx = canvas.getContext('2d') 115 | ctx.drawImage(image, 0, 0) 116 | gifEncoder.addFrame(ctx.getImageData(0, 0, canvasWidth, canvasHeight).data) 117 | } 118 | gifEncoder.finish() 119 | 120 | this.gifBuffer = await buffer(stream) 121 | } 122 | 123 | public async render(): Promise { 124 | 125 | const { APP_BASE_URL } = AppConfigService 126 | const BASE_URL = `${APP_BASE_URL}/minesweeper/${this.data.uuid}` 127 | 128 | const minesweeper: Minesweeper = new Minesweeper(JSON.parse(await AppConfigService.redis.client.get(this.redisKey))) 129 | let str = `

A classic Minesweeper

\n` 130 | str += `

\n` 131 | str += minesweeper.map.map(row => `${row.map(cell => cell.hidden ? ` ${cell.toEmoji()}\n` : ` ${cell.toEmoji()}\n`).join('')}`).join('
\n') 132 | str += `

\n` 133 | if(minesweeper.gameStatus === "Not Started") str += `

Come on, try it

\n` 134 | else if(minesweeper.gameStatus === "Started") str += `

Keep clearing, there are still many mines left.

\n` 135 | else str += minesweeper.gameLoosed ? `

You lost don't hesitate to try again

\n` : `

Congrats you won !

\n` 136 | 137 | const historyLength = Object.values(await AppConfigService.redis.client.hGetAll(commandOptions({ returnBuffers: true }), this.redisImagesKey)).length 138 | if(historyLength > 1) str += `

\n \n

\n` 139 | 140 | str += `

\n Reset Game\n

\n\n
\n\n` 141 | 142 | return str 143 | } 144 | 145 | async gif() { 146 | return this.gifBuffer 147 | } 148 | } -------------------------------------------------------------------------------- /src/modules/dynamics/chess.module.ts: -------------------------------------------------------------------------------- 1 | import { createCanvas, loadImage, Image } from "@napi-rs/canvas"; 2 | import { AbstractDynamicModule } from "../abstract.module"; 3 | import { Chess, Piece, Square } from "chess.js"; 4 | import { MoveInstruction } from "src/games/chess/declarations"; 5 | import { AppConfigService } from "src/services"; 6 | import { utils } from "src/games/chess/classes/utils"; 7 | 8 | interface Data { 9 | uuid: string 10 | } 11 | 12 | interface Options { 13 | } 14 | 15 | export class ChessDynamicModule extends AbstractDynamicModule { 16 | 17 | redisKey: string 18 | public boardBuffer: Buffer 19 | private static piecesMap: Map | undefined 20 | 21 | async init() { 22 | this.redisKey = `chess:${this.data['uuid']}` 23 | if(!await AppConfigService.redis.client.get(this.redisKey)) await this.new() 24 | await ChessDynamicModule.loadAssets() 25 | } 26 | 27 | static async loadAssets() { 28 | if(ChessDynamicModule.piecesMap) return 29 | this.piecesMap = new Map() 30 | 31 | const pieceNames = [ 32 | 'bb', 'bk', 'bn', 'bp', 'bq', 'br', 33 | 'wb', 'wk', 'wn', 'wp', 'wq', 'wr', 34 | ] 35 | 36 | const loadedImages = await Promise.all( 37 | pieceNames.map(async (name) => ({ 38 | name, 39 | image: await loadImage(`./src/games/chess/assets/${name}.png`), 40 | })) 41 | ) 42 | 43 | for (const { name, image } of loadedImages) { 44 | this.piecesMap.set(name, image) 45 | } 46 | } 47 | 48 | private static pieces = { 49 | p: { 50 | w: "♙", 51 | b: "♟", 52 | }, 53 | k: { 54 | w: "♔", 55 | b: "♚", 56 | }, 57 | q: { 58 | w: "♕", 59 | b: "♛", 60 | }, 61 | r: { 62 | w: "♖", 63 | b: "♜", 64 | }, 65 | n: { 66 | w: "♘", 67 | b: "♞", 68 | }, 69 | b: { 70 | w: "♗", 71 | b: "♝", 72 | }, 73 | } 74 | 75 | async new() { 76 | const chess = new Chess() 77 | await AppConfigService.redis.client.set(this.redisKey, chess.fen()) 78 | this.renderBoardImage() 79 | this.needsRender = true 80 | } 81 | 82 | async move(moveInstruction: MoveInstruction) { 83 | 84 | const chess = new Chess(await AppConfigService.redis.client.get(this.redisKey)) 85 | 86 | try { 87 | chess.move({ 88 | from: moveInstruction.from, 89 | to: moveInstruction.to, 90 | }) 91 | 92 | await AppConfigService.redis.client.set(this.redisKey, chess.fen()) 93 | this.needsRender = true 94 | 95 | return true 96 | } catch (error) { 97 | return false 98 | } 99 | } 100 | 101 | async renderBoardImage() { 102 | const tileSize = 32; 103 | const canvas = createCanvas(256, 256) 104 | const ctx = canvas.getContext('2d') 105 | ctx.fillStyle = '#eeeed2' 106 | ctx.fillRect(0, 0, 256, 256) 107 | 108 | ctx.fillStyle = '#769656' 109 | 110 | let currentColor; 111 | for (let i = 0; i < 8; i++) { 112 | for (let j = 0; j < 8; j++) { 113 | if ((i + j) % 2 === 0) { 114 | ctx.fillRect(tileSize * i, tileSize * j, tileSize, tileSize) 115 | } 116 | 117 | if(j === 7) { 118 | currentColor = ctx.fillStyle 119 | ctx.fillStyle = i % 2 === 0 ? '#769656' : '#eeeed2' 120 | ctx.fillText(String.fromCharCode(97 + i), tileSize * (i + 1) - 6, 253) 121 | ctx.fillStyle = currentColor 122 | } 123 | } 124 | currentColor = ctx.fillStyle 125 | ctx.fillStyle = i % 2 !== 0 ? '#769656' : '#eeeed2' 126 | ctx.fillText(String(8 - i), 1, tileSize * (i + 1) - 24) 127 | ctx.fillStyle = currentColor 128 | } 129 | 130 | const chess = new Chess(await AppConfigService.redis.client.get(this.redisKey)) 131 | 132 | for(const row of chess.board()) { 133 | for(const square of row) { 134 | if(!square) continue 135 | 136 | const [x, y] = square.square.split('') 137 | 138 | ctx.drawImage( 139 | ChessDynamicModule.piecesMap.get(`${square.color}${square.type}`), 140 | ["a", "b", "c", "d", "e", "f", "g", "h"].indexOf(x) * tileSize, 141 | (8 - (+y)) * tileSize, 142 | tileSize, 143 | tileSize 144 | ) 145 | } 146 | } 147 | 148 | const buffer = await canvas.encode('png') 149 | this.boardBuffer = buffer 150 | } 151 | 152 | private computeMoveString(chess: Chess, piece: { square: Square } & Piece) { 153 | const BASE_URL = `${AppConfigService.APP_BASE_URL}/chess/${this.data.uuid}` 154 | const moves = chess.moves({ square: piece.square, verbose: true }) 155 | const sqrt = Math.ceil(Math.sqrt(moves.length)) 156 | return moves.map((move, index: number) => { 157 | return `${(index % sqrt === 0 && index !== 0) ? "
" : ''}${move.to}` 158 | }).join('\n ') 159 | } 160 | 161 | async getBoardBuffer() { 162 | if(!this.boardBuffer) await this.renderBoardImage() 163 | return this.boardBuffer 164 | } 165 | 166 | public async render(): Promise { 167 | const chess = new Chess(await AppConfigService.redis.client.get(this.redisKey)) 168 | const BASE_URL = `${AppConfigService.APP_BASE_URL}/chess/${this.data.uuid}` 169 | 170 | let md = `

A classic Chess

\n` 171 | this.renderBoardImage() 172 | md += `

\n \n

\n` 173 | 174 | if(chess.isGameOver()) { 175 | if(chess.isStalemate()) md += `

Stalemate !

\n` 176 | else `

It's ${chess.turn() === "b" ? "White" :"Black"}'s turn

\n` 177 | } else md += `

It's ${chess.turn() === "b" ? "Black" : "White"}'s turn

\n` 178 | 179 | md += `\n \n` 180 | chess.board().forEach((row, y) => { 181 | md += ` \n \n` 182 | row.forEach((piece) => { 183 | md += ` \n` 185 | }) 186 | md += ` \n` 187 | }) 188 | 189 | md += ` \n \n \n \n \n \n \n \n \n \n \n \n
${utils.getletterFromNumber(y)}${piece ? (piece.color === chess.turn() && chess.moves({ square: piece.square }).length ? `\n
\n ${ChessDynamicModule.pieces[piece.type][piece.color]}\n ${this.computeMoveString(chess, piece)}\n
\n` : ChessDynamicModule.pieces[piece.type][piece.color] 184 | ): "‎ "}
🇦🇧🇨🇩🇪🇫🇬🇭
` 190 | 191 | md += `

\nReset Game\n

\n\n
\n\n` 192 | return md 193 | } 194 | } -------------------------------------------------------------------------------- /src/modules/dynamics/gba.module.ts: -------------------------------------------------------------------------------- 1 | import * as fs from 'fs'; 2 | import * as path from 'path'; 3 | import { Wrapper } from "gbats"; 4 | import { AbstractDynamicModule } from "../abstract.module"; 5 | import { createCanvas } from "@napi-rs/canvas"; 6 | import { RedisService } from "src/redis/redis.service"; 7 | import { CronJob } from 'cron'; 8 | import { Logger } from '@nestjs/common'; 9 | import { buffer } from 'stream/consumers'; 10 | import { GifEncoder } from '@skyra/gifenc'; 11 | import { Readable } from 'stream'; 12 | import { AppConfigService } from 'src/services'; 13 | import { Response } from 'express'; 14 | 15 | interface Data { 16 | uuid: string 17 | } 18 | 19 | interface Options { 20 | } 21 | 22 | export class GbaDynamicModule extends AbstractDynamicModule { 23 | 24 | gba_wrapper: Wrapper 25 | canvas = createCanvas(240, 160) 26 | redis: RedisService 27 | cron: CronJob 28 | protected readonly logger = new Logger("GBA") 29 | gifBuffer: Buffer 30 | redisKey: string 31 | 32 | constructor(data: Data, options?: Options) { 33 | super(data, options) 34 | this.redis = AppConfigService.redis 35 | this.redisKey = `gba:save_state:${this.data.uuid}` 36 | } 37 | 38 | public async init(): Promise { 39 | 40 | const rom = fs.readFileSync(path.join(process.env.PWD, 'roms', process.env.ROM_GBA_NAME)) 41 | 42 | this.gba_wrapper = new Wrapper({ 43 | rom, 44 | canvas: this.canvas, 45 | updateMethod: 'manual' 46 | }) 47 | const gi = await this.redis.client.get(this.redisKey) 48 | if(gi) { 49 | await this.gba_wrapper.loadSaveState(gi) 50 | } 51 | 52 | const frames = this.skipFrames(600, true) 53 | this.gifBuffer = await this.createGifBuffer(frames) 54 | 55 | this.cron = new CronJob(process.env.EMU_BACKUP_CRON, () => this.backup(), null, true) 56 | } 57 | 58 | async backup() { 59 | this.logger.log('[SHEDULED] Saving gba') 60 | const save = await this.gba_wrapper.createSaveState() 61 | this.redis.client.set(this.redisKey, save) 62 | } 63 | 64 | public render(): string | Promise { 65 | return '' 66 | } 67 | 68 | async input(input: number) { 69 | if(input < 0 || input > 9) return 70 | const frames = [] 71 | 72 | 73 | for(let i = 0; i < 5; i++) { 74 | this.gba_wrapper.press(input, 1) 75 | this.gba_wrapper.frame() 76 | frames.push(this.gba_wrapper.getPixels()) 77 | } 78 | frames.push(...this.skipFrames(300, true)) 79 | 80 | this.gifBuffer = await this.createGifBuffer(frames) 81 | } 82 | 83 | skipFrames( 84 | n: number, 85 | returnFrames: boolean = false 86 | ): undefined | number[][] { 87 | const start = performance.now() 88 | 89 | if(!returnFrames) { 90 | for(let i = 0; i < n; i++) this.gba_wrapper.frame() 91 | 92 | if(AppConfigService.getOrThrow('NODE_ENV') === "development") 93 | this.logger.debug(`${n} frames skipped in ${performance.now() - start}ms`) 94 | 95 | return 96 | } 97 | 98 | const frames = [] 99 | for(let i = 0; i < n; i++) { 100 | if(i % 4 === 0) { 101 | this.gba_wrapper.setScreen() 102 | this.gba_wrapper.frame() 103 | frames.push(this.gba_wrapper.getPixels()) 104 | this.gba_wrapper.removeScreen() 105 | } 106 | else this.gba_wrapper.frame() 107 | } 108 | this.gba_wrapper.setScreen() 109 | 110 | if(AppConfigService.getOrThrow('NODE_ENV') === "development") 111 | this.logger.debug(`${n} frames skipped in ${performance.now() - start}ms`) 112 | 113 | return frames 114 | } 115 | 116 | async createGifBuffer( 117 | frames: number[][] 118 | ) { 119 | const start = performance.now() 120 | 121 | const gifEncoder = new GifEncoder(240, 160) 122 | const stream = gifEncoder.createReadStream(); 123 | 124 | gifEncoder.setRepeat(-1).setDelay(64).setQuality(10); 125 | 126 | gifEncoder.start() 127 | const canvas = createCanvas(240, 160) 128 | const ctx = canvas.getContext('2d') 129 | let ctx_data = ctx.createImageData(240, 160); 130 | for(let i = 0; i < frames.length; i++) { 131 | for (let j=0; j < frames[i].length; j++){ 132 | ctx_data.data[j] = frames[i][j]; 133 | } 134 | ctx.putImageData(ctx_data, 0, 0); 135 | gifEncoder.addFrame(ctx.getImageData(0, 0, 240, 160).data) 136 | } 137 | gifEncoder.finish(); 138 | 139 | const gifBuffer = await buffer(stream) 140 | 141 | if(AppConfigService.getOrThrow('NODE_ENV') === "development") 142 | this.logger.debug(`Gif buffer created in: ${performance.now() - start}ms`) 143 | 144 | return gifBuffer 145 | } 146 | 147 | async save(res: Response) { 148 | const save = await this.gba_wrapper.createSaveState() 149 | 150 | const stream = Readable.from(save); 151 | 152 | res.attachment('save.txt') 153 | stream.pipe(res) 154 | this.skipFrames(600) 155 | } 156 | 157 | async load(loadObj: string) { 158 | 159 | await this.gba_wrapper.loadSaveState(loadObj) 160 | 161 | const frames = this.skipFrames(600, true) 162 | this.gifBuffer = await this.createGifBuffer(frames) 163 | 164 | const save = await this.gba_wrapper.createSaveState() 165 | await this.redis.client.set(this.redisKey, save) 166 | } 167 | 168 | getImageUrl(url_fragment: string) { 169 | const env = AppConfigService.getOrThrow('NODE_ENV') 170 | if(env === "production") 171 | return `./assets/gba/${url_fragment}` 172 | return `https://raw.githubusercontent.com/Charles-Chrismann/Charles-Chrismann/main/assets/gba/${url_fragment}` 173 | } 174 | 175 | async toMd() { 176 | const BASE_URL_GBA = `${AppConfigService.APP_BASE_URL}/gba` 177 | const env = AppConfigService.getOrThrow('NODE_ENV') 178 | const BASE_URL_GBA_WITH_ID = 179 | env === "production" 180 | ? `${BASE_URL_GBA}/${this.data['uuid']}` 181 | : `http://localhost:3000/gba/${this.data['uuid']}` 182 | let str = `

F*** Zodiac signs, let's play Pokemon together

\n` 183 | str += `

\n` 184 | 185 | str += ` \n \n \n` 186 | str += `
\n` 187 | str += ` \n \n \n` 188 | str += ` \n \n \n` 189 | str += ` \n \n \n` 190 | str += `
\n` 191 | str += ` \n \n \n` 192 | str += `
\n` 193 | str += ` \n \n \n` 194 | str += ` \n \n \n` 195 | str += `
\n` 196 | str += ` \n \n \n` 197 | str += ` \n \n \n` 198 | str += ` \n \n \n` 199 | str += ` \n \n \n` 200 | str += ` \n \n \n` 201 | str += `
\n` 202 | str += ` \n \n \n` 203 | str += ` \n \n \n` 204 | str += `
\n` 205 | str += ` \n \n \n` 206 | str += ` \n \n \n` 207 | 208 | str += `

\n\n
\n\n` 209 | 210 | return str 211 | } 212 | } -------------------------------------------------------------------------------- /src/games/minesweeper/classes/Minesweeper.ts: -------------------------------------------------------------------------------- 1 | import { Cell } from "./Cell"; 2 | 3 | export class Minesweeper { 4 | height: number; 5 | width: number; 6 | bombsCount: number; 7 | map = []; 8 | gameStatus = 'Not Started' 9 | gameLoosed = false; 10 | constructor(...setup: [Record] | [number, number, number]) { 11 | if(setup.length === 1) { 12 | const json = setup.shift() 13 | Object.assign(this, json) 14 | this.map = json.map.map(row => row.map(cell => new Cell(cell.x, cell.y, cell.value, cell.hidden))) 15 | return this 16 | } 17 | 18 | this.width = setup.shift(); 19 | this.height = setup.shift(); 20 | this.bombsCount = setup.shift(); 21 | this.CreateEmptyMap(); 22 | return this 23 | } 24 | 25 | CreateEmptyMap() { 26 | for(let i = 0; i < this.height; i++) { 27 | let row = [] 28 | for(let j = 0; j < this.width; j++) { 29 | row.push(new Cell(j, i, 0)) 30 | } 31 | this.map.push(row) 32 | } 33 | } 34 | 35 | CellExists(CellCoords) { 36 | return CellCoords.x >= 0 && CellCoords.x < this.width && CellCoords.y >= 0 && CellCoords.y < this.height 37 | } 38 | 39 | GetCell(click) { 40 | return this.CellExists(click) ? this.map[click.y][click.x] : null 41 | } 42 | 43 | HandleClick(click): boolean { 44 | if(this.gameStatus === 'Not Started') { 45 | this.PlaceBombs(click); 46 | this.gameStatus = 'Started'; 47 | let cell = this.GetCell(click) 48 | if(!cell) return false 49 | this.DiscoverRecursively(cell) 50 | } else if (this.gameStatus === 'Started') { 51 | let cell = this.GetCell(click) 52 | if(!cell) return false 53 | if(cell.value === 9) { 54 | this.reavealAllBombs() 55 | this.gameLoosed = true;// loose 56 | this.gameStatus = "Ended";// loose 57 | return true 58 | } else if(!cell.hidden) { 59 | return false 60 | } 61 | this.DiscoverRecursively(cell) 62 | } else if(this.gameStatus === 'Ended') return false 63 | return true 64 | } 65 | 66 | PlaceBombs(click) { 67 | let possibleBombsSpawns = [] 68 | this.map.forEach(row => { 69 | let rowToPush = [] 70 | row.forEach(cell => { 71 | rowToPush.push(cell) 72 | }) 73 | possibleBombsSpawns.push(rowToPush) 74 | }) 75 | 76 | // tops 77 | if(this.CellExists({x: click.x - 1, y: click.y - 1})) possibleBombsSpawns[click.y - 1].splice(click.x - 1, 1) // Splice modifie la longueur de la chaine donc click.x each time 78 | if(this.CellExists({x: click.x, y: click.y - 1})) possibleBombsSpawns[click.y - 1].splice(click.x - 1, 1) // Splice modifie la longueur de la chaine donc click.x each time 79 | if(this.CellExists({x: click.x + 1, y: click.y - 1})) possibleBombsSpawns[click.y - 1].splice(click.x - 1, 1) // Splice modifie la longueur de la chaine donc click.x each time 80 | 81 | // mids 82 | if(this.CellExists({x: click.x - 1, y: click.y})) possibleBombsSpawns[click.y].splice(click.x - 1, 1) 83 | if(this.CellExists({x: click.x, y: click.y})) possibleBombsSpawns[click.y].splice(click.x - 1, 1) 84 | if(this.CellExists({x: click.x + 1, y: click.y})) possibleBombsSpawns[click.y].splice(click.x - 1, 1) 85 | 86 | // bots 87 | if(this.CellExists({x: click.x - 1, y: click.y + 1})) possibleBombsSpawns[click.y + 1].splice(click.x - 1, 1) 88 | if(this.CellExists({x: click.x, y: click.y + 1})) possibleBombsSpawns[click.y + 1].splice(click.x - 1, 1) 89 | if(this.CellExists({x: click.x + 1, y: click.y + 1})) possibleBombsSpawns[click.y + 1].splice(click.x - 1, 1) 90 | 91 | possibleBombsSpawns = possibleBombsSpawns.flat() 92 | possibleBombsSpawns = possibleBombsSpawns.sort((a, b) => 0.5 - Math.random()); 93 | let bombCells = possibleBombsSpawns.splice(0, this.bombsCount) 94 | 95 | bombCells.forEach(bombCell => { 96 | this.map[bombCell.y][bombCell.x].value = 9 97 | 98 | if(this.map[bombCell.y - 1]) { 99 | if(this.map[bombCell.y - 1][bombCell.x - 1]) { 100 | if(this.map[bombCell.y - 1][bombCell.x - 1].value !== 9) this.map[bombCell.y - 1][bombCell.x - 1].value++ 101 | } 102 | } 103 | 104 | if(this.map[bombCell.y - 1]) { 105 | if(this.map[bombCell.y - 1][bombCell.x]) { 106 | if(this.map[bombCell.y - 1][bombCell.x].value !== 9) this.map[bombCell.y - 1][bombCell.x].value++ 107 | } 108 | } 109 | 110 | if(this.map[bombCell.y - 1]) { 111 | if(this.map[bombCell.y - 1][bombCell.x + 1]) { 112 | if(this.map[bombCell.y - 1][bombCell.x + 1].value !== 9) this.map[bombCell.y - 1][bombCell.x + 1].value++ 113 | } 114 | } 115 | 116 | 117 | 118 | if(this.map[bombCell.y]) { 119 | if(this.map[bombCell.y][bombCell.x - 1]) { 120 | if(this.map[bombCell.y][bombCell.x - 1].value !== 9) this.map[bombCell.y][bombCell.x - 1].value++ 121 | } 122 | } 123 | 124 | if(this.map[bombCell.y]) { 125 | if(this.map[bombCell.y][bombCell.x + 1]) { 126 | if(this.map[bombCell.y][bombCell.x + 1].value !== 9) this.map[bombCell.y][bombCell.x + 1].value++ 127 | } 128 | } 129 | 130 | 131 | 132 | 133 | if(this.map[bombCell.y + 1]) { 134 | if(this.map[bombCell.y + 1][bombCell.x - 1]) { 135 | if(this.map[bombCell.y + 1][bombCell.x - 1].value !== 9) this.map[bombCell.y + 1][bombCell.x - 1].value++ 136 | } 137 | } 138 | 139 | if(this.map[bombCell.y + 1]) { 140 | if(this.map[bombCell.y + 1][bombCell.x]) { 141 | if(this.map[bombCell.y + 1][bombCell.x].value !== 9) this.map[bombCell.y + 1][bombCell.x].value++ 142 | } 143 | } 144 | 145 | if(this.map[bombCell.y + 1]) { 146 | if(this.map[bombCell.y + 1][bombCell.x + 1]) { 147 | if(this.map[bombCell.y + 1][bombCell.x + 1].value !== 9) this.map[bombCell.y + 1][bombCell.x + 1].value++ 148 | } 149 | } 150 | }) 151 | } 152 | 153 | DiscoverRecursively(cell) { 154 | cell.revealCell() 155 | if(cell.value !== 0) return // evite si click au hasard sur un 5 de reveal les 0 a coté, + en recursif les numéro ne doivent pas montrer leurs siblibgs 156 | 157 | let nextCell; 158 | let cellCoordsToTest; 159 | 160 | // top left 161 | cellCoordsToTest = {x: cell.x - 1, y: cell.y - 1} 162 | if(this.CellExists(cellCoordsToTest)) { 163 | nextCell = this.GetCell(cellCoordsToTest) 164 | if(nextCell.hidden) this.DiscoverRecursively(nextCell) 165 | } 166 | 167 | // top 168 | cellCoordsToTest = {x: cell.x, y: cell.y - 1} 169 | if(this.CellExists(cellCoordsToTest)) { 170 | nextCell = this.GetCell(cellCoordsToTest) 171 | if(nextCell.hidden) this.DiscoverRecursively(nextCell) 172 | } 173 | 174 | // top right 175 | cellCoordsToTest = {x: cell.x + 1, y: cell.y - 1} 176 | if(this.CellExists(cellCoordsToTest)) { 177 | nextCell = this.GetCell(cellCoordsToTest) 178 | if(nextCell.hidden) this.DiscoverRecursively(nextCell) 179 | } 180 | 181 | // left 182 | cellCoordsToTest = {x: cell.x - 1, y: cell.y} 183 | if(this.CellExists(cellCoordsToTest)) { 184 | nextCell = this.GetCell(cellCoordsToTest) 185 | if(nextCell.hidden) this.DiscoverRecursively(nextCell) 186 | } 187 | 188 | // right 189 | cellCoordsToTest = {x: cell.x + 1, y: cell.y} 190 | if(this.CellExists(cellCoordsToTest)) { 191 | nextCell = this.GetCell(cellCoordsToTest) 192 | if(nextCell.hidden) this.DiscoverRecursively(nextCell) 193 | } 194 | 195 | // bot left 196 | cellCoordsToTest = {x: cell.x - 1, y: cell.y + 1} 197 | if(this.CellExists(cellCoordsToTest)) { 198 | nextCell = this.GetCell(cellCoordsToTest) 199 | if(nextCell.hidden) this.DiscoverRecursively(nextCell) 200 | } 201 | 202 | // bot 203 | cellCoordsToTest = {x: cell.x, y: cell.y + 1} 204 | if(this.CellExists(cellCoordsToTest)) { 205 | nextCell = this.GetCell(cellCoordsToTest) 206 | if(nextCell.hidden) this.DiscoverRecursively(nextCell) 207 | } 208 | 209 | // bot right 210 | cellCoordsToTest = {x: cell.x + 1, y: cell.y + 1} 211 | if(this.CellExists(cellCoordsToTest)) { 212 | nextCell = this.GetCell(cellCoordsToTest) 213 | if(nextCell.hidden) this.DiscoverRecursively(nextCell) 214 | } 215 | } 216 | 217 | reavealAllBombs() { 218 | this.map.flat().filter(cell => cell.value === 9 && cell.hidden).forEach(cell => cell.revealCell()) 219 | } 220 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Dynamic Readme 2 | 3 | This NestJs app allows you to create a fully interactive profile README, such as [mine](https://github.com/Charles-Chrismann), by displaying functional minigames on the page. 4 | 5 | It is inspired by [some other dynamic profile READMEs](https://github.com/abhisheknaiidu/awesome-github-profile-readme) (I remember [timburgan's one](https://github.com/timburgan/timburgan) as a motivation to start) that work with GitHub Actions on issues or by images, like the [profile views counter service](https://github.com/antonkomarev/github-profile-views-counter). 6 | 7 | This project takes a different approach by creating a new commit on the repository for most of the provided features. 8 | 9 |
10 | 📚 Table of Contents 11 | 12 | - 💭 [Philosophy](#-philosophy) 13 | - 🏗️ [Project Structure](#%EF%B8%8F-project-structure) 14 | - 🛠️ [Installation](#%EF%B8%8F-installation) 15 | - 📝 [To Do](#-to-do) 16 | - ✨ [Contributing](#-contributing) 17 | - ⚖️ [License](#%EF%B8%8F-license) 18 | 19 |
20 | 21 | ## 💭 Philosophy 22 | 23 | As you can see on many GitHub users' profiles, the profile is often divided into multiple sections such as "About Me", "My Projects", "My Tools", "Contact Me" etc. 24 | 25 | This project follows the same philosophy by dividing the file into what are called **modules**, which handle the logic and rendering of each section of the final file. 26 | 27 | ## 🏗️ Project Structure 28 | 29 | The core files and folders of the app are as follows: 30 | 31 | - **`src/modules`**: contains both static and dynamic modules. Each module encapsulates the logic for its section of the file and is also responsible for rendering that specific section. 32 | - **`src/State.js`**: the `State` class manages all modules and the final rendering of the file. 33 | - **`src/services/ConfigService.ts`**: a utility class used to access environment variables and the configuration object. 34 | - **`src/services/ReadmeService.ts`**: a utility class used to interact with GitHub. Most of the time, you’ll want to call `ReadmeService.updateReadmeAndRedirect()`. (Use `ReadmeService.doNothingAndRedirect()` if there are no changes to apply.) 35 | - **`src/services/RequestService.ts`**: a utility class used to interact with the GitHub REST and GraphQL APIs. 36 | 37 | A module can extend either the **AbstractStaticModule**, which means it is not likely to change — for example, an “About Me” section. 38 | 39 | A module can also extend the **AbstractDynamicModule**, which means it will change over time — for example, a chess game or a “Latest Followers” section. 40 | 41 | The workflow in all modules/games follows the same pattern: 42 | 43 | 1. The user clicks a link in the README and makes a GET request to the app. 44 | 2. The involved controller is called. 45 | 3. The associated service is called. 46 | 4. If a commit is needed, the app waits for the commit to be performed. 47 | 5. The app returns a redirection to the client for the profile README page that has been updated. 48 | 49 | This results in a seemingly simple page refresh for the user. 50 | 51 | > [!NOTE] 52 | > GitHub's cache system seems to work differently for logged-in users and non-logged-in users; non-logged-in users may not be able to instantly view new changes. 53 | 54 | ## 🛠️ Installation 55 | 56 | Requirements: 57 | - Docker 58 | - Node & NPM 59 | 60 | Steps: 61 | 1. git clone https://github.com/Charles-Chrismann/dynamic-readme 62 | 2. dupe .env.example and rename it .env, fill variables 63 | 3. dupe config.example.json and rename it config.json, fill variables 64 | 65 | > [!NOTE] 66 | > Some modules like the Gba module might required additional setup 67 | 68 |
69 | 👨‍💻 Developpement 70 | 71 | ```sh 72 | npm run dev 73 | ``` 74 | 75 | equivalent to: `docker compose -f docker-compose.dev.yml up --watch` 76 | 77 | > you might need to trigger the hot reload to get the latest version of the app. 78 | 79 |
80 | 81 |
82 | 🚀 Production 83 | 84 | ```sh 85 | npm run prod 86 | ``` 87 | 88 | equivalent to: `docker compose -f docker-compose.prod.yml up --build -d` 89 | 90 |
91 | 92 |
93 | 📂 Utility commands 94 | 95 | delet all volumes 96 | 97 | ```sh 98 | docker compose -f docker-compose.dev.yml --env-file .env.dev down -v 99 | ``` 100 | 101 | docker system df 102 | docker builder prune 103 | 104 | redis cli 105 | 106 | ``` 107 | redis-cli -h localhost -p 6379 108 | KEYS * 109 | ``` 110 | 111 | Backup 112 | 113 | ```sh 114 | docker exec dr-prod-redis redis-cli save 115 | docker cp dr-prod-redis:/data/dump.rdb ./dump.rdb 116 | ``` 117 | 118 | Restore 119 | 120 | ```sh 121 | docker cp ./dump.rdb dr-prod-redis:/data/dump.rdb 122 | docker restart dr-prod-redis 123 | ``` 124 | 125 | If docker seems to use an old versin of the code 126 | 127 | ```sh 128 | docker compose -f docker-compose.dev.yml --env-file .env.dev down --volumes --remove-orphans 129 | docker compose -f docker-compose.dev.yml --env-file .env.dev build --no-cache 130 | ``` 131 | 132 |
133 | 134 | ## ✨ Contributing 135 | 136 | Contributions are welcome! 137 | If you want to improve the project, fix a bug, or add a new feature, feel free to open a pull request or submit an issue. 138 | 139 | Before contributing, please make sure your code is clean, consistent, and well-documented. 140 | Try to follow the existing project structure and naming conventions to keep everything coherent. 141 | 142 | ## ⚖️ License 143 | 144 | This project is licensed under the **GNU General Public License v3.0 (GPL-3.0)**. 145 | 146 | This means that: 147 | - You are free to **use, modify, and distribute** the software. 148 | - If you distribute a modified version, you **must make your source code available** under the same license (GPL-3.0). 149 | - You **cannot** make the software proprietary or distribute it under a different license. 150 | - Any derivative work must remain **open source** and **credit the original author**. 151 | 152 | 👉 In short: you can do almost anything with the code, as long as you **keep it open source** and **share your modifications** under the same terms. 153 | 154 | For more details, see the full license text in the [LICENSE](./LICENSE) file. 155 | 156 | 157 | ## 📝 To Do 158 | 159 | This section is not mean to be user friendly, just taking notes 160 | 161 |
162 | 📝 To do 163 | 164 | screenshot of the game 165 | 166 | playing time 167 | 168 | disable some games/modules 169 | 170 | upgrade config.md 171 | 172 | ui to update the config file without restarting the app 173 | 174 | provide a raw module for the config file 175 | 176 | make dynamic/followers independant from trigger 177 | 178 | make tigger content configurable 179 | 180 | add 3third party such as github statistics 181 | 182 | fix dynamic/followers last works 183 | 184 | implement the `scoreboard` options in games/gba 185 | 186 | add steps for configurate each module 187 | - gba 188 | 189 | Add options for the minesweeper, width, height 190 | 191 | Add default config files `config.default.json` 192 | 193 | for games with a reset option button, switch to: 194 | 195 | ```jsonc 196 | { 197 | "reset": { 198 | "display": true, 199 | "content": "reset game" 200 | } 201 | } 202 | 203 | ``` 204 | 205 | Add hide reset btn for chess, and protect the reset route 206 | 207 | Add hide reset btn for Minesweeper, and protect the reset route 208 | 209 | UI for manage the app, reset games, with authentitcation 210 | 211 | protect the reset route for wordle 212 | 213 | add issue template 214 | 215 | add multiple backup for gba + screen/gif of la view 216 | 217 | add wordle custom response in case of bad submission (too long/ invalid) 218 | 219 | add wordle responve include wordle 220 | 221 | add wordle way to submit a new guess as a response of an issue 222 | 223 | add display scoreboard for gab 224 | 225 | add ui + connection live play for gba 226 | 227 | add display scoreboard for game boy color 228 | 229 | add display scoreboard for wordle 230 | 231 | create a full configuration tutorial for each module 232 | 233 | add thing to think on vm such as date for wordle reset for example 234 | 235 | switch chess to chess.js 236 | 237 | add chess plays orders 238 | 239 | add chess game progress 240 | 241 | add a save-reset for the app (functions that return a zip, that can be provided to a blank app to return to the at time created zip without reconfiguring) 242 | 243 | check config script 244 | 245 | add json compress config 246 | 247 | make it publishable on dockerhub (volume for config.json) 248 | 249 | add single `config` folder 250 | 251 | make roms optionnal 252 | 253 | complete setup steps 254 | 255 | explain env variables 256 | 257 | better readme (illustrations) 258 | 259 | add badge support for contact module 260 | 261 | add custom title for contact (reach me) module 262 | 263 | add admin dashboard 264 | 265 | disable game schedule if not runned 266 | 267 | add possibiity to disable games (gameboy service should not save if not displayed) & support for resume 268 | 269 | add theme configuration with colors and style buttons 270 | 271 | store md in variable to avoid rereender 272 | 273 | Add translation keys 274 | 275 | needsRender: rerender instantly instead of just setting variable and wait for next render call 276 | 277 | Add option to commit on start 278 | 279 | add live way to disable module 280 | 281 |
282 | 283 | -------------------------------------------------------------------------------- /src/games/gameboy/gameboy.service.ts: -------------------------------------------------------------------------------- 1 | import * as fs from 'fs'; 2 | import * as path from 'path'; 3 | import { Readable } from 'stream'; 4 | import { Injectable, Logger, OnModuleInit } from '@nestjs/common'; 5 | import { createCanvas, ImageData } from '@napi-rs/canvas'; 6 | import { compress, decompress } from 'compress-json'; 7 | import { Response } from 'express'; 8 | import { Cron } from '@nestjs/schedule'; 9 | import { RedisService } from 'src/redis/redis.service'; 10 | import { GifEncoder } from '@skyra/gifenc'; 11 | import IReadmeModule from 'src/declarations/readme-module.interface'; 12 | const Gameboy = require('serverboy') 13 | 14 | const rom = fs.readFileSync(path.join(process.env.PWD, 'roms', process.env.ROM_NAME)) 15 | 16 | @Injectable() 17 | export class GameboyService implements OnModuleInit, IReadmeModule { 18 | private readonly logger = new Logger(GameboyService.name) 19 | 20 | gameboy_instance: any 21 | renderInterval: NodeJS.Timer | null 22 | renderTimeout: NodeJS.Timeout | null 23 | lastInputFrames: number[][] = [] 24 | 25 | constructor(private readonly redis: RedisService) {} 26 | 27 | async onModuleInit() { 28 | const gi = JSON.parse(await this.redis.client.get('gameboy:instance')) 29 | if(gi) { 30 | this.load(gi) 31 | } 32 | else { 33 | this.gameboy_instance = new Gameboy() 34 | this.gameboy_instance.loadRom(rom) 35 | this.setRenderSession() 36 | } 37 | } 38 | 39 | @Cron(process.env.EMU_BACKUP_CRON) 40 | async backup() { 41 | this.logger.log('[SHEDULED] Saving gameboy') 42 | const save = this.gameboy_instance[Object.keys(this.gameboy_instance)[0]].gameboy.saveState() 43 | this.redis.client.set('gameboy:instance', JSON.stringify(compress(save))) 44 | } 45 | 46 | setRenderInterval(frameInterval = 5) { 47 | this.renderInterval = setInterval(() => { 48 | this.gameboy_instance.doFrame() 49 | }, frameInterval) 50 | } 51 | 52 | stopRenderInterval(intervalId) { 53 | clearInterval(intervalId) 54 | } 55 | 56 | setRenderTimeout(intervalId, timeout = 60000) { 57 | this.renderTimeout = setTimeout(() => this.stopRenderInterval(intervalId), timeout) 58 | } 59 | 60 | stopRenderTimeout() { 61 | clearTimeout(this.renderTimeout) 62 | } 63 | 64 | setRenderSession() { 65 | this.setRenderInterval() 66 | this.setRenderTimeout(this.renderInterval) 67 | } 68 | 69 | stopRenderSession() { 70 | this.stopRenderInterval(this.renderInterval) 71 | this.stopRenderTimeout() 72 | } 73 | 74 | skipFrames(n) { 75 | const frames = [] 76 | for(let i = 0; i < n; i++) { 77 | if(i % 4 === 0) frames.push(this.gameboy_instance.doFrame()) 78 | else this.gameboy_instance.doFrame() 79 | } 80 | return frames 81 | } 82 | 83 | async frame(res: Response) { 84 | const canvas = createCanvas(160, 144) 85 | const ctx = canvas.getContext('2d') 86 | let ctx_data = ctx.createImageData(160, 144); 87 | 88 | const screen = this.gameboy_instance.doFrame() 89 | 90 | for (let i=0; i < screen.length; i++){ 91 | ctx_data.data[i] = screen[i]; 92 | } 93 | 94 | ctx.putImageData(ctx_data, 0, 0); 95 | 96 | const stream = Readable.from(await canvas.encode('png')) 97 | res.setHeader('Content-Type', 'image/png') 98 | res.setHeader('Cache-Control', 'public, max-age=0') 99 | stream.pipe(res) 100 | } 101 | 102 | gif(res: Response) { 103 | res.setHeader('Content-Type', 'image/gif') 104 | res.setHeader('Cache-Control', 'public, max-age=0') 105 | 106 | const gifEncoder = new GifEncoder(160, 144) 107 | .setRepeat(-1) 108 | .setDelay(64) 109 | .setQuality(10); 110 | gifEncoder.createWriteStream().pipe(res) 111 | gifEncoder.start() 112 | const canvas = createCanvas(160, 144) 113 | const ctx = canvas.getContext('2d') 114 | let ctx_data = ctx.createImageData(160, 144); 115 | for(let i = 0; i < this.lastInputFrames.length; i++) { 116 | for (let j=0; j < this.lastInputFrames[i].length; j++){ 117 | ctx_data.data[j] = this.lastInputFrames[i][j]; 118 | } 119 | ctx.putImageData(ctx_data, 0, 0); 120 | gifEncoder.addFrame(ctx.getImageData(0, 0, 160, 144).data) 121 | } 122 | gifEncoder.finish(); 123 | } 124 | 125 | input(input: string) { 126 | this.stopRenderSession() 127 | this.lastInputFrames = [] 128 | 129 | for(let i = 0; i < 5; i++) { 130 | this.gameboy_instance.pressKey(input) 131 | this.lastInputFrames.push(this.gameboy_instance.doFrame()) 132 | } 133 | 134 | this.lastInputFrames = this.lastInputFrames.concat(this.skipFrames(300)) 135 | 136 | this.setRenderSession() 137 | } 138 | 139 | save(res) { 140 | this.stopRenderSession() 141 | const save = this.gameboy_instance[Object.keys(this.gameboy_instance)[0]].gameboy.saveState() 142 | 143 | const stream = Readable.from(JSON.stringify(compress(save))); 144 | 145 | res.setHeader('Content-Type', 'application/json'); 146 | res.attachment('save.json') 147 | stream.pipe(res) 148 | this.setRenderSession() 149 | } 150 | 151 | load(loadObj) { 152 | this.stopRenderSession() 153 | 154 | this.gameboy_instance = new Gameboy() 155 | this.gameboy_instance.loadRom(rom) 156 | this.gameboy_instance[Object.keys(this.gameboy_instance)[0]].gameboy.saving(decompress(loadObj)) 157 | 158 | this.setRenderSession() 159 | } 160 | 161 | async renderInputBoard(BASE_URL: string) { 162 | let str = `\n \n` 163 | str += ' \n \n \n' 164 | str += ` \n \n \n \n \n \n \n` 165 | const playersIds = await this.redis.client.keys("gameboy:players:*") 166 | const players = await Promise.all(playersIds.map(player => this.redis.client.hGetAll(player))) 167 | const users = await Promise.all(players.map(player => this.redis.client.hGetAll(`user:${player.id}`))) 168 | const rowsDatas = players.map((player, index) => ({...player, ...users[index]})).sort((a, b) => +b.inputCount - +a.inputCount) 169 | str += rowsDatas.map((row, i) => ` \n \n \n \n \n \n`).join('') 170 | str += ` \n \n \n` 171 | str += ` \n
Game Contributions
RankPlayerInputs
${i + 1}profil picture@${row.login}${row.inputCount}
Play with your Github account here !
\n\n` 172 | 173 | return str 174 | } 175 | 176 | async toMd(BASE_URL: string) { 177 | let str = `

GitHub Plays Pokemon ?

\n` 178 | str += `

` 179 | 180 | str += ` \n \n \n` 181 | str += `
\n` 182 | str += ` \n \n \n` 183 | str += ` \n \n \n` 184 | str += ` \n \n \n` 185 | str += `
\n` 186 | str += ` \n \n \n` 187 | str += `
\n` 188 | str += ` \n \n \n` 189 | str += ` \n \n \n` 190 | str += ` \n \n \n` 191 | str += `
\n` 192 | str += ` \n \n \n` 193 | str += ` \n \n \n` 194 | str += ` \n \n \n` 195 | str += ` \n \n \n` 196 | str += ` \n \n \n` 197 | str += `
\n` 198 | str += ` \n \n \n` 199 | str += ` \n \n \n` 200 | str += ` \n \n \n` 201 | str += `
\n` 202 | str += ` \n \n \n` 203 | str += ` \n \n \n` 204 | str += ` \n \n \n` 205 | str += ` \n \n \n` 206 | str += `
\n` 207 | str += ` \n \n \n\n` 208 | 209 | str += await this.renderInputBoard(BASE_URL) 210 | 211 | str += `

\n\n
\n\n` 212 | 213 | return str 214 | } 215 | } 216 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------