├── .dockerignore ├── .env.example ├── .eslintrc.js ├── .gitignore ├── .prettierrc ├── Dockerfile ├── LICENSE ├── README.md ├── config.example.json ├── config.md ├── docker-compose.dev.yml ├── docker-compose.prod.yml ├── nest-cli.json ├── package.json ├── public ├── .gitkeep ├── client.html ├── css │ ├── style.css │ ├── style.css.map │ └── style.scss ├── index.html ├── js │ └── main.js └── trigger.webp ├── roms └── .gitkeep ├── src ├── app.controller.spec.ts ├── app.controller.ts ├── app.module.ts ├── app.service.ts ├── assets │ └── emojis │ │ ├── boom.png │ │ ├── eight.png │ │ ├── five.png │ │ ├── four.png │ │ ├── one.png │ │ ├── seven.png │ │ ├── six.png │ │ ├── three.png │ │ └── two.png ├── auth │ ├── auth.controller.spec.ts │ ├── auth.controller.ts │ ├── auth.module.ts │ ├── auth.service.spec.ts │ └── auth.service.ts ├── config │ ├── config.service.spec.ts │ └── config.service.ts ├── declarations │ ├── config.interface.ts │ ├── readme-module.interface.ts │ └── structure.interface.ts ├── 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 │ │ ├── chess.controller.ts │ │ ├── chess.service.ts │ │ └── classes │ │ │ ├── Bishop.ts │ │ │ ├── Chess.ts │ │ │ ├── King.ts │ │ │ ├── Knight.ts │ │ │ ├── Pawn.ts │ │ │ ├── Piece.ts │ │ │ ├── Queen.ts │ │ │ ├── Rook.ts │ │ │ └── utils.ts │ ├── gameboy │ │ ├── gameboy.controller.ts │ │ ├── gameboy.gateway.ts │ │ ├── gameboy.module.ts │ │ └── gameboy.service.ts │ ├── games.module.ts │ ├── gba │ │ ├── gba.controller.ts │ │ ├── gba.module.ts │ │ └── gba.service.ts │ ├── minesweeper │ │ ├── classes │ │ │ ├── Cell.ts │ │ │ └── Minesweeper.ts │ │ ├── minesweeper.controller.ts │ │ └── minesweeper.service.ts │ ├── sudoku │ │ ├── sudoku.controller.ts │ │ ├── sudoku.module.ts │ │ └── sudoku.service.ts │ └── wordle │ │ ├── word_list.ts │ │ ├── wordle.controller.ts │ │ ├── wordle.module.ts │ │ └── wordle.service.ts ├── main.ts ├── readme │ ├── Renderer.ts │ ├── readme.module.ts │ └── readme.service.ts ├── redis │ ├── redis.module.ts │ └── redis.service.ts ├── request │ ├── request.module.ts │ └── request.service.ts ├── trigger │ ├── trigger.controller.ts │ └── trigger.module.ts └── users │ ├── users.module.ts │ ├── users.service.spec.ts │ └── users.service.ts ├── test ├── app.e2e-spec.ts └── jest-e2e.json ├── tsconfig.build.json └── tsconfig.json /.dockerignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | .git 4 | 5 | .env* 6 | config*.json -------------------------------------------------------------------------------- /.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="" -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /.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 -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:20 2 | WORKDIR /usr/src/app 3 | COPY package*.json ./ 4 | RUN npm install --silent 5 | COPY . . 6 | RUN npm run build 7 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | The workflow in all modules/games follows the same pattern: 10 | 11 | 1. The user clicks a link in the README and makes a GET request to the app. 12 | 2. The involved controller is called. 13 | 3. The associated service is called. 14 | 4. If a commit is needed, the app waits for the commit to be performed. 15 | 5. The app returns a redirection to the client for the profile README page that has been updated. 16 | 17 | This results in a seemingly simple page refresh for the user. 18 | 19 | **Please note**: 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. 20 | 21 | ## Setup 22 | 23 | Requirements: 24 | - Docker 25 | 26 | Steps: 27 | 1. git clone https://github.com/Charles-Chrismann/dynamic-readme 28 | 4. dupe .env.example and rename it .env, fill variables 29 | 4. dupe config.example.json and rename it config.json, fill variables 30 | 5. dl roms and put them in the `roms` folder 31 | 32 | ## Developpement 33 | 34 | ```sh 35 | npm run dev 36 | ``` 37 | 38 | equivalent to: `docker compose -f docker-compose.dev.yml up --watch` 39 | 40 | > you might need to trigger the hot reload to get the latest version of the app. 41 | 42 | ## Production 43 | 44 | ```sh 45 | npm run prod 46 | ``` 47 | 48 | equivalent to: `docker compose -f docker-compose.prod.yml up --build -d` 49 | 50 | ## Utility commands 51 | 52 | delet all volumes 53 | 54 | ```sh 55 | docker compose -f docker-compose.dev.yml --env-file .env.dev down -v 56 | ``` 57 | 58 | docker system df 59 | docker builder prune 60 | 61 | redis cli 62 | 63 | ``` 64 | redis-cli -h localhost -p 6379 65 | KEYS * 66 | ``` 67 | 68 | Backup 69 | 70 | ```sh 71 | docker exec dr-prod-redis redis-cli save 72 | docker cp dr-prod-redis:/data/dump.rdb ./dump.rdb 73 | ``` 74 | 75 | Restore 76 | 77 | ```sh 78 | docker cp ./dump.rdb dr-prod-redis:/data/dump.rdb 79 | docker restart dr-prod-redis 80 | ``` 81 | 82 | note: production file not ready 83 | 84 | ## To add 85 | 86 | screenshot of the game 87 | 88 | playing time 89 | 90 | disable some games/modules 91 | 92 | upgrade config.md 93 | 94 | ui to update the config file without restarting the app 95 | 96 | provide a raw module for the config file 97 | 98 | make dynamic/followers independant from trigger 99 | 100 | make tigger content configurable 101 | 102 | add 3third party such as github statistics 103 | 104 | fix dynamic/followers last works 105 | 106 | implement the `scoreboard` options in games/gba 107 | 108 | add steps for configurate each module 109 | - gba 110 | 111 | Add options for the minesweeper, width, height 112 | 113 | Add default config files `config.default.json` 114 | 115 | for games with a reset option button, switch to: 116 | 117 | ```jsonc 118 | { 119 | "reset": { 120 | "display": true, 121 | "content": "reset game" 122 | } 123 | } 124 | 125 | ``` 126 | 127 | Add hide reset btn for chess, and protect the reset route 128 | 129 | Add hide reset btn for Minesweeper, and protect the reset route 130 | 131 | UI for manage the app, reset games, with authentitcation 132 | 133 | protect the reset route for wordle 134 | 135 | add issue template 136 | 137 | add multiple backup for gba + screen/gif of la view 138 | 139 | add wordle custom response in case of bad submission (too long/ invalid) 140 | 141 | add wordle responve include wordle 142 | 143 | add wordle way to submit a new guess as a response of an issue 144 | 145 | add display scoreboard for gab 146 | 147 | add ui + connection live play for gba 148 | 149 | add display scoreboard for game boy color 150 | 151 | add display scoreboard for wordle 152 | 153 | create a full configuration tutorial for each module 154 | 155 | add thing to think on vm such as date for wordle reset for example 156 | 157 | switch chess to chess.js 158 | 159 | add chess plays orders 160 | 161 | add chess game progress 162 | 163 | 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) 164 | 165 | check config script 166 | 167 | add json compress config 168 | 169 | make it publishable on dockerhub (volume for config.json) 170 | 171 | add single `config` folder 172 | 173 | make roms optionnal 174 | 175 | complete setup steps 176 | 177 | explain env variables 178 | 179 | better readme (illustrations) 180 | 181 | add badge support for contact module 182 | 183 | add custom title for contact (reach me) module 184 | 185 | add admin dashboard 186 | 187 | disable game schedule if not runned 188 | 189 | add possibiity to disable games (gameboy service should not save if not displayed) & support for resume -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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 | ``` -------------------------------------------------------------------------------- /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 | # - NO_COMMIT=true 19 | command: npm run start:dev 20 | ports: 21 | - 3000:${APP_PORT} 22 | networks: 23 | - app-network 24 | depends_on: 25 | - redis-dev 26 | redis-dev: 27 | container_name: dr-dev-redis 28 | restart: unless-stopped 29 | image: redis:alpine 30 | ports: 31 | - 6379:6379 32 | volumes: 33 | - redis-data:/data 34 | networks: 35 | - app-network 36 | 37 | volumes: 38 | redis-data: 39 | networks: 40 | app-network: -------------------------------------------------------------------------------- /docker-compose.prod.yml: -------------------------------------------------------------------------------- 1 | version: '3.7' 2 | services: 3 | dynamic-readme-prod: 4 | container_name: dr-prod-app 5 | restart: unless-stopped 6 | build: 7 | context: . 8 | dockerfile: Dockerfile 9 | env_file: 10 | - .env 11 | environment: 12 | - NODE_ENV=production 13 | command: npm run start:prod 14 | ports: 15 | - ${DOCKER_LOCAL_PORT}:${APP_PORT} 16 | networks: 17 | - app-network-prod 18 | volumes: 19 | - ./config.json:/usr/src/app/config.json 20 | depends_on: 21 | - redis-prod 22 | redis-prod: 23 | container_name: dr-prod-redis 24 | restart: unless-stopped 25 | image: redis:alpine 26 | ports: 27 | - 6379:6379 28 | volumes: 29 | - redis-data-prod:/data 30 | networks: 31 | - app-network-prod 32 | 33 | volumes: 34 | redis-data-prod: 35 | networks: 36 | app-network-prod: -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | "prod": "docker compose -f docker-compose.prod.yml up --build -d", 11 | "build": "nest build", 12 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", 13 | "start": "nest start", 14 | "start:dev": "nest start --watch", 15 | "start:debug": "nest start --debug --watch", 16 | "start:prod": "node dist/main", 17 | "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", 18 | "test": "jest", 19 | "test:watch": "jest --watch", 20 | "test:cov": "jest --coverage", 21 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", 22 | "test:e2e": "jest --config ./test/jest-e2e.json", 23 | "sass:watch": "sass --watch public/css/style.scss:public/css/style.css" 24 | }, 25 | "dependencies": { 26 | "@napi-rs/canvas": "^0.1.53", 27 | "@nestjs/common": "^10.2.7", 28 | "@nestjs/config": "^3.1.1", 29 | "@nestjs/core": "^10.2.7", 30 | "@nestjs/jwt": "^10.1.1", 31 | "@nestjs/platform-express": "^10.2.7", 32 | "@nestjs/platform-socket.io": "^10.2.7", 33 | "@nestjs/schedule": "^3.0.4", 34 | "@nestjs/serve-static": "^4.0.0", 35 | "@skyra/gifenc": "^1.0.1", 36 | "axios": "^1.4.0", 37 | "compress-json": "^2.1.2", 38 | "cron": "^3.1.6", 39 | "gbats": "^1.0.9", 40 | "lodash-es": "^4.17.21", 41 | "octokit": "^2.0.14", 42 | "redis": "^4.6.10", 43 | "rxjs": "^7.2.0", 44 | "serverboy": "gitlab:piglet-plays/serverboy.js" 45 | }, 46 | "devDependencies": { 47 | "@nestjs/cli": "^9.0.0", 48 | "@nestjs/schematics": "^9.0.0", 49 | "@nestjs/testing": "^10.2.7", 50 | "@types/express": "^4.17.13", 51 | "@types/gifencoder": "^2.0.1", 52 | "@types/jest": "29.2.4", 53 | "@types/lodash": "^4.14.194", 54 | "@types/lodash-es": "^4.17.7", 55 | "@types/node": "^18.11.18", 56 | "@types/supertest": "^2.0.11", 57 | "@typescript-eslint/eslint-plugin": "^5.0.0", 58 | "@typescript-eslint/parser": "^5.0.0", 59 | "eslint": "^8.0.1", 60 | "eslint-config-prettier": "^8.3.0", 61 | "eslint-plugin-prettier": "^4.0.0", 62 | "jest": "29.3.1", 63 | "prettier": "^2.3.2", 64 | "source-map-support": "^0.5.20", 65 | "supertest": "^6.1.3", 66 | "ts-jest": "29.0.3", 67 | "ts-loader": "^9.2.3", 68 | "ts-node": "^10.0.0", 69 | "tsconfig-paths": "4.1.1", 70 | "typescript": "^4.7.4" 71 | }, 72 | "jest": { 73 | "moduleFileExtensions": [ 74 | "js", 75 | "json", 76 | "ts" 77 | ], 78 | "rootDir": "src", 79 | "testRegex": ".*\\.spec\\.ts$", 80 | "transform": { 81 | "^.+\\.(t|j)s$": "ts-jest" 82 | }, 83 | "collectCoverageFrom": [ 84 | "**/*.(t|j)s" 85 | ], 86 | "coverageDirectory": "../coverage", 87 | "testEnvironment": "node" 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /public/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/d407d5479d5a2093b1e7904cb0764a71853c604d/public/.gitkeep -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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"} -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Document 7 | 8 | 9 | Hello World ? 10 | 11 | -------------------------------------------------------------------------------- /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 | })() -------------------------------------------------------------------------------- /public/trigger.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/d407d5479d5a2093b1e7904cb0764a71853c604d/public/trigger.webp -------------------------------------------------------------------------------- /roms/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/d407d5479d5a2093b1e7904cb0764a71853c604d/roms/.gitkeep -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /src/app.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get } from '@nestjs/common'; 2 | import { AppService } from './app.service'; 3 | import { ReadmeService } from './readme/readme.service'; 4 | 5 | @Controller() 6 | export class AppController { 7 | constructor( 8 | private readonly appService: AppService, 9 | private readonly readmeService: ReadmeService, 10 | ) {} 11 | 12 | // @Get() 13 | // async getHello(): Promise { 14 | // return this.appService.getHello(); 15 | // } 16 | } 17 | -------------------------------------------------------------------------------- /src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { join } from 'path'; 2 | import { Module } from '@nestjs/common'; 3 | import { ServeStaticModule } from '@nestjs/serve-static'; 4 | import { AppController } from './app.controller'; 5 | import { AppService } from './app.service'; 6 | import { GamesModule } from './games/games.module'; 7 | import { ReadmeModule } from './readme/readme.module'; 8 | import { TriggerModule } from './trigger/trigger.module'; 9 | import { ReadmeService } from './readme/readme.service'; 10 | import { RequestModule } from './request/request.module'; 11 | import { ScheduleModule } from '@nestjs/schedule'; 12 | import { ConfigModule } from '@nestjs/config'; 13 | import { RedisModule } from './redis/redis.module'; 14 | import { AuthModule } from './auth/auth.module'; 15 | import { UsersModule } from './users/users.module'; 16 | import { ConfigService } from './config/config.service'; 17 | 18 | @Module({ 19 | imports: [ 20 | ConfigModule.forRoot(), 21 | ScheduleModule.forRoot(), 22 | GamesModule, 23 | ReadmeModule, 24 | TriggerModule, 25 | ServeStaticModule.forRoot({ 26 | rootPath: join(__dirname, '..', 'public'), 27 | }), 28 | RequestModule, 29 | RedisModule, 30 | AuthModule, 31 | UsersModule, 32 | ], 33 | controllers: [AppController], 34 | providers: [AppService, ReadmeService, ConfigService], 35 | }) 36 | export class AppModule {} 37 | -------------------------------------------------------------------------------- /src/app.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | 3 | @Injectable() 4 | export class AppService { 5 | getHello(): string { 6 | return 'Hello World!'; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/assets/emojis/boom.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/d407d5479d5a2093b1e7904cb0764a71853c604d/src/assets/emojis/boom.png -------------------------------------------------------------------------------- /src/assets/emojis/eight.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/d407d5479d5a2093b1e7904cb0764a71853c604d/src/assets/emojis/eight.png -------------------------------------------------------------------------------- /src/assets/emojis/five.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/d407d5479d5a2093b1e7904cb0764a71853c604d/src/assets/emojis/five.png -------------------------------------------------------------------------------- /src/assets/emojis/four.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/d407d5479d5a2093b1e7904cb0764a71853c604d/src/assets/emojis/four.png -------------------------------------------------------------------------------- /src/assets/emojis/one.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/d407d5479d5a2093b1e7904cb0764a71853c604d/src/assets/emojis/one.png -------------------------------------------------------------------------------- /src/assets/emojis/seven.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/d407d5479d5a2093b1e7904cb0764a71853c604d/src/assets/emojis/seven.png -------------------------------------------------------------------------------- /src/assets/emojis/six.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/d407d5479d5a2093b1e7904cb0764a71853c604d/src/assets/emojis/six.png -------------------------------------------------------------------------------- /src/assets/emojis/three.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/d407d5479d5a2093b1e7904cb0764a71853c604d/src/assets/emojis/three.png -------------------------------------------------------------------------------- /src/assets/emojis/two.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/d407d5479d5a2093b1e7904cb0764a71853c604d/src/assets/emojis/two.png -------------------------------------------------------------------------------- /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/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/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/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/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/config/config.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { ConfigService } from './config.service'; 3 | 4 | describe('ConfigService', () => { 5 | let service: ConfigService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | providers: [ConfigService], 10 | }).compile(); 11 | 12 | service = module.get(ConfigService); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(service).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/config/config.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import Config from 'src/declarations/config.interface'; 3 | import * as fs from 'fs' 4 | 5 | @Injectable() 6 | export class ConfigService { 7 | config: Config 8 | constructor() { 9 | this.config = JSON.parse(fs.readFileSync('./config.json').toString()) 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/declarations/config.interface.ts: -------------------------------------------------------------------------------- 1 | export default interface Config { 2 | [name: string]: any 3 | } -------------------------------------------------------------------------------- /src/declarations/readme-module.interface.ts: -------------------------------------------------------------------------------- 1 | export default interface IReadmeModule { 2 | toMd: (BASE_URL: string, data: any, options: any) => Promise 3 | } -------------------------------------------------------------------------------- /src/declarations/structure.interface.ts: -------------------------------------------------------------------------------- 1 | export default interface RendererStructure { 2 | [name: string]: any 3 | } -------------------------------------------------------------------------------- /src/games/chess/assets/bb.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/d407d5479d5a2093b1e7904cb0764a71853c604d/src/games/chess/assets/bb.png -------------------------------------------------------------------------------- /src/games/chess/assets/bk.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/d407d5479d5a2093b1e7904cb0764a71853c604d/src/games/chess/assets/bk.png -------------------------------------------------------------------------------- /src/games/chess/assets/bn.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/d407d5479d5a2093b1e7904cb0764a71853c604d/src/games/chess/assets/bn.png -------------------------------------------------------------------------------- /src/games/chess/assets/bp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/d407d5479d5a2093b1e7904cb0764a71853c604d/src/games/chess/assets/bp.png -------------------------------------------------------------------------------- /src/games/chess/assets/bq.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/d407d5479d5a2093b1e7904cb0764a71853c604d/src/games/chess/assets/bq.png -------------------------------------------------------------------------------- /src/games/chess/assets/br.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/d407d5479d5a2093b1e7904cb0764a71853c604d/src/games/chess/assets/br.png -------------------------------------------------------------------------------- /src/games/chess/assets/wb.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/d407d5479d5a2093b1e7904cb0764a71853c604d/src/games/chess/assets/wb.png -------------------------------------------------------------------------------- /src/games/chess/assets/wk.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/d407d5479d5a2093b1e7904cb0764a71853c604d/src/games/chess/assets/wk.png -------------------------------------------------------------------------------- /src/games/chess/assets/wn.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/d407d5479d5a2093b1e7904cb0764a71853c604d/src/games/chess/assets/wn.png -------------------------------------------------------------------------------- /src/games/chess/assets/wp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/d407d5479d5a2093b1e7904cb0764a71853c604d/src/games/chess/assets/wp.png -------------------------------------------------------------------------------- /src/games/chess/assets/wq.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/d407d5479d5a2093b1e7904cb0764a71853c604d/src/games/chess/assets/wq.png -------------------------------------------------------------------------------- /src/games/chess/assets/wr.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Charles-Chrismann/dynamic-readme/d407d5479d5a2093b1e7904cb0764a71853c604d/src/games/chess/assets/wr.png -------------------------------------------------------------------------------- /src/games/chess/chess.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get, Request, Res } from '@nestjs/common'; 2 | import { ChessService } from './chess.service'; 3 | import { Response } from 'express' 4 | import { ReadmeService } from 'src/readme/readme.service'; 5 | import { ConfigService } from 'src/config/config.service'; 6 | 7 | @Controller('chess') 8 | export class ChessController { 9 | constructor( 10 | private configService: ConfigService, 11 | private chessService: ChessService, 12 | private readmeService: ReadmeService 13 | ) {} 14 | @Get('new') 15 | async new(@Res() res: Response) { 16 | const {config} = this.configService 17 | this.chessService.new() 18 | await this.readmeService.commit(':chess_pawn: Reset chess') 19 | res.status(200) 20 | res.redirect(config.datas.repo.url + '#a-classic-chess') 21 | } 22 | 23 | @Get('move') 24 | async move(@Res() res: Response, @Request() req) { 25 | const {config} = this.configService 26 | if(this.chessService.move(req)) await this.readmeService.commit(':chess_pawn: Update chess') 27 | res.status(200) 28 | res.redirect(config.datas.repo.url + '#a-classic-chess') 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/games/chess/chess.service.ts: -------------------------------------------------------------------------------- 1 | import * as fs from 'fs'; 2 | import { Injectable, OnModuleInit } from '@nestjs/common'; 3 | import { createCanvas, loadImage } from '@napi-rs/canvas'; 4 | import { Chess } from './classes/Chess'; 5 | import { utils } from './classes/utils'; 6 | import { Piece } from './classes/Piece'; 7 | import { RedisService } from 'src/redis/redis.service'; 8 | import IReadmeModule from 'src/declarations/readme-module.interface'; 9 | 10 | @Injectable() 11 | export class ChessService implements OnModuleInit, IReadmeModule { 12 | pieces = { 13 | Pawn: { 14 | white: "♙", 15 | black: "♟", 16 | }, 17 | King: { 18 | white: "♔", 19 | black: "♚", 20 | }, 21 | Queen: { 22 | white: "♕", 23 | black: "♛", 24 | }, 25 | Rook: { 26 | white: "♖", 27 | black: "♜", 28 | }, 29 | Knight: { 30 | white: "♘", 31 | black: "♞", 32 | }, 33 | Bishop: { 34 | white: "♗", 35 | black: "♝", 36 | }, 37 | } 38 | 39 | constructor(private redisService: RedisService) {} 40 | 41 | async onModuleInit() { 42 | if(!await this.redisService.client.get('chess')) await this.new() 43 | } 44 | 45 | async new() { 46 | const chess = new Chess() 47 | await this.redisService.client.set('chess', JSON.stringify(chess)) 48 | } 49 | 50 | async move(req): Promise { 51 | const chess = new Chess(JSON.parse(await this.redisService.client.get('chess'))) 52 | const returnBool = chess.updateBoard({x: +req.query.x1, y: +req.query.y1},{x: +req.query.x2, y: +req.query.y2}) 53 | if(!returnBool) return false 54 | await this.redisService.client.set('chess', JSON.stringify(chess)) 55 | return true 56 | } 57 | 58 | async renderBoardImage() { 59 | const tileSize = 32; 60 | const canvas = createCanvas(256, 256) 61 | const ctx = canvas.getContext('2d') 62 | ctx.fillStyle = '#eeeed2' 63 | ctx.fillRect(0, 0, 256, 256) 64 | 65 | ctx.fillStyle = '#769656' 66 | 67 | let currentColor; 68 | for (let i = 0; i < 8; i++) { 69 | for (let j = 0; j < 8; j++) { 70 | if ((i + j) % 2 === 0) { 71 | ctx.fillRect(tileSize * i, tileSize * j, tileSize, tileSize) 72 | } 73 | 74 | if(j === 7) { 75 | currentColor = ctx.fillStyle 76 | ctx.fillStyle = i % 2 === 0 ? '#769656' : '#eeeed2' 77 | ctx.fillText(String.fromCharCode(97 + i), tileSize * (i + 1) - 6, 253) 78 | ctx.fillStyle = currentColor 79 | } 80 | } 81 | currentColor = ctx.fillStyle 82 | ctx.fillStyle = i % 2 !== 0 ? '#769656' : '#eeeed2' 83 | ctx.fillText(String(8 - i), 1, tileSize * (i + 1) - 24) 84 | ctx.fillStyle = currentColor 85 | } 86 | 87 | const chess = new Chess(JSON.parse(await this.redisService.client.get('chess'))) 88 | const piecesMap = new Map() 89 | for(const piece of utils.getAllPieces(chess.board)) { 90 | const pieceName = piece.getImage() 91 | let pieceImg = piecesMap.get(pieceName) 92 | if(!pieceImg) { 93 | pieceImg = await loadImage('./src/games/chess/assets/' + piece.getImage() + '.png') 94 | piecesMap.set(pieceName, pieceImg) 95 | } 96 | ctx.drawImage(pieceImg, piece.x * tileSize, piece.y * tileSize, tileSize, tileSize) 97 | } 98 | const buffer = await canvas.encode('png') 99 | fs.writeFileSync('./public/board.png', buffer) 100 | } 101 | 102 | private computeMoveString(piece: Piece, BASE_URL: string) { 103 | const sqrt = Math.ceil(Math.sqrt(piece.legalMoves.length)) 104 | return piece.legalMoves.map((move, index: number) => { 105 | return `${(index % sqrt === 0 && index !== 0) ? "
" : ''}${utils.coordsToBoardCoards({x: move.x, y: move.y})}` 106 | }).join('\n ') 107 | } 108 | 109 | async toMd(BASE_URL: string, data: any, options: any) { 110 | const chess = new Chess(JSON.parse(await this.redisService.client.get('chess'))) 111 | utils.defineAllLegalMoves(chess, chess.board); 112 | 113 | let str = `

