diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..78ec7b1 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,2 @@ +__pycache__/ +*.py[co] diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..f824b3e --- /dev/null +++ b/.editorconfig @@ -0,0 +1,7 @@ +root = true + +[*] +trim_trailing_whitespace = true +insert_final_newline = true +indent_size = 2 +indent_style = space diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml new file mode 100644 index 0000000..4b72f2d --- /dev/null +++ b/.github/workflows/ci.yaml @@ -0,0 +1,37 @@ +name: "build" + +on: + push: + branches: "**" + tags-ignore: ["**"] + pull_request: + +permissions: + contents: "read" + packages: "write" + +jobs: + build: + # Only run on PRs if the source branch is on someone else's repo + if: "${{ github.event_name != 'pull_request' || github.repository != github.event.pull_request.head.repo.full_name }}" + runs-on: ubuntu-latest + steps: + - name: "setup" + id: "setup" + uses: "KyoriPowered/.github/.github/actions/setup-python-env@trunk" + - name: "install deps" + run: "poetry install" + - name: "setup / login to ghcr" + if: "${{ github.event_name == 'push' && steps.setup.outputs.publishing-branch != ''}}" + uses: "docker/login-action@v3.3.0" + with: + registry: "ghcr.io" + username: "${{ github.actor }}" + password: "${{ secrets.GITHUB_TOKEN }}" + - name: "docker / build" + run: "docker build -t ghcr.io/kyoripowered/pydisgit ." + - name: "docker / push" + if: "${{ github.event_name == 'push' && steps.setup.outputs.publishing-branch != ''}}" + run: "docker push ghcr.io/kyoripowered/pydisgit" + + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b0d3c81 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +# python +*.pyc +__pycache__/ +dist/ + +# OS dust + +.DS_Store +Thumbs.db diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..48fdbc6 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,34 @@ +ARG pythonversion=3.13 +FROM python:${pythonversion}-slim as builder + +# environment +ENV PYTHONDONTWRITEBYTECODE 1 +ENV PYTHONUNBUFFERED 1 + +# setup deps +COPY pyproject.toml poetry.lock ./ +RUN pip install poetry && poetry install --only main --no-root --no-directory + +# build project + +COPY src/ ./src/ +COPY README.md ./ +RUN poetry build -f wheel + +FROM python:${pythonversion} + +ENV APP_NAME=pydisgit +ENV HOME=/home/${APP_NAME} +ENV PATH="${HOME}/.local/bin:${PATH}" +EXPOSE 8000 + +RUN mkdir -p $HOME +RUN addgroup --gid 1000 --system $APP_NAME && adduser --system --uid 1000 $APP_NAME --ingroup $APP_NAME +RUN chown -R $APP_NAME:$APP_NAME $HOME +USER ${APP_NAME} + +COPY --from=builder dist/ ./dist/ +RUN pip install $(echo dist/*.whl) + +ENTRYPOINT [ "hypercorn", "asgi:pydisgit:app" ] + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..ff0bcde --- /dev/null +++ b/README.md @@ -0,0 +1,45 @@ +# pydisgit + +pydisgit is a port of the [disgit](https://github.com/JRoy/disgit) tool to Python on a [Quart](https://quart.palletsprojects.com/en/latest/)/ASGI stack. As with the original, pydisgit is a webook proxy for sending GitHub messages to Discord that provides higher quality results than the built-in GitHub endpoint that Discord offers. + +This additionally leaves it fully independent of the Cloudflare environment, and lets us use the (subjectively) superior and more reliable Python ecosystem. + +## usage + +pydisgit is published to PyPI for use in more custom environments, and as a Docker image ready to go. + +### environment variables +pydisgit has the following optional environment variables that you can use to customize your instance; +- `IGNORED_BRANCHES_REGEX` - A regex pattern for branches that should be ignored +- `IGNORED_BRANCHES` - A comma seperated list of branches that should be ignored +- `IGNORED_USERS` - A comma seperated list of users that should be ignored +- `IGNORED_PAYLOADS` - A comma seperated list of webhook events that should be ignored + +## licensing + +pydisgit is released under the terms of the Apache Software License version 2.0. Thanks additionally go out to JRoy and all other contributors to upstream disgit for making it what it is today. + +## Supported Events +The following webhook events are supported as of now; +* [check_run](https://docs.github.com/en/developers/webhooks-and-events/webhook-events-and-payloads#check_run) +* [commit_comment](https://docs.github.com/en/developers/webhooks-and-events/webhook-events-and-payloads#commit_comment) +* [create](https://docs.github.com/en/developers/webhooks-and-events/webhook-events-and-payloads#create) +* [delete](https://docs.github.com/en/developers/webhooks-and-events/webhook-events-and-payloads#delete) +* [deployment](https://docs.github.com/en/developers/webhooks-and-events/webhooks/webhook-events-and-payloads#deployment) +* [deployment_status](https://docs.github.com/en/developers/webhooks-and-events/webhooks/webhook-events-and-payloads#deployment_status) +* [discussion](https://docs.github.com/en/developers/webhooks-and-events/webhook-events-and-payloads#discussion) +* [discussion_comment](https://docs.github.com/en/developers/webhooks-and-events/webhook-events-and-payloads#discussion_comment) +* [fork](https://docs.github.com/en/developers/webhooks-and-events/webhook-events-and-payloads#fork) +* [gollum](https://docs.github.com/en/developers/webhooks-and-events/webhooks/webhook-events-and-payloads#gollum) (wiki) +* [issue_comment](https://docs.github.com/en/developers/webhooks-and-events/webhook-events-and-payloads#issue_comment) + * This event also sends pull request comments...*sigh* +* [issues](https://docs.github.com/en/developers/webhooks-and-events/webhook-events-and-payloads#issues) +* [package](https://docs.github.com/en/webhooks-and-events/webhooks/webhook-events-and-payloads#package) +* [ping](https://docs.github.com/en/developers/webhooks-and-events/webhook-events-and-payloads#ping) +* [pull_request](https://docs.github.com/en/developers/webhooks-and-events/webhook-events-and-payloads#pull_request) +* [pull_request_review](https://docs.github.com/en/developers/webhooks-and-events/webhook-events-and-payloads#pull_request_review) +* [pull_request_review_comment](https://docs.github.com/en/developers/webhooks-and-events/webhook-events-and-payloads#pull_request_review_comment) +* [push](https://docs.github.com/en/developers/webhooks-and-events/webhook-events-and-payloads#push) +* [release](https://docs.github.com/en/developers/webhooks-and-events/webhook-events-and-payloads#release) +* [star](https://docs.github.com/en/developers/webhooks-and-events/webhook-events-and-payloads#star) +* ...feel free to contribute more that suit your needs! diff --git a/poetry.lock b/poetry.lock new file mode 100644 index 0000000..c52a669 --- /dev/null +++ b/poetry.lock @@ -0,0 +1,466 @@ +# This file is automatically @generated by Poetry 2.0.1 and should not be changed by hand. + +[[package]] +name = "aiofiles" +version = "24.1.0" +description = "File support for asyncio." +optional = false +python-versions = ">=3.8" +groups = ["main"] +files = [ + {file = "aiofiles-24.1.0-py3-none-any.whl", hash = "sha256:b4ec55f4195e3eb5d7abd1bf7e061763e864dd4954231fb8539a0ef8bb8260e5"}, + {file = "aiofiles-24.1.0.tar.gz", hash = "sha256:22a075c9e5a3810f0c2e48f3008c94d68c65d763b9b03857924c99e57355166c"}, +] + +[[package]] +name = "anyio" +version = "4.8.0" +description = "High level compatibility layer for multiple asynchronous event loop implementations" +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "anyio-4.8.0-py3-none-any.whl", hash = "sha256:b5011f270ab5eb0abf13385f851315585cc37ef330dd88e27ec3d34d651fd47a"}, + {file = "anyio-4.8.0.tar.gz", hash = "sha256:1d9fe889df5212298c0c0723fa20479d1b94883a2df44bd3897aa91083316f7a"}, +] + +[package.dependencies] +idna = ">=2.8" +sniffio = ">=1.1" +typing_extensions = {version = ">=4.5", markers = "python_version < \"3.13\""} + +[package.extras] +doc = ["Sphinx (>=7.4,<8.0)", "packaging", "sphinx-autodoc-typehints (>=1.2.0)", "sphinx_rtd_theme"] +test = ["anyio[trio]", "coverage[toml] (>=7)", "exceptiongroup (>=1.2.0)", "hypothesis (>=4.0)", "psutil (>=5.9)", "pytest (>=7.0)", "trustme", "truststore (>=0.9.1)", "uvloop (>=0.21)"] +trio = ["trio (>=0.26.1)"] + +[[package]] +name = "blinker" +version = "1.9.0" +description = "Fast, simple object-to-object and broadcast signaling" +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "blinker-1.9.0-py3-none-any.whl", hash = "sha256:ba0efaa9080b619ff2f3459d1d500c57bddea4a6b424b60a91141db6fd2f08bc"}, + {file = "blinker-1.9.0.tar.gz", hash = "sha256:b4ce2265a7abece45e7cc896e98dbebe6cead56bcf805a3d23136d145f5445bf"}, +] + +[[package]] +name = "certifi" +version = "2024.12.14" +description = "Python package for providing Mozilla's CA Bundle." +optional = false +python-versions = ">=3.6" +groups = ["main"] +files = [ + {file = "certifi-2024.12.14-py3-none-any.whl", hash = "sha256:1275f7a45be9464efc1173084eaa30f866fe2e47d389406136d332ed4967ec56"}, + {file = "certifi-2024.12.14.tar.gz", hash = "sha256:b650d30f370c2b724812bee08008be0c4163b163ddaec3f2546c1caf65f191db"}, +] + +[[package]] +name = "click" +version = "8.1.8" +description = "Composable command line interface toolkit" +optional = false +python-versions = ">=3.7" +groups = ["main"] +files = [ + {file = "click-8.1.8-py3-none-any.whl", hash = "sha256:63c132bbbed01578a06712a2d1f497bb62d9c1c0d329b7903a866228027263b2"}, + {file = "click-8.1.8.tar.gz", hash = "sha256:ed53c9d8990d83c2a27deae68e4ee337473f6330c040a31d4225c9574d16096a"}, +] + +[package.dependencies] +colorama = {version = "*", markers = "platform_system == \"Windows\""} + +[[package]] +name = "colorama" +version = "0.4.6" +description = "Cross-platform colored terminal text." +optional = false +python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7" +groups = ["main"] +markers = "platform_system == \"Windows\"" +files = [ + {file = "colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6"}, + {file = "colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"}, +] + +[[package]] +name = "flask" +version = "3.1.0" +description = "A simple framework for building complex web applications." +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "flask-3.1.0-py3-none-any.whl", hash = "sha256:d667207822eb83f1c4b50949b1623c8fc8d51f2341d65f72e1a1815397551136"}, + {file = "flask-3.1.0.tar.gz", hash = "sha256:5f873c5184c897c8d9d1b05df1e3d01b14910ce69607a117bd3277098a5836ac"}, +] + +[package.dependencies] +blinker = ">=1.9" +click = ">=8.1.3" +itsdangerous = ">=2.2" +Jinja2 = ">=3.1.2" +Werkzeug = ">=3.1" + +[package.extras] +async = ["asgiref (>=3.2)"] +dotenv = ["python-dotenv"] + +[[package]] +name = "h11" +version = "0.14.0" +description = "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1" +optional = false +python-versions = ">=3.7" +groups = ["main"] +files = [ + {file = "h11-0.14.0-py3-none-any.whl", hash = "sha256:e3fe4ac4b851c468cc8363d500db52c2ead036020723024a109d37346efaa761"}, + {file = "h11-0.14.0.tar.gz", hash = "sha256:8f19fbbe99e72420ff35c00b27a34cb9937e902a8b810e2c88300c6f0a3b699d"}, +] + +[[package]] +name = "h2" +version = "4.1.0" +description = "HTTP/2 State-Machine based protocol implementation" +optional = false +python-versions = ">=3.6.1" +groups = ["main"] +files = [ + {file = "h2-4.1.0-py3-none-any.whl", hash = "sha256:03a46bcf682256c95b5fd9e9a99c1323584c3eec6440d379b9903d709476bc6d"}, + {file = "h2-4.1.0.tar.gz", hash = "sha256:a83aca08fbe7aacb79fec788c9c0bac936343560ed9ec18b82a13a12c28d2abb"}, +] + +[package.dependencies] +hpack = ">=4.0,<5" +hyperframe = ">=6.0,<7" + +[[package]] +name = "hpack" +version = "4.1.0" +description = "Pure-Python HPACK header encoding" +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "hpack-4.1.0-py3-none-any.whl", hash = "sha256:157ac792668d995c657d93111f46b4535ed114f0c9c8d672271bbec7eae1b496"}, + {file = "hpack-4.1.0.tar.gz", hash = "sha256:ec5eca154f7056aa06f196a557655c5b009b382873ac8d1e66e79e87535f1dca"}, +] + +[[package]] +name = "httpcore" +version = "1.0.7" +description = "A minimal low-level HTTP client." +optional = false +python-versions = ">=3.8" +groups = ["main"] +files = [ + {file = "httpcore-1.0.7-py3-none-any.whl", hash = "sha256:a3fff8f43dc260d5bd363d9f9cf1830fa3a458b332856f34282de498ed420edd"}, + {file = "httpcore-1.0.7.tar.gz", hash = "sha256:8551cb62a169ec7162ac7be8d4817d561f60e08eaa485234898414bb5a8a0b4c"}, +] + +[package.dependencies] +certifi = "*" +h11 = ">=0.13,<0.15" + +[package.extras] +asyncio = ["anyio (>=4.0,<5.0)"] +http2 = ["h2 (>=3,<5)"] +socks = ["socksio (==1.*)"] +trio = ["trio (>=0.22.0,<1.0)"] + +[[package]] +name = "httpx" +version = "0.28.1" +description = "The next generation HTTP client." +optional = false +python-versions = ">=3.8" +groups = ["main"] +files = [ + {file = "httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad"}, + {file = "httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc"}, +] + +[package.dependencies] +anyio = "*" +certifi = "*" +httpcore = "==1.*" +idna = "*" + +[package.extras] +brotli = ["brotli", "brotlicffi"] +cli = ["click (==8.*)", "pygments (==2.*)", "rich (>=10,<14)"] +http2 = ["h2 (>=3,<5)"] +socks = ["socksio (==1.*)"] +zstd = ["zstandard (>=0.18.0)"] + +[[package]] +name = "hypercorn" +version = "0.17.3" +description = "A ASGI Server based on Hyper libraries and inspired by Gunicorn" +optional = false +python-versions = ">=3.8" +groups = ["main"] +files = [ + {file = "hypercorn-0.17.3-py3-none-any.whl", hash = "sha256:059215dec34537f9d40a69258d323f56344805efb462959e727152b0aa504547"}, + {file = "hypercorn-0.17.3.tar.gz", hash = "sha256:1b37802ee3ac52d2d85270700d565787ab16cf19e1462ccfa9f089ca17574165"}, +] + +[package.dependencies] +h11 = "*" +h2 = ">=3.1.0" +priority = "*" +wsproto = ">=0.14.0" + +[package.extras] +docs = ["pydata_sphinx_theme", "sphinxcontrib_mermaid"] +h3 = ["aioquic (>=0.9.0,<1.0)"] +trio = ["trio (>=0.22.0)"] +uvloop = ["uvloop (>=0.18)"] + +[[package]] +name = "hyperframe" +version = "6.1.0" +description = "Pure-Python HTTP/2 framing" +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "hyperframe-6.1.0-py3-none-any.whl", hash = "sha256:b03380493a519fce58ea5af42e4a42317bf9bd425596f7a0835ffce80f1a42e5"}, + {file = "hyperframe-6.1.0.tar.gz", hash = "sha256:f630908a00854a7adeabd6382b43923a4c4cd4b821fcb527e6ab9e15382a3b08"}, +] + +[[package]] +name = "idna" +version = "3.10" +description = "Internationalized Domain Names in Applications (IDNA)" +optional = false +python-versions = ">=3.6" +groups = ["main"] +files = [ + {file = "idna-3.10-py3-none-any.whl", hash = "sha256:946d195a0d259cbba61165e88e65941f16e9b36ea6ddb97f00452bae8b1287d3"}, + {file = "idna-3.10.tar.gz", hash = "sha256:12f65c9b470abda6dc35cf8e63cc574b1c52b11df2c86030af0ac09b01b13ea9"}, +] + +[package.extras] +all = ["flake8 (>=7.1.1)", "mypy (>=1.11.2)", "pytest (>=8.3.2)", "ruff (>=0.6.2)"] + +[[package]] +name = "itsdangerous" +version = "2.2.0" +description = "Safely pass data to untrusted environments and back." +optional = false +python-versions = ">=3.8" +groups = ["main"] +files = [ + {file = "itsdangerous-2.2.0-py3-none-any.whl", hash = "sha256:c6242fc49e35958c8b15141343aa660db5fc54d4f13a1db01a3f5891b98700ef"}, + {file = "itsdangerous-2.2.0.tar.gz", hash = "sha256:e0050c0b7da1eea53ffaf149c0cfbb5c6e2e2b69c4bef22c81fa6eb73e5f6173"}, +] + +[[package]] +name = "jinja2" +version = "3.1.5" +description = "A very fast and expressive template engine." +optional = false +python-versions = ">=3.7" +groups = ["main"] +files = [ + {file = "jinja2-3.1.5-py3-none-any.whl", hash = "sha256:aba0f4dc9ed8013c424088f68a5c226f7d6097ed89b246d7749c2ec4175c6adb"}, + {file = "jinja2-3.1.5.tar.gz", hash = "sha256:8fefff8dc3034e27bb80d67c671eb8a9bc424c0ef4c0826edbff304cceff43bb"}, +] + +[package.dependencies] +MarkupSafe = ">=2.0" + +[package.extras] +i18n = ["Babel (>=2.7)"] + +[[package]] +name = "markupsafe" +version = "3.0.2" +description = "Safely add untrusted strings to HTML/XML markup." +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "MarkupSafe-3.0.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:7e94c425039cde14257288fd61dcfb01963e658efbc0ff54f5306b06054700f8"}, + {file = "MarkupSafe-3.0.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:9e2d922824181480953426608b81967de705c3cef4d1af983af849d7bd619158"}, + {file = "MarkupSafe-3.0.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:38a9ef736c01fccdd6600705b09dc574584b89bea478200c5fbf112a6b0d5579"}, + {file = "MarkupSafe-3.0.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bbcb445fa71794da8f178f0f6d66789a28d7319071af7a496d4d507ed566270d"}, + {file = "MarkupSafe-3.0.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:57cb5a3cf367aeb1d316576250f65edec5bb3be939e9247ae594b4bcbc317dfb"}, + {file = "MarkupSafe-3.0.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:3809ede931876f5b2ec92eef964286840ed3540dadf803dd570c3b7e13141a3b"}, + {file = "MarkupSafe-3.0.2-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:e07c3764494e3776c602c1e78e298937c3315ccc9043ead7e685b7f2b8d47b3c"}, + {file = "MarkupSafe-3.0.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:b424c77b206d63d500bcb69fa55ed8d0e6a3774056bdc4839fc9298a7edca171"}, + {file = "MarkupSafe-3.0.2-cp310-cp310-win32.whl", hash = "sha256:fcabf5ff6eea076f859677f5f0b6b5c1a51e70a376b0579e0eadef8db48c6b50"}, + {file = "MarkupSafe-3.0.2-cp310-cp310-win_amd64.whl", hash = "sha256:6af100e168aa82a50e186c82875a5893c5597a0c1ccdb0d8b40240b1f28b969a"}, + {file = "MarkupSafe-3.0.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:9025b4018f3a1314059769c7bf15441064b2207cb3f065e6ea1e7359cb46db9d"}, + {file = "MarkupSafe-3.0.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:93335ca3812df2f366e80509ae119189886b0f3c2b81325d39efdb84a1e2ae93"}, + {file = "MarkupSafe-3.0.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2cb8438c3cbb25e220c2ab33bb226559e7afb3baec11c4f218ffa7308603c832"}, + {file = "MarkupSafe-3.0.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a123e330ef0853c6e822384873bef7507557d8e4a082961e1defa947aa59ba84"}, + {file = "MarkupSafe-3.0.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1e084f686b92e5b83186b07e8a17fc09e38fff551f3602b249881fec658d3eca"}, + {file = "MarkupSafe-3.0.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:d8213e09c917a951de9d09ecee036d5c7d36cb6cb7dbaece4c71a60d79fb9798"}, + {file = "MarkupSafe-3.0.2-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:5b02fb34468b6aaa40dfc198d813a641e3a63b98c2b05a16b9f80b7ec314185e"}, + {file = "MarkupSafe-3.0.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:0bff5e0ae4ef2e1ae4fdf2dfd5b76c75e5c2fa4132d05fc1b0dabcd20c7e28c4"}, + {file = "MarkupSafe-3.0.2-cp311-cp311-win32.whl", hash = "sha256:6c89876f41da747c8d3677a2b540fb32ef5715f97b66eeb0c6b66f5e3ef6f59d"}, + {file = "MarkupSafe-3.0.2-cp311-cp311-win_amd64.whl", hash = "sha256:70a87b411535ccad5ef2f1df5136506a10775d267e197e4cf531ced10537bd6b"}, + {file = "MarkupSafe-3.0.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:9778bd8ab0a994ebf6f84c2b949e65736d5575320a17ae8984a77fab08db94cf"}, + {file = "MarkupSafe-3.0.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:846ade7b71e3536c4e56b386c2a47adf5741d2d8b94ec9dc3e92e5e1ee1e2225"}, + {file = "MarkupSafe-3.0.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1c99d261bd2d5f6b59325c92c73df481e05e57f19837bdca8413b9eac4bd8028"}, + {file = "MarkupSafe-3.0.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e17c96c14e19278594aa4841ec148115f9c7615a47382ecb6b82bd8fea3ab0c8"}, + {file = "MarkupSafe-3.0.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:88416bd1e65dcea10bc7569faacb2c20ce071dd1f87539ca2ab364bf6231393c"}, + {file = "MarkupSafe-3.0.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:2181e67807fc2fa785d0592dc2d6206c019b9502410671cc905d132a92866557"}, + {file = "MarkupSafe-3.0.2-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:52305740fe773d09cffb16f8ed0427942901f00adedac82ec8b67752f58a1b22"}, + {file = "MarkupSafe-3.0.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:ad10d3ded218f1039f11a75f8091880239651b52e9bb592ca27de44eed242a48"}, + {file = "MarkupSafe-3.0.2-cp312-cp312-win32.whl", hash = "sha256:0f4ca02bea9a23221c0182836703cbf8930c5e9454bacce27e767509fa286a30"}, + {file = "MarkupSafe-3.0.2-cp312-cp312-win_amd64.whl", hash = "sha256:8e06879fc22a25ca47312fbe7c8264eb0b662f6db27cb2d3bbbc74b1df4b9b87"}, + {file = "MarkupSafe-3.0.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:ba9527cdd4c926ed0760bc301f6728ef34d841f405abf9d4f959c478421e4efd"}, + {file = "MarkupSafe-3.0.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f8b3d067f2e40fe93e1ccdd6b2e1d16c43140e76f02fb1319a05cf2b79d99430"}, + {file = "MarkupSafe-3.0.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:569511d3b58c8791ab4c2e1285575265991e6d8f8700c7be0e88f86cb0672094"}, + {file = "MarkupSafe-3.0.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:15ab75ef81add55874e7ab7055e9c397312385bd9ced94920f2802310c930396"}, + {file = "MarkupSafe-3.0.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f3818cb119498c0678015754eba762e0d61e5b52d34c8b13d770f0719f7b1d79"}, + {file = "MarkupSafe-3.0.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:cdb82a876c47801bb54a690c5ae105a46b392ac6099881cdfb9f6e95e4014c6a"}, + {file = "MarkupSafe-3.0.2-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:cabc348d87e913db6ab4aa100f01b08f481097838bdddf7c7a84b7575b7309ca"}, + {file = "MarkupSafe-3.0.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:444dcda765c8a838eaae23112db52f1efaf750daddb2d9ca300bcae1039adc5c"}, + {file = "MarkupSafe-3.0.2-cp313-cp313-win32.whl", hash = "sha256:bcf3e58998965654fdaff38e58584d8937aa3096ab5354d493c77d1fdd66d7a1"}, + {file = "MarkupSafe-3.0.2-cp313-cp313-win_amd64.whl", hash = "sha256:e6a2a455bd412959b57a172ce6328d2dd1f01cb2135efda2e4576e8a23fa3b0f"}, + {file = "MarkupSafe-3.0.2-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:b5a6b3ada725cea8a5e634536b1b01c30bcdcd7f9c6fff4151548d5bf6b3a36c"}, + {file = "MarkupSafe-3.0.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:a904af0a6162c73e3edcb969eeeb53a63ceeb5d8cf642fade7d39e7963a22ddb"}, + {file = "MarkupSafe-3.0.2-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4aa4e5faecf353ed117801a068ebab7b7e09ffb6e1d5e412dc852e0da018126c"}, + {file = "MarkupSafe-3.0.2-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c0ef13eaeee5b615fb07c9a7dadb38eac06a0608b41570d8ade51c56539e509d"}, + {file = "MarkupSafe-3.0.2-cp313-cp313t-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d16a81a06776313e817c951135cf7340a3e91e8c1ff2fac444cfd75fffa04afe"}, + {file = "MarkupSafe-3.0.2-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:6381026f158fdb7c72a168278597a5e3a5222e83ea18f543112b2662a9b699c5"}, + {file = "MarkupSafe-3.0.2-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:3d79d162e7be8f996986c064d1c7c817f6df3a77fe3d6859f6f9e7be4b8c213a"}, + {file = "MarkupSafe-3.0.2-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:131a3c7689c85f5ad20f9f6fb1b866f402c445b220c19fe4308c0b147ccd2ad9"}, + {file = "MarkupSafe-3.0.2-cp313-cp313t-win32.whl", hash = "sha256:ba8062ed2cf21c07a9e295d5b8a2a5ce678b913b45fdf68c32d95d6c1291e0b6"}, + {file = "MarkupSafe-3.0.2-cp313-cp313t-win_amd64.whl", hash = "sha256:e444a31f8db13eb18ada366ab3cf45fd4b31e4db1236a4448f68778c1d1a5a2f"}, + {file = "MarkupSafe-3.0.2-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:eaa0a10b7f72326f1372a713e73c3f739b524b3af41feb43e4921cb529f5929a"}, + {file = "MarkupSafe-3.0.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:48032821bbdf20f5799ff537c7ac3d1fba0ba032cfc06194faffa8cda8b560ff"}, + {file = "MarkupSafe-3.0.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1a9d3f5f0901fdec14d8d2f66ef7d035f2157240a433441719ac9a3fba440b13"}, + {file = "MarkupSafe-3.0.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:88b49a3b9ff31e19998750c38e030fc7bb937398b1f78cfa599aaef92d693144"}, + {file = "MarkupSafe-3.0.2-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:cfad01eed2c2e0c01fd0ecd2ef42c492f7f93902e39a42fc9ee1692961443a29"}, + {file = "MarkupSafe-3.0.2-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:1225beacc926f536dc82e45f8a4d68502949dc67eea90eab715dea3a21c1b5f0"}, + {file = "MarkupSafe-3.0.2-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:3169b1eefae027567d1ce6ee7cae382c57fe26e82775f460f0b2778beaad66c0"}, + {file = "MarkupSafe-3.0.2-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:eb7972a85c54febfb25b5c4b4f3af4dcc731994c7da0d8a0b4a6eb0640e1d178"}, + {file = "MarkupSafe-3.0.2-cp39-cp39-win32.whl", hash = "sha256:8c4e8c3ce11e1f92f6536ff07154f9d49677ebaaafc32db9db4620bc11ed480f"}, + {file = "MarkupSafe-3.0.2-cp39-cp39-win_amd64.whl", hash = "sha256:6e296a513ca3d94054c2c881cc913116e90fd030ad1c656b3869762b754f5f8a"}, + {file = "markupsafe-3.0.2.tar.gz", hash = "sha256:ee55d3edf80167e48ea11a923c7386f4669df67d7994554387f84e7d8b0a2bf0"}, +] + +[[package]] +name = "priority" +version = "2.0.0" +description = "A pure-Python implementation of the HTTP/2 priority tree" +optional = false +python-versions = ">=3.6.1" +groups = ["main"] +files = [ + {file = "priority-2.0.0-py3-none-any.whl", hash = "sha256:6f8eefce5f3ad59baf2c080a664037bb4725cd0a790d53d59ab4059288faf6aa"}, + {file = "priority-2.0.0.tar.gz", hash = "sha256:c965d54f1b8d0d0b19479db3924c7c36cf672dbf2aec92d43fbdaf4492ba18c0"}, +] + +[[package]] +name = "python-dotenv" +version = "1.0.1" +description = "Read key-value pairs from a .env file and set them as environment variables" +optional = false +python-versions = ">=3.8" +groups = ["main"] +files = [ + {file = "python-dotenv-1.0.1.tar.gz", hash = "sha256:e324ee90a023d808f1959c46bcbc04446a10ced277783dc6ee09987c37ec10ca"}, + {file = "python_dotenv-1.0.1-py3-none-any.whl", hash = "sha256:f7b63ef50f1b690dddf550d03497b66d609393b40b564ed0d674909a68ebf16a"}, +] + +[package.extras] +cli = ["click (>=5.0)"] + +[[package]] +name = "quart" +version = "0.20.0" +description = "A Python ASGI web framework with the same API as Flask" +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "quart-0.20.0-py3-none-any.whl", hash = "sha256:003c08f551746710acb757de49d9b768986fd431517d0eb127380b656b98b8f1"}, + {file = "quart-0.20.0.tar.gz", hash = "sha256:08793c206ff832483586f5ae47018c7e40bdd75d886fee3fabbdaa70c2cf505d"}, +] + +[package.dependencies] +aiofiles = "*" +blinker = ">=1.6" +click = ">=8.0" +flask = ">=3.0" +hypercorn = ">=0.11.2" +itsdangerous = "*" +jinja2 = "*" +markupsafe = "*" +python-dotenv = {version = "*", optional = true, markers = "extra == \"dotenv\""} +werkzeug = ">=3.0" + +[package.extras] +dotenv = ["python-dotenv"] + +[[package]] +name = "sniffio" +version = "1.3.1" +description = "Sniff out which async library your code is running under" +optional = false +python-versions = ">=3.7" +groups = ["main"] +files = [ + {file = "sniffio-1.3.1-py3-none-any.whl", hash = "sha256:2f6da418d1f1e0fddd844478f41680e794e6051915791a034ff65e5f100525a2"}, + {file = "sniffio-1.3.1.tar.gz", hash = "sha256:f4324edc670a0f49750a81b895f35c3adb843cca46f0530f79fc1babb23789dc"}, +] + +[[package]] +name = "typing-extensions" +version = "4.12.2" +description = "Backported and Experimental Type Hints for Python 3.8+" +optional = false +python-versions = ">=3.8" +groups = ["main"] +markers = "python_version < \"3.13\"" +files = [ + {file = "typing_extensions-4.12.2-py3-none-any.whl", hash = "sha256:04e5ca0351e0f3f85c6853954072df659d0d13fac324d0072316b67d7794700d"}, + {file = "typing_extensions-4.12.2.tar.gz", hash = "sha256:1a7ead55c7e559dd4dee8856e3a88b41225abfe1ce8df57b7c13915fe121ffb8"}, +] + +[[package]] +name = "werkzeug" +version = "3.1.3" +description = "The comprehensive WSGI web application library." +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "werkzeug-3.1.3-py3-none-any.whl", hash = "sha256:54b78bf3716d19a65be4fceccc0d1d7b89e608834989dfae50ea87564639213e"}, + {file = "werkzeug-3.1.3.tar.gz", hash = "sha256:60723ce945c19328679790e3282cc758aa4a6040e4bb330f53d30fa546d44746"}, +] + +[package.dependencies] +MarkupSafe = ">=2.1.1" + +[package.extras] +watchdog = ["watchdog (>=2.3)"] + +[[package]] +name = "wsproto" +version = "1.2.0" +description = "WebSockets state-machine based protocol implementation" +optional = false +python-versions = ">=3.7.0" +groups = ["main"] +files = [ + {file = "wsproto-1.2.0-py3-none-any.whl", hash = "sha256:b9acddd652b585d75b20477888c56642fdade28bdfd3579aa24a4d2c037dd736"}, + {file = "wsproto-1.2.0.tar.gz", hash = "sha256:ad565f26ecb92588a3e43bc3d96164de84cd9902482b130d0ddbaa9664a85065"}, +] + +[package.dependencies] +h11 = ">=0.9.0,<1" + +[metadata] +lock-version = "2.1" +python-versions = ">= 3.12" +content-hash = "b1cde66192a6a4b20a3fe1b6094a16bbbc5f0db39c268b11b7b2ef83b0177840" diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..632e1c9 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,22 @@ +[project] +name = "pydisgit" +version = "0.1.0" +description = "Python port of GitHub webhook to discord proxy" +authors = [ + { name = "KyoriPowered" }, +] +license = "Apache-2.0" +readme = "README.md" +requires-python = ">= 3.12" +dependencies = [ + "quart [dotenv] ~= 0.20.0", + "httpx (>=0.28.1,<0.29.0)", + "hypercorn (>=0.17.3,<0.18.0)" +] + +[project.scripts] +pydisgit = 'pydisgit:run_dev' + +[build-system] +requires = ["poetry-core"] +build-backend = "poetry.core.masonry.api" diff --git a/src/pydisgit/__init__.py b/src/pydisgit/__init__.py new file mode 100644 index 0000000..403e795 --- /dev/null +++ b/src/pydisgit/__init__.py @@ -0,0 +1,89 @@ +from httpx import AsyncClient +from quart import Quart, Response, request +from werkzeug.exceptions import BadRequest + +from pydisgit.webhook import WebhookRouter +from .conf import Config, BoundEnv + +Quart.__annotations__["http_client"] = AsyncClient +app = Quart(__name__) + + +# config setup +app.config.from_object(Config) +app.config.from_prefixed_env(prefix="PYDISGIT") + +bound = BoundEnv(app.config) + +from .handlers import router as free_handler_router +handler_router = free_handler_router.bind(bound, app.logger) + +# http client + +@app.before_serving +async def setup_httpclient(): + app.http_client = AsyncClient( + headers={'User-Agent': 'pydisgit (kyori flavour)'} + ) + +@app.after_serving +async def teardown_httpclient(): + await app.http_client.aclose() + +@app.get('/') +async def hello() -> str: + """ + root handler + """ + return "begone foul beast", 400 + + +@app.post('//') +async def gh_hook(hook_id: str, token: str) -> dict: + event = request.headers["X-GitHub-Event"] + if not event or not request.content_type: + raise BadRequest("No event or content type") + + #if (!(await validateRequest(request, env.githubWebhookSecret))) { + # return new Response('Invalid secret', { status: 403 }); + #} + + if "application/json" in request.content_type: + json = await request.json + elif "application/x-www-form-urlencoded" in request.content_type: + json = json.loads((await request.form)['payload']) + else: + raise BadRequest(f"Unknown content type {request.content_type}") + + embed = handler_router.process_request(event, json) + if not embed: + return 'Webhook NO-OP', 200 + + if app.config['DEBUG']: + pass + # embed = await bound.buildDebugPaste(embed) + + http: AsyncClient = app.http_client + + result = await http.post(f"https://discord.com/api/webhooks/{hook_id}/{token}", json = embed) + + if result.status_code == 200: + result_text = "".join([await a async for a in result.aiter_text()]) + return {"message": f"We won! Webhook {hook_id} executed with token {token} :3, response: {result_text}"}, 200 + else: + return Response(response = await result.aread(), status = result.status_code, content_type=result.headers) + + +@app.get('/health') +async def health_check() -> str: + """ + simple aliveness check + """ + return "OK" + + +def run_dev() -> None: + """ + Run a development instance of the app + """ + app.run() diff --git a/src/pydisgit/conf.py b/src/pydisgit/conf.py new file mode 100644 index 0000000..a4db441 --- /dev/null +++ b/src/pydisgit/conf.py @@ -0,0 +1,82 @@ +""" +Configuration for pydisgit +""" +from typing import Optional +import re + +class Config: + """ + Raw environment from Workers + """ + IGNORED_BRANCH_REGEX: str = "" + IGNORED_BRANCHES: str = "" + IGNORED_USERS: str = "" + IGNORED_PAYLOADS: str = "" + + # secrets + PASTE_GG_API_KEY: Optional[str] = None + GITHUB_WEBHOOK_SECRET: Optional[str] = None + + +class BoundEnv: + """ + Parsed + bound environment + """ + + __ignored_branch_pattern: re.Pattern + __ignored_branches: list[str] + __ignored_users: list[str] + __ignored_payloads: list[str] + __pastegg_api_key: str + __github_webhook_secret: str; + + def __init__(self, env): + self.__ignored_branch_pattern = re.compile(env['IGNORED_BRANCH_REGEX']) if 'IGNORED_BRANCH_REGEX' in env else None + self.__ignored_branches = env['IGNORED_BRANCHES'].split(",") + self.__ignored_users = env['IGNORED_USERS'].split(",") + self.__ignored_payloads = env['IGNORED_PAYLOADS'].split(",") + self.__pastegg_api_key = env['PASTE_GG_API_KEY'] + self.__github_webhook_secret = env['GITHUB_WEBHOOK_SECRET'] + + def ignored_branch(self, branch: str) -> bool: + return (self.__ignored_branch_pattern + and self.__ignored_branch_pattern.match(branch)) \ + or branch in self.__ignored_branches + + def ignored_user(self, user: str) -> bool: + return user in self.__ignored_users + + def ignored_payload(self, payload: str) -> bool: + return payload in self.__ignored_payloads + + @property + def github_webhook_secret(self) -> str: + return self.__github_webhook_secret + + async def build_debug_paste(self, embed: any) -> str: + pass +# embed = JSON.stringify({ +# "files": [ +# { +# "content": { +# "format": "text", +# "value": embed +# } +# } +# ] +# }); +# +# embed = await (await fetch("https://api.paste.gg/v1/pastes", { +# "headers": { +# "user-agent": "disgit (kyori flavor)", +# "content-type": "application/json", +# "Authorization": f'Key {self.__pastegg_api_key}' +# }, +# "method": "POST", +# "body": embed +# })).text(); +# +# embed = JSON.stringify({ +# "content": embed +# }); +# return embed; diff --git a/src/pydisgit/handlers.py b/src/pydisgit/handlers.py new file mode 100644 index 0000000..eed1937 --- /dev/null +++ b/src/pydisgit/handlers.py @@ -0,0 +1,531 @@ +""" +GH event handlers +""" + +from .conf import BoundEnv +from .util import short_commit, truncate +from .webhook import EmbedBody, Field, WebhookRouter + +__slots__ = ['router'] + +router = WebhookRouter() + +@router.handler('ping') +def ping(zen, hook, repository, sender, organization) -> EmbedBody: + is_org = hook['type'] == 'Organization' + name = organization['login'] if is_org else repository['full_name'] + + return EmbedBody( + f'[{name}] {hook['type']} hook ping received', + None, + sender, + 0xb8e98c, + zen + ) + + +check_run_action = router.by_action("check_run") + +@check_run_action('completed') +# @router.filter(test = BoundEnv.ignored_branch, path = ['check_run', 'check_suite', 'head_branch']) # would this ever be nicer? than injecting the env as a parameter +def check_completed(env: BoundEnv, check_run, repository, sender) -> EmbedBody: + conclusion = check_run["conclusion"] + output = check_run["output"] + html_url = check_run["html_url"] + check_suite = check_run["check_suite"] + + if not repository or not (target := check_suite["head_branch"]): + return None + + if env.ignored_branch(target): + return None + + if len(check_suite["pull_requests"]): + pull = check_suite["pull_requests"][0] + if pull.url.startsWith(f'https://api.github.com/repos/{repository["full_name"]}'): + target = f'PR #{pull.number}' + + color = 0xaaaaaa + status = "failed" + match conclusion: + case "success": + color = 0x00b32a + status = "succeeded" + case "failure" | "cancelled": + color = 0xff3b3b + status = "failed" if conclusion == "failure" else "cancelled" + case "timed_out" | "action_required" | "stale": + color = 0xe4a723 + match conclusion: + case "timed_out": status = "timed out" + case "action_required": status = "requires action" + case _: status = "stale" + case "neutral": + status = "didn't run" + case "skipped": + status = "was skipped" + + fields = [ + Field(name='Action Name', value = check_run["name"]) + ] + + if "title" in output: + fields.append(Field(name="Output Title", value=output["title"])) + + if "summary" in output: + fields.append(Field(name="Output Summary", value=output["summary"])) + + return EmbedBody( + f"[{repository["full_name"]}] Actions check {status} on {target}", + html_url, + sender, + color, + None, + None, + None + ) + +commit_comment = router.by_action('commit_comment') + +@commit_comment('created') +def commit_comment_created(env: BoundEnv, sender, comment, repository): + if env.ignored_user(sender["login"]): + return None + + return EmbedBody( + f"[{repository["full_name"]}] New comment on commit `{short_commit(comment["commit_id"])}`", + comment["html_url"], + sender, + 0x000001, + comment["body"] + ) + + +@router.handler('create') +def create_branch(env: BoundEnv, ref, ref_type, repository, sender): + if env.ignored_user(sender["login"]): + return None + + if ref_type == "branch" and env.ignored_branch(ref): + return None + + return EmbedBody( + f"[{repository["full_name"]}] New {ref_type} created: {ref}", + None, + sender, + 0x000001 + ) + + +@router.handler('delete') +def delete_branch(env: BoundEnv, ref, ref_type, repository, sender): + if ref_type == "branch" and env.ignored_branch(ref): + return None + + return EmbedBody( + f"[{repository["full_name"]}] {ref_type} deleted: {ref}", + None, + sender, + 0x000001 + ) + + +discussion_action = router.by_action('discussion') + + +@discussion_action('created') +def discussion_created(env: BoundEnv, discussion, repository, sender): + if env.ignored_user(sender.login): + return None + + return EmbedBody( + f"[{repository["full_name"]}] New discussion: #{discussion["number"]} {discussion["title"]}", + discussion["html_url"], + sender, + 0x9494ff, + discussion["body"], + f"Discussion Category: {discussion["category"]["name"]}" + ) + + +discussion_comment_action = router.by_action('discussion_comment') + + +@discussion_comment_action('created') +def discussion_comment_created(env: BoundEnv, discussion, comment, repository, sender): + if env.ignored_user(sender["login"]): + return None + + return EmbedBody( + f"[{repository["full_name"]}] New comment on discussion: #{discussion["number"]} {discussion["title"]}", + comment["html_url"], + sender, + 0x008a76, + comment.body, + f"Discussion Category: {discussion["category"]["name"]}" + ) + + +@router.handler("fork") +def fork(sender, repository, forkee): + return EmbedBody( + f"[{repository["full_name"]}] Fork Created: {forkee["full_name"]}", + forkee["html_url"], + sender, + 0xfcb900 + ) + +issue_comment_action = router.by_action('issue_comment') + +@issue_comment_action('created') +def issue_comment_created(env: BoundEnv, issue, comment, repository, sender): + if env.ignored_user(sender["login"]): + return None + + entity = "pull request" if "pull_request" in issue else "issue" + return EmbedBody( + f"[{repository["full_name"]}] New comment on {entity}: #{issue["number"]} {issue["title"]}", + comment["html_url"], + sender, + 0xad8b00, + comment["body"] + ) + + +issues_action = router.by_action('issues') + + +@issues_action('opened') +def issues_opened(env: BoundEnv, issue, repository, sender): + if env.ignored_user(sender["login"]): + return None + + return EmbedBody( + f"[{repository["full_name"]}] Issue opened: #{issue["number"]} {issue["title"]}", + issue["html_url"], + sender, + 0xff7d00, + issue["body"] + ) + + +@issues_action('reopened') +def issues_reopened(issue, repository, sender): + return EmbedBody( + f"[{repository["full_name"]}] Issue reopened: #{issue["number"]} {issue["title"]}", + issue["html_url"], + sender, + 0xff7d00 + ) + + +@issues_action('closed') +def issues_closed(issue, repository, sender): + return EmbedBody( + f"[{repository["full_name"]}] Issue closed: #{issue["number"]} {issue["title"]}", + issue["html_url"], + sender, + 0xff482f + ) + + +package_action = router.by_action('package') + + +@package_action('published') +def package_published(sender, repository, package=None, registry_package=None): + pkg = package if package else registry_package + + return EmbedBody( + f"[{repository["full_name"]}] Package Published: {pkg["namespace"]}/{pkg["name"]}", + pkg["package_version"]["html_url"], + sender, + 0x009202 + ) + + +@package_action('updated') +def package_updated(sender, repository, package=None, registry_package=None): + pkg = package if package else registry_package + + return EmbedBody( + f"[{repository["full_name"]}] Package Updated: {pkg["namespace"]}/{pkg["name"]}", + pkg["package_version"]["html_url"], + sender, + 0x9202 + ) + + +pull_request_action = router.by_action('pull_request') + + +@pull_request_action('opened') +def pull_request_opened(env: BoundEnv, pull_request, repository, sender): + if env.ignored_user(sender["login"]): + return None + + draft = pull_request["draft"] + color = 0xa7a7a7 if draft else 0x009202 + pr_type = "Draft pull request" if draft else "Pull request" + + return EmbedBody( + f"[{repository["full_name"]}] {pr_type} opened: #{pull_request["number"]} {pull_request["title"]}", + pull_request["html_url"], + sender, + color + ) + +@pull_request_action('closed') +def pull_request_closed(pull_request, repository, sender): + merged = pull_request["merged"] + color = 0x8748ff if merged else 0xff293a + status = "merged" if merged else "closed" + + return EmbedBody( + f"[{repository["full_name"]}] Pull request {status}: #{pull_request["number"]} {pull_request["title"]}", + pull_request["html_url"], + sender, + color + ) + +@pull_request_action('reopened') +def pull_request_reopened(env: BoundEnv, pull_request, repository, sender): + if env.ignored_user(sender["login"]): + return None + + draft = pull_request["draft"] + color = 0xa7a7a7 if draft else 0x009202 + pr_type = "Draft pull request" if draft else "Pull request" + + return EmbedBody( + f"[{repository["full_name"]}] {pr_type} reopened: #{pull_request["number"]} {pull_request["title"]}", + pull_request["html_url"], + sender, + color + ) + +@pull_request_action('converted_to_draft') +def pull_request_converted_to_draft(pull_request, repository, sender): + return EmbedBody( + f"[{repository["full_name"]}] Pull request marked as draft: #{pull_request["number"]} {pull_request["title"]}", + pull_request["html_url"], + sender, + 0xa7a7a7 + ) + +@pull_request_action('ready_for_review') +def pull_request_ready_for_review(pull_request, repository, sender): + return EmbedBody( + f"[{repository["full_name"]}] Pull request marked for review: #{pull_request["number"]} {pull_request["title"]}", + pull_request["html_url"], + sender, + 0x009202 + ) + +pull_request_review_action = router.by_action('pull_request_review') + +@pull_request_review_action('submitted') +@pull_request_review_action('dismissed') +def pull_request_review(pull_request, review, repository, action, sender): + state = "reviewed" + color = 7829367 + + match review["state"]: + case "approved": + state = "approved" + color = 37378 + case "changes_requested": + state = "changes requested" + color = 16722234 + case _: + if action == "dismissed": + state = "review dismissed" + + return EmbedBody( + f"[{repository["full_name"]}] Pull request {state}: #{pull_request["number"]} {pull_request["title"]}", + review["html_url"], + sender, + color, + review["body"] + ) + +pull_request_review_comment_action = router.by_action('pull_request_review_comment') + + +@pull_request_review_comment_action('created') +def pull_request_review_comment_created(pull_request, comment, repository, sender): + return EmbedBody( + f"[{repository["full_name"]}] Pull request review comment: #{pull_request["number"]} {pull_request["title"]}", + comment["html_url"], + sender, + 0x777777, + comment["body"] + ) + +@router.handler('push') +def push(env: BoundEnv, commits, forced, after, repository, ref, compare, sender): + branch = ref[11:] + + if env.ignored_branch(branch): + return None + if env.ignored_user(sender["login"]): + return None + + if forced: + return EmbedBody( + f"[{repository["full_name"]}] Branch {branch} was force-pushed to `{short_commit(after)}`", + compare.replace("...", ".."), + sender, + 0xff293a + ) + + amount = len(commits) + if amount == 0: + return None + + description = "" + last_commit_url = "" + for commit in commits: + commit_url = commit["url"] + line = f"[`{short_commit(commit["id"])}`]({commit_url}) {truncate(commit["message"].split("\n")[0], 50)} - {commit["author"]["username"]}\n" + if (len(description) + len(line)) >= 1500: + break + + last_commit_url = commit_url + description += line + + commit_word = "commit" if amount == 1 else "commits" + + return EmbedBody( + f"[{repository["name"]}:{branch}] {amount} new {commit_word}", + last_commit_url if amount == 1 else compare, + sender, + 0x5d62e4, + description + ) + +release_action = router.by_action('release') + +@release_action('released') +@release_action('prereleased') +def release_released(release, repository, sender): + if release["draft"]: + return None + + effective_name = release.get("name", None) + if not effective_name: + effective_name = release["tag_name"] + + return EmbedBody( + f"[{repository['full_name']}] New {'pre' if release["prerelease"] else ''}release published: {effective_name}", + release["html_url"], + sender, + 0xde5de4, + release["body"] + ) + +star_action = router.by_action('star') + +@star_action('created') +def star_created(sender, repository): + return EmbedBody( + f"[{repository["full_name"]}] New star added", + repository["html_url"], + sender, + 0xfcb900 + ) + +deployment_action = router.by_action('deployment') + +@deployment_action('created') +def deployment_created(deployment, repository, sender): + web_url = deployment["payload"].get("web_url") + if not web_url: + web_url = "" + + return EmbedBody( + f"[{repository["full_name"]}] Deployment started for {deployment["description"]}", + web_url, + sender, + 0xaa44b9 + ) + +@router.handler('deployment_status') +def deployment_status(deployment, deployment_status, repository, sender): + web_url = deployment["payload"].get("web_url") + if not web_url: + web_url = "" + + color = 0xff3b3b + term = "succeeded" + match deployment_status["state"]: + case "success": + color = 0x00b32a + case "failure": + term = "failed" + case "error": + term = "errored" + case _: + return None + + return EmbedBody( + f"[{repository["full_name"]}] Deployment for {deployment["description"]} {term}", + web_url, + sender, + color + ) + +@router.handler("gollum") +def gollum(pages, sender, repository): + # Pages is always an array with several "actions". + # Count the amount of "created" and "edited" actions and store the amount in a variable. + # Also store the titles of the pages in an array since we will need them later. + created = 0 + edited = 0 + titles: list[str] = [] + for page in pages: + action = page["action"] + if action == "created": + created += 1 + elif action == "edited": + edited += 1 + + # Wrap the title in a markdown with the link to the page. + title = f"[{page["title"]}](${page["html_url"]})" + + # Capitalize the first letter of the action, then prepend it to the title. + titles.insert(0, f"{action[0].upper() + action[1:]}: {title}") + + # Set the message based on if there are any created or edited pages. + # If there are only 1 of one type, set the message to singular. + # If there are multiple of one type, set the message to plural. + message = "" + color = 6120164 + match (created, edited): + case (0, 0): + # If there are no pages, return null. + return None + case (1, 0): + message = "A page was created" + # Set the color to green. + color = 0x00b32a + case (0, 1): + message = "A page was edited" + # Set the color to orange. + color = 0xfcb900 + case (a, b) if a > 0 and b > 0: + message = f"{created} page{"s" if created > 1 else ""} were created and {edited} {"were" if edited > 1 else "was"} edited" + case _: + message = f"{max(created, edited)} pages were {"created" if created > 0 else "edited"}" + + # Prepend the repository title to the message. + message = f"[{repository["full_name"]}] {message}" + + # Build the embed, with the sender as the author, the message as the title, and the edited pages as the description. + return EmbedBody( + message, + repository["html_url"], + sender, + color, + "\n".join(titles), + ) diff --git a/src/pydisgit/util.py b/src/pydisgit/util.py new file mode 100644 index 0000000..a2c1c59 --- /dev/null +++ b/src/pydisgit/util.py @@ -0,0 +1,32 @@ +from dataclasses import dataclass +from hmac import HMAC +import re +from typing import NamedTuple, Optional + +__NEWLINE_REGEXP = re.compile(r"[\n|\r]*") + + +def truncate(text: str, num: int) -> Optional[str]: + if not text: + return None + + text = __NEWLINE_REGEXP.sub("", text) + if len(text) <= num: + return text + + return text[0:num - 3] + "..." + + +def short_commit(hash: str) -> str: + return hash[0:7] + + +# make into middleware +async def validate_request(request, secret: str) -> bool: + pass +# signature_header = request.headers.get("X-Hub-Signature-256")?.substring("sha256=".length); +# +# if not signature_header: return False +# const hmac = createHmac("sha256", secret); +# hmac.update(await request.bytes()); +# return signatureHeader == hmac.digest('hex'); diff --git a/src/pydisgit/webhook.py b/src/pydisgit/webhook.py new file mode 100644 index 0000000..c32681a --- /dev/null +++ b/src/pydisgit/webhook.py @@ -0,0 +1,175 @@ +""" +Core logic for webhook handling +""" + +from collections.abc import Callable +from dataclasses import dataclass, field +from logging import Logger +from typing import Any, Optional, NamedTuple +import inspect + +from .conf import BoundEnv +from .util import truncate + + +class Sender(NamedTuple): + """ + GH API Sender representation + """ + login: str + html_url: str + avatar_url: str + + @classmethod + def from_json(cls, data: Any): + return cls(data["login"], data["html_url"], data["avatar_url"]) + +class Field(NamedTuple): + """ + Discord API field representation + """ + name: str + value: str + inline: bool = True + + def to_json(self) -> Any: + """ + Return a JSON representation of this field for sending to discord + """ + return { + "name": self.name, + "value": truncate(self.value, 1000), + "inline": self.inline + } + +@dataclass +class EmbedBody: + """ + Discord API embed representation + """ + title: str + url: Optional[str] + sender: Sender + color: int + description: Optional[str] = None + footer: Optional[str] = None + fields: list[Field] = field(default_factory=lambda: []) + + def __post_init__(self): + if not isinstance(self.sender, Sender): + self.sender = Sender.from_json(self.sender) + + def to_json(self) -> Any: + return { + "embeds": [ + { + "title": truncate(self.title, 255), + "url": self.url, + "description": truncate(self.description, 1000) if self.description else None, + "author": { + "name": truncate(self.sender.login, 255), + "url": self.sender.html_url, + "icon_url": self.sender.avatar_url + }, + "color": self.color, + "footer": { + "text": truncate(self.footer, 255), + } if self.footer else None, + "fields": [f.to_json() for f in self.fields], + } + ] + } + + +type EventHandler = Callable[[BoundEnv, dict], Optional[EmbedBody]] + +class BoundRouter: + + def __init__(self, handlers: dict[str, EventHandler], env: BoundEnv, logger: Logger): + self._handlers = handlers + self._env = env + self._logger = logger + + def process_request(self, gh_hook_type: str, gh_data: dict) -> Optional[Any]: + """ + Process the request based on the hook types + """ + if self._env.ignored_payload(gh_hook_type): + self._logger.info("Ignoring payload type %s", gh_hook_type) + return None + + if gh_hook_type not in self._handlers: + self._logger.debug("No handler for %s", gh_hook_type) + return None + + result = self._handlers[gh_hook_type](self._env, gh_data) + if not result: + self._logger.debug("Produced no result for event type '%s' with payload '%s", gh_hook_type, gh_data) + return None + + return result.to_json() + + +class WebhookRouter(): + __handlers: dict[str, EventHandler] = {} + + def bind(self, env: BoundEnv, logger: Logger) -> BoundRouter: + return BoundRouter(self.__handlers, env, logger) + + def _wrap_func(self, func): + def result(env, data): + sig = inspect.signature(func) + final_data = dict(data) + # if we don't have a kwargs field, remove any extra attributes from the args map + if len([v for v in sig.parameters.values() if v.kind == inspect.Parameter.VAR_KEYWORD]) == 0: + for k in data.keys(): + if k not in sig.parameters.keys(): + del final_data[k] + + # if there's an env parameter, inject our environment state + env_param = sig.parameters.get("env", None) + if env_param and env_param.annotation == BoundEnv: + final_data["env"] = env + + # then call the actual handler + return func(**final_data) + return result + + def handler(self, event: str) -> Callable: + """ + Decorator, function plus event name + """ + def decorator(func): + if event in self.__handlers: + raise f"Already registered a handler for {event}!" + + self.__handlers[event] = self._wrap_func(func) + return func + return decorator + + def by_action(self, event: str) -> Callable[[str], Callable[[EventHandler], EventHandler]]: + """ + Return a value that can be used as a decorator to dispatch handlers + for ``event`` based on the provided action. + """ + + dispatchers: dict[str, EventHandler] = {} + + def subhandler(env, data) -> Optional[EmbedBody]: + action = data.get("action", None) + if action not in dispatchers: + return None + return dispatchers[action](env, data) + + def decorator_wrap(action: str) -> Callable[[EventHandler], EventHandler]: + def decorator(func: EventHandler) -> EventHandler: + if action in dispatchers: + raise f"Already registered a subhandler for {action} (in {event}!" + + dispatchers[action] = self._wrap_func(func) + return func + return decorator + + self.__handlers[event] = subhandler + + return decorator_wrap