A classic Chess

\n` 114 | this.renderBoardImage() 115 | str += `

\n \n

\n` 116 | 117 | if( chess.status === "black" || 118 | chess.status === "white" 119 | ) str += `

${chess.status.charAt(0).toUpperCase() + chess.status.slice(1)} wins !

\n` 120 | else if(chess.status === "tie") str += `

Stalemate !

\n` 121 | else str += `

It's ${chess.playerTurn.charAt(0).toUpperCase() + chess.playerTurn.slice(1)}'s turn

\n` 122 | 123 | if(!chess.status) { 124 | str += `\n \n` 125 | chess.board.forEach((row, y) => { 126 | str += ` \n \n` 127 | row.forEach((piece) => { 128 | str += ` \n` 130 | }) 131 | str += ` \n` 132 | }) 133 | 134 | str += ` \n \n \n \n \n \n \n \n \n \n \n \n
${utils.getletterFromNumber(y)}${piece ? (piece.legalMoves.length && piece.color === chess.playerTurn ? `\n
\n ${this.pieces[piece.type][piece.color]}\n ${this.computeMoveString(piece, BASE_URL)}\n
\n` : this.pieces[piece.type][piece.color] 129 | ): "‎ "}
🇦🇧🇨🇩🇪🇫🇬🇭
` 135 | } 136 | 137 | str += `

\nReset Game\n

\n\n
\n\n` 138 | return str 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /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/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 | } -------------------------------------------------------------------------------- /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/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 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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/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/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/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 | -------------------------------------------------------------------------------- /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 'src/config/config.service'; 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 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/gameboy/gameboy.gateway.ts: -------------------------------------------------------------------------------- 1 | import { SubscribeMessage, WebSocketGateway, OnGatewayConnection, WebSocketServer, OnGatewayDisconnect, OnGatewayInit } from '@nestjs/websockets'; 2 | import { Socket, Server } from 'socket.io'; 3 | import { GameboyService } from './gameboy.service'; 4 | import { AuthService } from 'src/auth/auth.service'; 5 | import { CronJob } from 'cron' 6 | import { RedisService } from 'src/redis/redis.service'; 7 | import { ReadmeService } from 'src/readme/readme.service'; 8 | 9 | @WebSocketGateway({ 10 | namespace: 'gameboy' 11 | }) 12 | export class GameboyGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect { 13 | renderInterval: NodeJS.Timer | null 14 | sessionFrames = 0 15 | connected = 0 16 | clients = new Map() 17 | users = new Map() 18 | saveJob = new CronJob('0 * * * * *', async () => { await this.saveUsers(this); if (this.needCommit) this.reamdeService.commit(":joystick: Update Gameboy Contributions"); this.needCommit = false}) 19 | needCommit = false 20 | lastSendedFrame!: number[] 21 | constructor(private gameboyService: GameboyService, private authService: AuthService, private redis: RedisService, private reamdeService: ReadmeService){ 22 | this.saveJob.start() 23 | } 24 | 25 | @WebSocketServer() 26 | server: Server; 27 | 28 | async afterInit(io: Server) { 29 | 30 | io.use(async (socket, next) => { 31 | try { 32 | const payload = await this.authService.verify(socket.handshake.headers.authorization.split(' ')[1]) 33 | if(payload) { 34 | this.clients.set(socket.id, payload.id) 35 | this.users.set(String(payload.id), { id: payload.id, inputCount: 0, pressed: [], connectetd: true }) 36 | next() 37 | } else next(new Error('authentication error')) 38 | } catch (e) { 39 | console.log(e) 40 | next(new Error('authentication error')) 41 | } 42 | }) 43 | } 44 | 45 | computeFrameDiff(newFrame: number[]) { 46 | const startArray: number[][] = Array.from({ length: 256 }, e => Array() ) 47 | for(let i = 0; i < newFrame.length; i++) { 48 | if(newFrame[i] !== this.lastSendedFrame[i]) { 49 | startArray[newFrame[i]].push(i) 50 | } 51 | } 52 | 53 | const returnArray = [] as (number | number[])[] 54 | for(let i = 0; i < startArray.length; i+= 1) { 55 | if(startArray[i].length) { 56 | returnArray.push(i) 57 | returnArray.push(startArray[i]) 58 | } 59 | } 60 | return returnArray 61 | } 62 | 63 | handleConnection(socket: Socket): void { 64 | this.lastSendedFrame = this.gameboyService.gameboy_instance.doFrame() 65 | this.server.emit('frame', this.lastSendedFrame) 66 | if(++this.connected > 1) return 67 | this.saveJob.start() 68 | 69 | this.gameboyService.stopRenderSession() 70 | this.renderInterval = setInterval(() => { 71 | if(++this.sessionFrames % 10 === 0) { 72 | const newFrame = this.gameboyService.gameboy_instance.doFrame() 73 | const diff = this.computeFrameDiff(newFrame) 74 | if(diff.length) this.server.emit('diff', diff) 75 | this.lastSendedFrame = newFrame 76 | } else { 77 | if(this.gameboyService.lastInputFrames.length >= 80) { 78 | this.gameboyService.lastInputFrames.splice(0, this.gameboyService.lastInputFrames.length - 80 + 1) 79 | } 80 | if(this.sessionFrames % 4 === 0) this.gameboyService.lastInputFrames.push(this.gameboyService.gameboy_instance.doFrame()) 81 | else this.gameboyService.gameboy_instance.doFrame() 82 | } 83 | }, 5) 84 | } 85 | 86 | handleDisconnect(socket: Socket) { 87 | const user = this.users.get(String(this.clients.get(socket.id))) 88 | if(user) user.connectetd = false 89 | this.clients.delete(socket.id) 90 | if(--this.connected === 0) { 91 | this.saveUsers(this) 92 | this.saveJob.stop() 93 | this.sessionFrames = 0 94 | clearInterval(this.renderInterval as NodeJS.Timeout) 95 | this.renderInterval = null 96 | this.gameboyService.setRenderSession() 97 | } 98 | } 99 | 100 | @SubscribeMessage('input') 101 | async handleMessage(client: any, payload: string[]) { 102 | this.needCommit = true 103 | let userId = this.clients.get(client.id) 104 | if(!userId) return 105 | let userAction = this.users.get(String(userId)) ?? { id: userId, inputCount: 0, pressed: [] as string[], connectetd: true } 106 | const validatedInputs = userAction.pressed.filter(input => !payload.find(v => input === v)) 107 | userAction.inputCount += validatedInputs.length 108 | userAction.pressed = payload 109 | this.users.set(String(userId), userAction) 110 | for(let i = 0; i < 2; i++) { 111 | this.gameboyService.gameboy_instance.pressKeys(payload) 112 | this.gameboyService.gameboy_instance.doFrame() 113 | } 114 | } 115 | 116 | async saveUsers(that) { 117 | for(const [key, user] of that.users) { 118 | const isSaved = await that.redis.client.hGet(`gameboy:players:${user.id}`, 'id') 119 | if(!isSaved) await that.redis.client.hSet(`gameboy:players:${user.id}`, {id: user.id, inputCount: user.inputCount}) 120 | else { 121 | const userInputCount = await that.redis.client.hGet(`gameboy:players:${user.id}`, 'inputCount') 122 | that.redis.client.hSet(`gameboy:players:${user.id}`, 'inputCount', +userInputCount + user.inputCount) 123 | } 124 | user.inputCount = 0 125 | if(!user.connected) that.users.delete(user.id) 126 | } 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /src/games/games.module.ts: -------------------------------------------------------------------------------- 1 | import { Module, forwardRef } 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 { ReadmeModule } from 'src/readme/readme.module'; 7 | import { WordleService } from './wordle/wordle.service'; 8 | import { WordleController } from './wordle/wordle.controller'; 9 | import { RedisModule } from 'src/redis/redis.module'; 10 | import { GameboyController } from './gameboy/gameboy.controller'; 11 | import { GameboyService } from './gameboy/gameboy.service'; 12 | import { GameboyGateway } from './gameboy/gameboy.gateway'; 13 | import { AuthModule } from 'src/auth/auth.module'; 14 | import { ConfigService } from 'src/config/config.service'; 15 | 16 | import { GbaService } from './gba/gba.service'; 17 | import { GbaController } from './gba/gba.controller'; 18 | 19 | @Module({ 20 | imports: [forwardRef(() => ReadmeModule), RedisModule, AuthModule], 21 | controllers: [MinesweeperController, ChessController, WordleController, GameboyController, GbaController], 22 | providers: [MinesweeperService, ChessService, WordleService, GameboyService, GameboyGateway, GbaService, ConfigService], 23 | exports: [MinesweeperService, ChessService, WordleService, GameboyService, GbaService] 24 | }) 25 | export class GamesModule {} 26 | -------------------------------------------------------------------------------- /src/games/gba/gba.controller.ts: -------------------------------------------------------------------------------- 1 | import { Body, Controller, Get, Param, Post, Query, RawBodyRequest, Req, Res } from '@nestjs/common'; 2 | import { Request, Response } from 'express'; 3 | import { GbaService } from './gba.service'; 4 | import * as rawbody from 'raw-body'; 5 | import { ConfigService } from 'src/config/config.service'; 6 | 7 | @Controller('gba') 8 | export class GbaController { 9 | 10 | constructor( 11 | private configService: ConfigService, 12 | private gbaService: GbaService 13 | ){} 14 | 15 | @Get('/input') 16 | input(@Query('input') input: string, @Res() res: Response) { 17 | const {config} = this.configService 18 | res.status(200) 19 | res.redirect(config.datas.perso.homepage) 20 | if(input) this.gbaService.input(+input) 21 | } 22 | 23 | @Get('/save') 24 | async save(@Res() res: Response) { 25 | return await this.gbaService.save(res) 26 | } 27 | 28 | @Post('/load') 29 | async load(@Req() req: Request) { 30 | const save = (await rawbody(req)).toString().trim() 31 | this.gbaService.load(save) 32 | } 33 | 34 | @Get('/doframe') 35 | frame(@Res() res: Response) { 36 | return this.gbaService.frame(res) 37 | } 38 | 39 | @Get('/dogif') 40 | gif(@Res() res: Response) { 41 | if(!this.gbaService.lastInputFrames.length) return this.gbaService.frame(res) 42 | return this.gbaService.gif(res) 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /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 | import { ReadmeModule } from 'src/readme/readme.module'; 6 | 7 | @Module({ 8 | imports: [AuthModule], 9 | providers: [GbaService], 10 | controllers: [GbaController] 11 | }) 12 | export class GbaModule {} 13 | -------------------------------------------------------------------------------- /src/games/gba/gba.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 { Response } from 'express'; 7 | import { Cron } from '@nestjs/schedule'; 8 | import { RedisService } from 'src/redis/redis.service'; 9 | import { GifEncoder } from '@skyra/gifenc'; 10 | import { Wrapper } from 'gbats'; 11 | import IReadmeModule from 'src/declarations/readme-module.interface'; 12 | 13 | const rom = fs.readFileSync(path.join(process.env.PWD, 'roms', process.env.ROM_GBA_NAME)) 14 | 15 | @Injectable() 16 | export class GbaService implements OnModuleInit, IReadmeModule { 17 | private readonly logger = new Logger(GbaService.name) 18 | 19 | gba_wrapper: Wrapper 20 | canvas = createCanvas(240, 160) 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 | 29 | this.gba_wrapper = new Wrapper({ 30 | rom, 31 | canvas: this.canvas, 32 | updateMethod: 'manual' 33 | }) 34 | const gi = await this.redis.client.get('gba:save_state') 35 | if(gi) { 36 | // console.log(globalThis) 37 | this.gba_wrapper.loadSaveState(gi) 38 | } 39 | this.setRenderSession() 40 | } 41 | 42 | @Cron(process.env.EMU_BACKUP_CRON) 43 | async backup() { 44 | this.logger.log('[SHEDULED] Saving gameboy') 45 | const save = await this.gba_wrapper.createSaveState() 46 | this.redis.client.set('gba:save_state', save) 47 | } 48 | 49 | setRenderInterval(frameInterval = 5) { 50 | this.renderInterval = setInterval(() => { 51 | this.gba_wrapper.frame() 52 | }, frameInterval) 53 | } 54 | 55 | stopRenderInterval(intervalId) { 56 | clearInterval(intervalId) 57 | } 58 | 59 | setRenderTimeout(intervalId, timeout = 60000) { 60 | this.renderTimeout = setTimeout(() => this.stopRenderInterval(intervalId), timeout) 61 | } 62 | 63 | stopRenderTimeout() { 64 | clearTimeout(this.renderTimeout) 65 | } 66 | 67 | setRenderSession() { 68 | this.setRenderInterval() 69 | this.setRenderTimeout(this.renderInterval) 70 | } 71 | 72 | stopRenderSession() { 73 | this.stopRenderInterval(this.renderInterval) 74 | this.stopRenderTimeout() 75 | } 76 | 77 | skipFrames(n) { 78 | const frames = [] 79 | for(let i = 0; i < n; i++) { 80 | if(i % 4 === 0) { 81 | this.gba_wrapper.setScreen() 82 | this.gba_wrapper.frame() 83 | frames.push(this.gba_wrapper.getPixels()) 84 | this.gba_wrapper.removeScreen() 85 | } 86 | else this.gba_wrapper.frame() 87 | } 88 | this.gba_wrapper.setScreen() 89 | return frames 90 | } 91 | 92 | async frame(res: Response) { 93 | const canvas = createCanvas(240, 160) 94 | const ctx = canvas.getContext('2d') 95 | let ctx_data = ctx.createImageData(240, 160); 96 | 97 | const screen = this.gba_wrapper.getPixels() 98 | 99 | for (let i=0; i < screen.length; i++){ 100 | ctx_data.data[i] = screen[i]; 101 | } 102 | 103 | ctx.putImageData(ctx_data, 0, 0); 104 | 105 | const stream = Readable.from(await canvas.encode('png')) 106 | res.setHeader('Content-Type', 'image/png') 107 | res.setHeader('Cache-Control', 'public, max-age=0') 108 | stream.pipe(res) 109 | } 110 | 111 | gif(res: Response) { 112 | res.setHeader('Content-Type', 'image/gif') 113 | res.setHeader('Cache-Control', 'public, max-age=0') 114 | 115 | const gifEncoder = new GifEncoder(240, 160) 116 | .setRepeat(-1) 117 | .setDelay(64) 118 | .setQuality(10); 119 | gifEncoder.createWriteStream().pipe(res) 120 | gifEncoder.start() 121 | const canvas = createCanvas(240, 160) 122 | const ctx = canvas.getContext('2d') 123 | let ctx_data = ctx.createImageData(240, 160); 124 | for(let i = 0; i < this.lastInputFrames.length; i++) { 125 | for (let j=0; j < this.lastInputFrames[i].length; j++){ 126 | ctx_data.data[j] = this.lastInputFrames[i][j]; 127 | } 128 | ctx.putImageData(ctx_data, 0, 0); 129 | gifEncoder.addFrame(ctx.getImageData(0, 0, 240, 160).data) 130 | } 131 | gifEncoder.finish(); 132 | } 133 | 134 | input(input: number) { 135 | 136 | const tick = performance.now() 137 | if(input < 0 || input > 9) return 138 | this.stopRenderSession() 139 | this.lastInputFrames = [] 140 | 141 | for(let i = 0; i < 5; i++) { 142 | this.gba_wrapper.press(input, 1) 143 | this.gba_wrapper.frame() 144 | this.lastInputFrames.push(this.gba_wrapper.getPixels()) 145 | } 146 | this.lastInputFrames = this.lastInputFrames.concat(this.skipFrames(300)) 147 | 148 | this.setRenderSession() 149 | } 150 | 151 | async save(res) { 152 | this.stopRenderSession() 153 | const save = await this.gba_wrapper.createSaveState() 154 | 155 | const stream = Readable.from(save); 156 | 157 | res.attachment('save.txt') 158 | stream.pipe(res) 159 | this.setRenderSession() 160 | } 161 | 162 | async load(loadObj: string) { 163 | this.stopRenderSession() 164 | 165 | await this.gba_wrapper.loadSaveState(loadObj) 166 | 167 | this.setRenderSession() 168 | } 169 | 170 | async renderInputBoard() { 171 | let str = `\n \n` 172 | str += ' \n \n \n' 173 | str += ` \n \n \n \n \n \n \n` 174 | const playersIds = await this.redis.client.keys("gameboy:players:*") 175 | const players = await Promise.all(playersIds.map(player => this.redis.client.hGetAll(player))) 176 | const users = await Promise.all(players.map(player => this.redis.client.hGetAll(`user:${player.id}`))) 177 | const rowsDatas = players.map((player, index) => ({...player, ...users[index]})).sort((a, b) => +b.inputCount - +a.inputCount) 178 | str += rowsDatas.map((row, i) => ` \n \n \n \n \n \n`).join('') 179 | str += ` \n \n \n` 180 | str += ` \n
Game Contributions
RankPlayerInputs
${i + 1}profil picture@${row.login}${row.inputCount}
Play with your Github account here !
\n\n` 181 | 182 | return str 183 | } 184 | 185 | async toMd(BASE_URL: string) { 186 | const BASE_URL_GBA = `${BASE_URL}/gba` 187 | let str = `

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

\n` 188 | str += `

\n` 189 | 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` 196 | str += ` \n \n \n` 197 | str += `
\n` 198 | str += ` \n \n \n` 199 | str += ` \n \n \n` 200 | str += `
\n` 201 | str += ` \n \n \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` 208 | str += ` \n \n \n` 209 | str += `
\n` 210 | str += ` \n \n \n` 211 | str += ` \n \n \n` 212 | 213 | str += `

\n\n
\n\n` 214 | 215 | return str 216 | } 217 | } 218 | -------------------------------------------------------------------------------- /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/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 | } -------------------------------------------------------------------------------- /src/games/minesweeper/minesweeper.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get, Query, Res } from '@nestjs/common'; 2 | import { Response } from 'express'; 3 | import { MinesweeperService } from './minesweeper.service'; 4 | import { ReadmeService } from 'src/readme/readme.service'; 5 | import { ConfigService } from 'src/config/config.service'; 6 | 7 | @Controller('minesweeper') 8 | export class MinesweeperController { 9 | constructor( 10 | private configService: ConfigService, 11 | private minesweeperService: MinesweeperService, 12 | private readmeService: ReadmeService 13 | ) {} 14 | @Get('new') 15 | async new(@Res() res: Response) { 16 | const {config} = this.configService 17 | await this.minesweeperService.new() 18 | await this.readmeService.commit(':boom: Reset minesweeper') 19 | res.status(200) 20 | res.redirect(config.datas.repo.url + '#a-classic-minesweeper') 21 | } 22 | 23 | @Get('click') 24 | async click(@Query('x') x: string, @Query('y') y: string, @Res() res: Response){ 25 | const {config} = this.configService 26 | if(await this.minesweeperService.click(+x, +y)) await this.readmeService.commit(':boom: Update minesweeper') 27 | res.status(200) 28 | res.redirect(config.datas.repo.url + '#a-classic-minesweeper') 29 | } 30 | } -------------------------------------------------------------------------------- /src/games/minesweeper/minesweeper.service.ts: -------------------------------------------------------------------------------- 1 | import * as fs from 'fs'; 2 | import { createCanvas, loadImage } from '@napi-rs/canvas'; 3 | import { Injectable, OnModuleInit } from '@nestjs/common'; 4 | import { Minesweeper } from './classes/Minesweeper'; 5 | import { RedisService } from 'src/redis/redis.service'; 6 | import { commandOptions } from 'redis'; 7 | import { GifEncoder } from '@skyra/gifenc'; 8 | import IReadmeModule from 'src/declarations/readme-module.interface'; 9 | 10 | @Injectable() 11 | export class MinesweeperService implements OnModuleInit, IReadmeModule { 12 | constructor(private redisService: RedisService) {} 13 | 14 | async onModuleInit() { 15 | if(!await this.redisService.client.get('minesweeper')) await this.new() 16 | } 17 | 18 | async new() { 19 | const minesweeper = new Minesweeper(18, 14, 24) 20 | await Promise.all([ 21 | this.redisService.client.set('minesweeper', JSON.stringify(minesweeper)), 22 | this.redisService.client.unlink('minesweeperImages') 23 | ]) 24 | await this.renderGameImageCtx(true, minesweeper) 25 | return minesweeper 26 | } 27 | 28 | /** 29 | * @param x 30 | * @param y 31 | * @returns true if the map has been updated false otherwise 32 | */ 33 | async click(x: number, y: number): Promise { 34 | const minesweeperData: Record = JSON.parse(await this.redisService.client.get('minesweeper')) 35 | const minesweeper = minesweeperData ? new Minesweeper(minesweeperData) : await this.new() 36 | if(minesweeper.gameStatus === "Ended") return false 37 | if(!minesweeper.HandleClick({x: x, y: y})) return false 38 | if(minesweeper.map.flat().filter(cell => cell.hidden).length === minesweeper.bombsCount) minesweeper.gameStatus = "Endend" 39 | await this.renderGameImageCtx(false, minesweeper) 40 | await this.redisService.client.set('minesweeper', JSON.stringify(minesweeper)) 41 | return true 42 | } 43 | 44 | async renderGameImageCtx(isFirst: boolean = false, minesweeperData: Record) { 45 | const tileSize = 16; 46 | const canvas = createCanvas(tileSize * minesweeperData.width, tileSize * minesweeperData.height) 47 | const ctx = canvas.getContext('2d') 48 | ctx.fillStyle = "#000000" 49 | ctx.fillRect(0, 0, tileSize * minesweeperData.width, tileSize * minesweeperData.height) 50 | 51 | if(isFirst) { 52 | this.redisService.client.hSet('minesweeperImages', 0, ctx.canvas.toBuffer('image/png')) 53 | return 54 | } 55 | 56 | const emojis = {} 57 | const emojiList = ["one", "two", "three", "four", "five", "six", "seven", "eight", "boom"] 58 | for(let i = 0; i < minesweeperData.width; i++) { 59 | for(let j = 0; j < minesweeperData.height; j++) { 60 | const cell = minesweeperData.map[j][i] 61 | if(cell.hidden) continue 62 | if(!cell.value) { 63 | ctx.fillStyle = "#ffffff" 64 | ctx.fillRect(i * tileSize, j * tileSize, tileSize, tileSize) 65 | continue 66 | } 67 | const emojiImage = await (emojis[emojiList[cell.value - 1]] ?? (async () => { 68 | const emoji = emojiList[cell.value - 1] 69 | emojis[emoji] = await loadImage(`./src/assets/emojis/${emoji}.png`) 70 | return emojis[emoji] 71 | })()) 72 | ctx.drawImage(emojiImage, cell.x * tileSize, cell.y * tileSize, tileSize, tileSize) 73 | } 74 | } 75 | const savedImages = await this.redisService.client.hGetAll('minesweeperImages') 76 | this.redisService.client.hSet('minesweeperImages', Object.keys(savedImages).length, ctx.canvas.toBuffer('image/png')) 77 | } 78 | 79 | async generatehistoryGif() { 80 | const minesweeperData: Record = JSON.parse(await this.redisService.client.get('minesweeper')) 81 | const imagesPromises = Object.values(await this.redisService.client.hGetAll(commandOptions({ returnBuffers: true }),'minesweeperImages')).map(async buffer => await loadImage(buffer)) 82 | const images = await Promise.all(imagesPromises) 83 | 84 | const tileSize = 16; 85 | const canvasWidth = minesweeperData.width * tileSize 86 | const canvasHeight = minesweeperData.height * tileSize 87 | const gifEncoder = new GifEncoder(canvasWidth, canvasHeight) 88 | .setRepeat(0) 89 | .setDelay(Math.floor(5000 / images.length || 1)) 90 | .setQuality(10) 91 | gifEncoder.createWriteStream().pipe(fs.createWriteStream('./public/minesweeper.gif')) 92 | gifEncoder.start() 93 | 94 | for(let i = 0; i < images.length; i++) { 95 | const image = images[i] 96 | const canvas = createCanvas(canvasWidth, canvasHeight) 97 | const ctx = canvas.getContext('2d') 98 | ctx.drawImage(image, 0, 0) 99 | gifEncoder.addFrame(ctx.getImageData(0, 0, canvasWidth, canvasHeight).data) 100 | } 101 | gifEncoder.finish() 102 | } 103 | 104 | async toMd(BASE_URL: string) { 105 | this.generatehistoryGif() // asyncrone mais peux poser un probleme de timing 106 | 107 | const minesweeper: Minesweeper = new Minesweeper(JSON.parse(await this.redisService.client.get('minesweeper'))) 108 | let str = `

A classic Minesweeper

\n` 109 | str += `

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

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

Come on, try it

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

Keep clearing, there are still many mines left.

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

You lost don't hesitate to try again

\n` : `

Congrats you won !

\n` 115 | 116 | const historyLength = Object.values(await this.redisService.client.hGetAll(commandOptions({ returnBuffers: true }),'minesweeperImages')).length 117 | if(historyLength) str += `

\n \n

\n` 118 | 119 | str += `

\n Reset Game\n

\n\n
\n\n` 120 | 121 | return str 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /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 'src/config/config.service'; 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 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 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/sudoku/sudoku.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { SudokuService } from './sudoku.service'; 3 | import { SudokuController } from './sudoku.controller'; 4 | import { ReadmeModule } from 'src/readme/readme.module'; 5 | 6 | @Module({ 7 | providers: [SudokuService], 8 | controllers: [SudokuController], 9 | imports: [ReadmeModule] 10 | }) 11 | export class SudokuModule {} 12 | -------------------------------------------------------------------------------- /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/games/wordle/wordle.controller.ts: -------------------------------------------------------------------------------- 1 | import { Body, Controller, Get, HttpException, HttpStatus, Post, Req, Res } from '@nestjs/common'; 2 | import { WordleService } from './wordle.service'; 3 | import { Request, Response } from 'express'; 4 | import { ReadmeService } from 'src/readme/readme.service'; 5 | import { Cron } from '@nestjs/schedule'; 6 | import { ConfigService } from 'src/config/config.service'; 7 | 8 | @Controller('wordle') 9 | export class WordleController { 10 | constructor( 11 | private configService: ConfigService, 12 | private readonly wordleService: WordleService, 13 | private readonly readmeService: ReadmeService 14 | ) {} 15 | 16 | @Get('wordle') 17 | async wordle() { 18 | await this.wordleService.wordle(); 19 | await this.readmeService.commit(':book: set today\'s wordle') 20 | return 'wordle'; 21 | } 22 | 23 | @Cron('0 0 22 * * *') 24 | async wordleAndCommit() { 25 | await this.wordle(); 26 | } 27 | 28 | @Post('guess') 29 | async guess( 30 | @Res() res: Response, 31 | @Body('guess') guess: string, 32 | @Body('GH_ACTION_TRUST') GH_ACTION_TRUST: string, 33 | @Body('issuer') issuer: string, 34 | @Body('issuerId') issuerId: number, 35 | @Req() req: Request 36 | ) { 37 | if(GH_ACTION_TRUST !== process.env.GH_ACTION_TRUST) throw new HttpException('Bad Request', HttpStatus.BAD_REQUEST); 38 | if(!guess || guess.length !== 5) throw new HttpException('Bad Request', HttpStatus.BAD_REQUEST); 39 | if(!issuer) throw new HttpException('Bad Request', HttpStatus.BAD_REQUEST); 40 | if(!issuerId) throw new HttpException('Bad Request', HttpStatus.BAD_REQUEST); 41 | console.log('passed') 42 | 43 | await this.wordleService.guess(guess, issuer, issuerId); 44 | await this.readmeService.commit(':book: Update wordle') 45 | const {config} = this.configService 46 | res.redirect(200, config.datas.repo.url + "#a-classic-wordle"); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /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 | import { ReadmeModule } from 'src/readme/readme.module'; 5 | 6 | @Module({ 7 | imports: [ReadmeModule], 8 | providers: [WordleService], 9 | controllers: [WordleController] 10 | }) 11 | export class WordleModule {} 12 | -------------------------------------------------------------------------------- /src/games/wordle/wordle.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { five_char_words } from './word_list'; 3 | import { RedisService } from 'src/redis/redis.service'; 4 | import IReadmeModule from 'src/declarations/readme-module.interface'; 5 | import { ConfigService } from 'src/config/config.service'; 6 | 7 | @Injectable() 8 | export class WordleService implements IReadmeModule { 9 | todayWordle: { 10 | word: string, 11 | guessed: boolean, 12 | guesses: { 13 | username: string, 14 | userId: number, 15 | guess: { 16 | valid: boolean, 17 | letters: { value: string, status: "correct" | "present" | "absent" }[] 18 | } 19 | }[] 20 | }; 21 | scoreBoard: { 22 | users: { 23 | username: string, 24 | userId: number, 25 | guesses: number 26 | }[] 27 | } 28 | constructor( 29 | private configService: ConfigService, 30 | private redisService: RedisService 31 | ) {} 32 | 33 | async onModuleInit() { 34 | if(!await this.redisService.client.get('wordle')) await this.wordle() 35 | if(!await this.redisService.client.get('wordle-scoreBoard')) { 36 | await this.redisService.client.set( 37 | 'wordle-scoreBoard', 38 | JSON.stringify({ 39 | users: [] as { 40 | username: string, 41 | userId: number, 42 | guesses: number 43 | }[] 44 | } 45 | ) 46 | ) 47 | } 48 | } 49 | 50 | async wordle() { 51 | const word = five_char_words[Math.floor(Math.random() * five_char_words.length)] 52 | const wordle = { 53 | word, 54 | guessed: false, 55 | guesses: [] 56 | } 57 | await this.redisService.client.set('wordle', JSON.stringify(wordle)) 58 | 59 | return 'wordle'; 60 | } 61 | 62 | async guess(guess: string, issuer: string, issuerId: number) { 63 | guess = guess.toUpperCase(); 64 | if(!guess.length || guess.length > 5) return 65 | const guessContainsOnlyLetters = /^[A-Z]+$/.test(guess); 66 | if(!guessContainsOnlyLetters) return 67 | const wordle = JSON.parse(await this.redisService.client.get('wordle')); 68 | if(!wordle || wordle.guessed) return 69 | const guessObj = { 70 | username: issuer, 71 | userId: issuerId, 72 | guess: { 73 | valid: five_char_words.includes(guess), 74 | letters: [] as { value: string, status: "correct" | "present" | "absent" }[] 75 | } 76 | } 77 | for(let i = 0; i < 5; i++) { 78 | const value = guess[i]; 79 | if(value === wordle.word[i]) { 80 | guessObj.guess.letters.push({ value, status: "correct" }) 81 | } else if(wordle.word.includes(value)) { 82 | guessObj.guess.letters.push({ value, status: "present" }) 83 | } else { 84 | guessObj.guess.letters.push({ value, status: "absent" }) 85 | } 86 | } 87 | 88 | wordle.guessed = guess === wordle.word; 89 | wordle.guesses.push(guessObj); 90 | await this.redisService.client.set('wordle', JSON.stringify(wordle)) 91 | this.todayWordle = wordle; 92 | 93 | let scoreBoard = JSON.parse(await this.redisService.client.get('wordle-scoreBoard')) 94 | if(wordle.guessed) { 95 | if(!scoreBoard) scoreBoard = { users: [] }; 96 | const userIndex = scoreBoard.users.findIndex(user => user.username === issuer); 97 | if(userIndex === -1) { 98 | scoreBoard.users.push({ username: issuer, userId: issuerId, guesses: 1}); 99 | } else { 100 | scoreBoard.users[userIndex].guesses += 1; 101 | } 102 | scoreBoard.users.sort((a, b) => b.guesses - a.guesses); 103 | await this.redisService.client.set('wordle-scoreBoard', JSON.stringify(scoreBoard)) 104 | } 105 | } 106 | 107 | 108 | async toMd(BASE_URL: string): Promise { 109 | const {config} = this.configService 110 | const todayWordle = JSON.parse(await this.redisService.client.get('wordle')) 111 | const scoreBoard = JSON.parse(await this.redisService.client.get('wordle-scoreBoard')) 112 | let str = `

A classic Wordle

\n` 113 | str += `\n \n \n \n \n \n \n` 114 | str += todayWordle.guesses.map(guess => { 115 | let letterTds 116 | if(!guess.guess.valid) letterTds = guess.guess.letters.map(letter => ` \n`).join('') 117 | else letterTds = guess.guess.letters.map(letter => ` \n`).join('') 118 | return ` \n${letterTds} \n \n` 119 | }).join('') 120 | 121 | str += ` \n \n \n \n \n \n \n \n` 122 | str += ` \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` 123 | 124 | str += `\n \n \n \n \n \n \n \n \n \n \n \n` 125 | str += scoreBoard.users.map((user, index) => ` \n \n \n \n \n \n`).join('') 126 | str += ` \n
Scoreboard
RankPlayerWins
${index + 1}\n \n \n \n \n @${user.username}\n ${user.guesses}
\n\n` 127 | 128 | str += `
\n\n` 129 | return str 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /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 | app.useBodyParser('json', { limit: '100mb' }); 8 | app.enableCors() 9 | await app.listen(process.env.APP_PORT); 10 | console.log(`Application is running on: ${await app.getUrl()}`) 11 | } 12 | bootstrap(); 13 | -------------------------------------------------------------------------------- /src/readme/Renderer.ts: -------------------------------------------------------------------------------- 1 | import { RequestService } from "src/request/request.service" 2 | import { ChessService } from "src/games/chess/chess.service" 3 | import { GameboyService } from "src/games/gameboy/gameboy.service" 4 | import { GbaService } from "src/games/gba/gba.service" 5 | import { MinesweeperService } from "src/games/minesweeper/minesweeper.service" 6 | import { WordleService } from "src/games/wordle/wordle.service" 7 | import * as fs from 'fs' 8 | import Config from "src/declarations/config.interface" 9 | 10 | class Module { 11 | value: string 12 | 13 | constructor( 14 | private parent: Renderer, 15 | public flat: any 16 | ) {} 17 | 18 | render() { 19 | const {config} = this.parent 20 | if(this.value) return this.value 21 | 22 | const {id, data, options} = this.flat 23 | console.log(id) 24 | if(id === "static/element") this.value = `<${data.element}${options?.align ? ` align="${options?.align}"` : `` }>${data.content}\n` 25 | else if(id === "static/raw") this.value = data.content + ((data.content as string).endsWith('\n') ? "" : "\n") 26 | else if(id === "static/greeting") this.value = `

I'm ${config.datas.perso.firstname} ${config.datas.perso.lastname} !

\n` 27 | else if(id === "3rdParty/profileViews") this.value = `

\n \n

\n` 28 | else if(id === "static/lines") { 29 | const path = data.field.split('.') 30 | let lines: any = config.datas; 31 | 32 | for (let i = 0; i < path.length; i++) { 33 | lines = lines[path[i]]; 34 | } 35 | 36 | if(!data.range.includes('-')) lines = [lines[+data.range - 1]] 37 | else { 38 | const [start, end] = data.range.split('-').map((r: string) => +r) 39 | lines = lines.slice(start - 1, end) 40 | } 41 | 42 | this.value = lines.map(l => `

${l}

\n`).join('') 43 | } 44 | else if(id === "static/list") { 45 | const path = data.field.split('.') 46 | let list: any = config.datas; 47 | 48 | for (let i = 0; i < path.length; i++) { 49 | list = list[path[i]]; 50 | } 51 | 52 | const {title, content} = list 53 | 54 | this.value = `${title ? `

${title}

\n` : ''}
    \n${content.map(l => `
  • ${l}
  • \n`).join('')}
\n` 55 | } 56 | else if(id === "static/socials") { 57 | let readMeString = '' 58 | readMeString += `

Reach Me

\n`; 59 | readMeString += `

\n`; 60 | readMeString += config.datas.perso.socials.map((social) => { 61 | return ` \n ${social.name}\n \n`; 62 | }).join(''); 63 | readMeString += `

\n`; 64 | 65 | this.value = readMeString 66 | } 67 | else if(id === "static/skills") { 68 | let skills = config.skills; 69 | let readMeString = '' 70 | 71 | readMeString += `

Technical skills

\n`; 72 | 73 | if(config.skills.learning) { 74 | readMeString += `

Currently learning:\n`; 75 | readMeString += skills.learning.map((skill) => { 76 | return ` \n ${skill.alt}\n \n`; 77 | }).join(''); 78 | readMeString += `

\n`; 79 | } 80 | 81 | // Front 82 | readMeString += `

Front-end technologies

\n

\n`; 83 | readMeString += skills.front.map((skill) => { 84 | return ` \n ${skill.alt}\n \n`; 85 | }).join(''); 86 | readMeString += `

\n`; 87 | 88 | // Back 89 | readMeString += `

Back-end technologies

\n

\n`; 90 | readMeString += skills.back.map((skill) => { 91 | return ` \n ${skill.alt}\n \n`; 92 | }).join(''); 93 | readMeString += `

\n`; 94 | 95 | // Notions 96 | readMeString += `

Other technologies where I have notions

\n

\n`; 97 | readMeString += skills.notions.map((skill) => { 98 | return ` \n ${skill.alt}\n \n`; 99 | }).join(''); 100 | readMeString += `

\n`; 101 | 102 | // Tools 103 | readMeString += `

Tools

\n

\n`; 104 | readMeString += skills.tools.map((skill) => { 105 | return ` \n ${skill.alt}\n \n`; 106 | }).join(''); 107 | readMeString += `

\n`; 108 | 109 | this.value = readMeString 110 | } 111 | else if(id === "static/trigger") { 112 | let readMeString = '' 113 | readMeString += `

Work in progress

\n`; 114 | readMeString += `

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

\n`; 115 | readMeString += `

To understand how it works, take a look here

\n`; 116 | readMeString += `

\n work in progress\n

\n`; 117 | readMeString += `

\n See ya <3\n

\n`; 118 | this.value = readMeString 119 | } 120 | 121 | return this.value 122 | } 123 | } 124 | 125 | class AsyncModule { 126 | 127 | constructor(private parent: Renderer, public flat: any) {} 128 | 129 | async render() { 130 | 131 | const {id, data, options} = this.flat 132 | 133 | if(id === "dynamic/followers") { 134 | 135 | const followers = (this.parent.services.get('request')! as RequestService).lastFollowers 136 | 137 | let returnString = ''; 138 | returnString += `\n \n \n \n \n \n \n`; 139 | returnString += JSON.parse(JSON.stringify(followers.lastFollowers)).reverse().map((follower, index) => { 140 | return ` \n \n \n \n \n`; 141 | }).join(''); 142 | returnString += ` \n \n \n `; 143 | 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`; 144 | 145 | return returnString 146 | } 147 | else if(id.startsWith('games/')) { 148 | return await (this.parent.services.get(id.split('/')[1])! as ChessService | GameboyService | GbaService | MinesweeperService | WordleService).toMd(this.parent.BASE_URL, data, options) 149 | } 150 | else if(id === "dynamic/generated") { 151 | let currentDate = new Date(); 152 | const days = [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] 153 | const months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep" , "Oct", "Nov", "Dec"] 154 | return `

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

\n`; 155 | } 156 | } 157 | } 158 | 159 | class Renderer { 160 | BASE_URL = `${process.env.APP_PROTOCOL}://${process.env.APP_SUB_DOMAIN}.${process.env.APP_DOMAIN}` 161 | services = new Map() 162 | structure: (Module | AsyncModule)[] 163 | startRenderDate: number 164 | config: Config 165 | constructor() { 166 | this.config = JSON.parse(fs.readFileSync('./config.json').toString()) 167 | this.createStructure() 168 | } 169 | 170 | createStructure() { 171 | const {config} = this 172 | this.structure = config.structure.filter(m => !m?.disabled).map(flatModule => { 173 | if( 174 | flatModule.id === "trigger" 175 | || flatModule.id.startsWith("static") 176 | || flatModule.id.startsWith("3rdParty") 177 | ) return new Module(this, flatModule) 178 | return new AsyncModule(this, flatModule) 179 | }) 180 | } 181 | 182 | async render() { 183 | 184 | this.startRenderDate = Date.now() 185 | 186 | const parts = await Promise.all(this.structure.filter(m => m.flat.id !== "dynamic/generated").map(m => m.render())) 187 | if(this.structure.at(-1).flat.id === "dynamic/generated") { 188 | let currentDate = new Date(); 189 | const days = [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] 190 | const months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep" , "Oct", "Nov", "Dec"] 191 | parts.push(`

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

\n`); 192 | } 193 | 194 | return parts.join('') 195 | } 196 | } 197 | 198 | export default new Renderer() -------------------------------------------------------------------------------- /src/readme/readme.module.ts: -------------------------------------------------------------------------------- 1 | import { Module, forwardRef } from '@nestjs/common'; 2 | import { ReadmeService } from './readme.service'; 3 | import { GamesModule } from 'src/games/games.module'; 4 | import { RequestModule } from 'src/request/request.module'; 5 | import { ConfigService } from 'src/config/config.service'; 6 | 7 | @Module({ 8 | imports: [forwardRef(() => GamesModule), RequestModule], 9 | providers: [ReadmeService, ConfigService], 10 | exports: [ReadmeService] 11 | }) 12 | export class ReadmeModule {} 13 | -------------------------------------------------------------------------------- /src/readme/readme.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, OnModuleInit } from '@nestjs/common'; 2 | import { Octokit } from 'octokit'; 3 | import { MinesweeperService } from 'src/games/minesweeper/minesweeper.service'; 4 | import { ChessService } from 'src/games/chess/chess.service'; 5 | import { RequestService } from 'src/request/request.service'; 6 | import { WordleService } from 'src/games/wordle/wordle.service'; 7 | import { GbaService } from 'src/games/gba/gba.service'; 8 | import renderer from './Renderer'; 9 | import { ConfigService } from 'src/config/config.service'; 10 | 11 | @Injectable() 12 | export class ReadmeService { 13 | currentContentSha: string | null; 14 | startDateRender: number; 15 | 16 | constructor( 17 | private configService: ConfigService, 18 | private requestService: RequestService, 19 | private minesweeperService: MinesweeperService, 20 | private chessService: ChessService, 21 | private wordleService: WordleService, 22 | private gbaService: GbaService, 23 | ) { 24 | renderer.services.set("request", this.requestService) 25 | renderer.services.set("minesweeper", this.minesweeperService) 26 | renderer.services.set("chess", this.chessService) 27 | renderer.services.set("wordle", this.wordleService) 28 | renderer.services.set("gba", this.gbaService) 29 | this.currentContentSha = null; 30 | } 31 | 32 | async push(octokit: Octokit, message: string, content: string, sha: string): Promise { 33 | const {config} = this.configService 34 | return (await octokit.request( 35 | `PUT /repos/${config.datas.repo.owner}/${config.datas.repo.name}/contents/${config.datas.repo.readme.path}`, 36 | { 37 | owner: config.datas.repo.owner, 38 | repo: config.datas.repo.name, 39 | path: config.datas.repo.readme.path, 40 | message, 41 | committer: { 42 | name: process.env.OCTO_COMMITTER_NAME, 43 | email: process.env.OCTO_COMMITTER_EMAIL, 44 | }, 45 | content, 46 | sha, 47 | }, 48 | )).data.content.sha 49 | } 50 | 51 | async commit(commitMessage: string) { 52 | const {config} = this.configService 53 | this.startDateRender = Date.now(); 54 | const octokit = new Octokit({ auth: process.env.GH_TOKEN }); 55 | 56 | let sha: string | any = this.currentContentSha 57 | if(!this.currentContentSha) { 58 | sha = (await octokit.request( 59 | `GET /repos/${config.datas.repo.owner}/${config.datas.repo.name}/contents/${config.datas.repo.readme.path}`, 60 | )).data.sha; 61 | } 62 | 63 | const readmeContent = await renderer.render() 64 | 65 | const buffer = Buffer.from(readmeContent); 66 | const base64 = buffer.toString('base64'); 67 | if(process.env.NO_COMMIT === "true") { 68 | console.log(readmeContent) 69 | return 70 | } 71 | let pushRespSha: string 72 | try { 73 | pushRespSha = await this.push(octokit, commitMessage, base64, sha) 74 | console.log(readmeContent) 75 | } catch (e) { 76 | this.currentContentSha = (await octokit.request(`GET /repos/${config.datas.repo.owner}/${config.datas.repo.name}/contents/${config.datas.repo.readme.path}`)).data.sha 77 | pushRespSha = await this.push(octokit, commitMessage, base64, this.currentContentSha) 78 | } 79 | this.currentContentSha = pushRespSha; 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /src/request/request.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { RequestService } from './request.service'; 3 | import { ConfigService } from 'src/config/config.service'; 4 | 5 | @Module({ 6 | providers: [RequestService, ConfigService], 7 | exports: [RequestService] 8 | }) 9 | export class RequestModule {} 10 | -------------------------------------------------------------------------------- /src/request/request.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import axios from 'axios'; 3 | import { ConfigService } from 'src/config/config.service'; 4 | 5 | @Injectable() 6 | export class RequestService { 7 | public lastFollowers: {followerCount: number, lastFollowers: {login: string, avatarUrl: string}[]} = {followerCount: 0, lastFollowers: []} 8 | 9 | constructor( 10 | private configService: ConfigService 11 | ) { 12 | this.getFollowers(3).then((followers) => { 13 | this.lastFollowers = followers 14 | }) 15 | } 16 | 17 | async getFollowers(limit: number): Promise<{followerCount: number, lastFollowers: {login: string, avatarUrl: string}[]}> { 18 | const {config} = this.configService 19 | try { 20 | const query = ` 21 | query { 22 | user(login: "${config.datas.repo.owner}") { 23 | totalCount: followers { 24 | totalCount 25 | } 26 | followers(first: ${limit}) { 27 | nodes { 28 | login 29 | avatarUrl 30 | } 31 | } 32 | } 33 | }`; 34 | const response = await axios.post('https://api.github.com/graphql', { query }, { 35 | headers: { 36 | Authorization: `Bearer ${process.env.GH_TOKEN}`, 37 | }, 38 | }); 39 | return { 40 | followerCount: response.data.data.user.totalCount.totalCount, 41 | lastFollowers: response.data.data.user.followers.nodes 42 | } 43 | } catch (error) { 44 | console.error(error) 45 | return {followerCount: 0, lastFollowers: []} 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/trigger/trigger.controller.ts: -------------------------------------------------------------------------------- 1 | import { join } from 'path'; 2 | import { Controller, Get, Res } from '@nestjs/common'; 3 | import { Response } from 'express'; 4 | import { ReadmeService } from 'src/readme/readme.service'; 5 | import { RequestService } from 'src/request/request.service'; 6 | 7 | @Controller('trigger') 8 | export class TriggerController { 9 | constructor( 10 | private requestService: RequestService, 11 | private readMeService: ReadmeService, 12 | ) {} 13 | 14 | @Get() 15 | trigger(@Res() res: Response) { 16 | // return as soon as possible 17 | this.requestService.getFollowers(3).then((followers) => { 18 | if(JSON.stringify(followers) !== JSON.stringify(this.requestService.lastFollowers)) { 19 | this.requestService.lastFollowers = followers 20 | this.readMeService.commit(':alarm_clock: Update followers table') 21 | } 22 | }) 23 | return res.sendFile(join(process.cwd(), 'public/trigger.webp')) 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/trigger/trigger.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { TriggerController } from './trigger.controller'; 3 | import { ReadmeModule } from 'src/readme/readme.module'; 4 | import { RequestModule } from 'src/request/request.module'; 5 | 6 | @Module({ 7 | imports: [ReadmeModule, RequestModule], 8 | controllers: [TriggerController], 9 | }) 10 | export class TriggerModule {} 11 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/users/users.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | 3 | @Injectable() 4 | export class UsersService {} 5 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------