diff --git a/.github/workflows/black.yaml b/.github/workflows/black.yaml deleted file mode 100644 index 3d0810e..0000000 --- a/.github/workflows/black.yaml +++ /dev/null @@ -1,27 +0,0 @@ -name: Black - -on: - push: - branches: [ master, stable ] - pull_request: - branches: [ master, stable ] - -jobs: - black: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - - name: Set up Python - uses: actions/setup-python@v2 - with: - python-version: 3.8 - - - name: Install dependencies - run: | - pip install --upgrade pip - pip install black - - - name: Black check - run: | - black --check butterrobot diff --git a/.github/workflows/docker-build-latest.yaml b/.github/workflows/docker-build-latest.yaml deleted file mode 100644 index de0b1e9..0000000 --- a/.github/workflows/docker-build-latest.yaml +++ /dev/null @@ -1,21 +0,0 @@ -name: Build latest tag docker image - -on: - push: - branches: - - master - -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - - name: Build the Docker image - run: docker build --tag butterrobot:$(git rev-parse --short HEAD) -f Dockerfile.dev . - - - name: Push into Github packages (latest) - run: | - echo "${{ secrets.GITHUB_TOKEN }}" | docker login docker.pkg.github.com -u fmartingr --password-stdin - docker tag butterrobot:$(git rev-parse --short HEAD) docker.pkg.github.com/fmartingr/butterrobot/butterrobot:latest - docker push docker.pkg.github.com/fmartingr/butterrobot/butterrobot:latest diff --git a/.github/workflows/pytest.yaml b/.github/workflows/pytest.yaml deleted file mode 100644 index 8db9c98..0000000 --- a/.github/workflows/pytest.yaml +++ /dev/null @@ -1,32 +0,0 @@ -name: Pytest - -on: - push: - branches: [ master, stable ] - pull_request: - branches: [ master, stable ] - -jobs: - pytest: - runs-on: ubuntu-latest - strategy: - matrix: - python-version: [3.8] - - steps: - - uses: actions/checkout@v2 - - - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v2 - with: - python-version: ${{ matrix.python-version }} - - - name: Install dependencies - run: | - pip install --upgrade pip poetry - poetry install - - - name: Test with pytest - run: | - ls - poetry run pytest --cov=butterrobot --cov=butterrobot_plugins_contrib diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml deleted file mode 100644 index 00984ea..0000000 --- a/.github/workflows/release.yaml +++ /dev/null @@ -1,47 +0,0 @@ -name: Release - -on: - push: - branches: - - stable - -jobs: - prepare: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - publish: - runs-on: ubuntu-latest - needs: - - prepare - steps: - - name: Set up Python 3.8 - uses: actions/setup-python@v1 - with: - python-version: 3.8 - - - name: Install poetry - run: | - pip install poetry - - - name: Build and publish - run: | - poetry publish -u ${{ secrets.PYPI_USERNAME }} -p ${{ secrets.PYPI_PASSWORD }} --build - - build: - runs-on: ubuntu-latest - needs: - - prepare - - publish - steps: - - name: Build the Docker image - run: docker build --tag butterrobot:$(git rev-parse --short HEAD) docker - - - name: Push into Github packages (stable) - run: | - echo "${{ secrets.GITHUB_TOKEN }}" | docker login docker.pkg.github.com -u fmartingr --password-stdin - docker tag butterrobot:$(git rev-parse --short HEAD) docker.pkg.github.com/fmartingr/butterrobot/butterrobot:stable - docker tag butterrobot:$(git rev-parse --short HEAD) docker.pkg.github.com/fmartingr/butterrobot/butterrobot:$(cat pyproject.toml | grep version | cut -d "\"" -f 2) - docker push docker.pkg.github.com/fmartingr/butterrobot/butterrobot:stable - docker push docker.pkg.github.com/fmartingr/butterrobot/butterrobot:$(cat pyproject.toml | grep version | cut -d "\"" -f 2) diff --git a/.gitignore b/.gitignore index 309685e..d964ffb 100644 --- a/.gitignore +++ b/.gitignore @@ -4,16 +4,10 @@ __pycache__ *~ *.cert .env-local -test.py .coverage -# Distribution dist -*.egg-info -pip-wheel-metadata - -# Github Codespaces -pythonenv3.8 - +bin # Butterrobot *.sqlite* +butterrobot.db diff --git a/.goreleaser.yml b/.goreleaser.yml new file mode 100644 index 0000000..68d1f62 --- /dev/null +++ b/.goreleaser.yml @@ -0,0 +1,150 @@ +version: 2 + +gitea_urls: + api: https://git.nakama.town/api/v1 + download: https://git.nakama.town + +before: + hooks: + - go mod tidy + +git: + ignore_tags: + - "{{ if not .IsNightly }}*-rc*{{ end }}" + +builds: + - binary: butterrobot + main: ./cmd/butterrobot + env: + - CGO_ENABLED=0 + - GIN_MODE=release + tags: + - netgo + - osusergo + goos: + - linux + - windows + - darwin + goarch: + - amd64 + - arm + - arm64 + goarm: + - "7" + ignore: + - goos: darwin + goarch: arm + - goos: windows + goarch: arm + - goos: windows + goarch: arm64 + +archives: + - id: butterrobot + name_template: >- + {{ .ProjectName }}_ + {{- if eq .Os "darwin" }}Darwin{{- else if eq .Os "linux" }}Linux{{- else if eq .Os "windows" }}Windows{{- else }}{{ .Os }}{{ end }}_ + {{- if eq .Arch "amd64" }}x86_64{{- else if eq .Arch "arm64" }}aarch64{{- else }}{{ .Arch }}{{ end }}_{{ .Version }} + format_overrides: + - goos: windows + format: zip + +dockers: +- image_templates: + - &amd64_image "git.nakama.town/fmartingr/butterrobot:{{ .Version }}-amd64" + use: buildx + dockerfile: &dockerfile Containerfile + goos: linux + goarch: amd64 + build_flag_templates: + - "--pull" + - "--platform=linux/amd64" +- image_templates: + - &arm64_image "git.nakama.town/fmartingr/butterrobot:{{ .Version }}-arm64" + use: buildx + dockerfile: *dockerfile + goos: linux + goarch: arm64 + build_flag_templates: + - "--pull" + - "--platform=linux/arm64" +- image_templates: + - &armv7_image "git.nakama.town/fmartingr/butterrobot:{{ .Version }}-armv7" + use: buildx + dockerfile: *dockerfile + goos: linux + goarch: arm + goarm: "7" + build_flag_templates: + - "--pull" + - "--platform=linux/arm/v7" + +docker_manifests: + - name_template: "git.nakama.town/fmartingr/butterrobot:{{ .Version }}" + image_templates: + - *amd64_image + - *arm64_image + - *armv7_image + # - name_template: "git.nakama.town/fmartingr/butterrobot:latest" + # image_templates: + # - *amd64_image + # - *arm64_image + # - *armv7_image + +nfpms: + - maintainer: Felipe Martin + description: SMTP server to forward messages to shoutrrr endpoints + homepage: https://git.nakama.town/fmartingr/butterrobot + license: AGPL-3.0 + formats: + - deb + - rpm + - apk + +upx: + - enabled: true + ids: + - butterrobot + goos: [linux, darwin] + goarch: [amd64, arm, arm64] + goarm: ["7"] + +checksum: + name_template: 'checksums.txt' + +snapshot: + version_template: "{{ incpatch .Version }}-next" + +changelog: + sort: asc + groups: + - title: Features + regexp: '^.*?feat(\([[:word:]]+\))??!?:.+$' + order: 0 + - title: "Fixes" + regexp: '^.*?fix(\([[:word:]]+\))??!?:.+$' + order: 1 + - title: "Performance" + regexp: '^.*?perf(\([[:word:]]+\))??!?:.+$' + order: 2 + - title: API + regexp: '^.*?api(\([[:word:]]+\))??!?:.+$' + order: 3 + - title: Documentation + regexp: '^.*?docs(\([[:word:]]+\))??!?:.+$' + order: 4 + - title: "Tests" + regexp: '^.*?test(\([[:word:]]+\))??!?:.+$' + order: 5 + - title: CI and Delivery + regexp: '^.*?ci(\([[:word:]]+\))??!?:.+$' + order: 6 + - title: Others + order: 999 + filters: + exclude: + - "^deps:" + - "^chore\\(deps\\):" + +release: + prerelease: auto diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml deleted file mode 100644 index 621aa22..0000000 --- a/.pre-commit-config.yaml +++ /dev/null @@ -1,22 +0,0 @@ -repos: -- repo: https://github.com/pre-commit/pre-commit-hooks - rev: v2.2.3 - hooks: - - id: trailing-whitespace - - id: end-of-file-fixer - - id: flake8 - -- repo: https://github.com/asottile/seed-isort-config - rev: v1.9.2 - hooks: - - id: seed-isort-config -- repo: https://github.com/pre-commit/mirrors-isort - rev: v4.3.20 - hooks: - - id: isort - -- repo: https://github.com/ambv/black - rev: stable - hooks: - - id: black - language_version: python3 diff --git a/.woodpecker/ci.yml b/.woodpecker/ci.yml new file mode 100644 index 0000000..4353088 --- /dev/null +++ b/.woodpecker/ci.yml @@ -0,0 +1,23 @@ +when: + event: + - push + - pull_request + branch: + - main + +steps: + format: + image: golang:1.24 + commands: + - make format + - git diff --exit-code # Fail if files were changed + + lint: + image: golang:1.24 + commands: + - make ci-lint + + test: + image: golang:1.24 + commands: + - make test diff --git a/.woodpecker/release.yml b/.woodpecker/release.yml new file mode 100644 index 0000000..b24eb15 --- /dev/null +++ b/.woodpecker/release.yml @@ -0,0 +1,16 @@ +when: + - event: tag + branch: main + +steps: + - name: Release + image: goreleaser/goreleaser:latest + environment: + GITEA_TOKEN: + from_secret: GITEA_TOKEN + DOCKER_HOST: unix:///var/run/docker.sock + volumes: + - "/var/run/docker.sock:/var/run/docker.sock" + commands: + - docker login -u fmartingr -p $GITEA_TOKEN git.nakama.town + - goreleaser release --clean diff --git a/Containerfile b/Containerfile new file mode 100644 index 0000000..6a9ff7d --- /dev/null +++ b/Containerfile @@ -0,0 +1,6 @@ +# This file is used directly by the goreleaser build +# It is used to build the final container image +FROM scratch +WORKDIR / +COPY /butterrobot /usr/bin/butterrobot +ENTRYPOINT ["/usr/bin/butterrobot"] diff --git a/Dockerfile.dev b/Dockerfile.dev deleted file mode 100644 index c1a4a16..0000000 --- a/Dockerfile.dev +++ /dev/null @@ -1,26 +0,0 @@ -FROM docker.io/library/alpine:3.11 - -ENV PYTHON_VERSION=3.8.2-r1 -ENV APP_PORT 8080 -ENV BUILD_DIR /tmp/build -ENV APP_PATH /etc/butterrobot - -WORKDIR ${BUILD_DIR} -COPY README.md ${BUILD_DIR}/README.md -COPY poetry.lock ${BUILD_DIR}/poetry.lock -COPY pyproject.toml ${BUILD_DIR}/pyproject.toml -COPY ./butterrobot_plugins_contrib ${BUILD_DIR}/butterrobot_plugins_contrib -COPY ./butterrobot ${BUILD_DIR}/butterrobot -RUN apk --update add curl python3-dev==${PYTHON_VERSION} gcc musl-dev libffi-dev openssl-dev && \ - pip3 install poetry && \ - poetry build && \ - pip3 install ${BUILD_DIR}/dist/butterrobot-*.tar.gz && \ - rm -rf ${BUILD_DIR} && \ - mkdir ${APP_PATH} && \ - chown -R 1000:1000 ${APP_PATH} - -USER 1000 -WORKDIR ${APP_PATH} -COPY ./docker/bin/start-server.sh /usr/local/bin/start-server - -CMD ["/usr/local/bin/start-server"] diff --git a/Makefile b/Makefile index 2791e1c..ff08163 100644 --- a/Makefile +++ b/Makefile @@ -1,27 +1,100 @@ -# Local development -setup: - poetry install +PROJECT_NAME := butterrobot -podman@build: - podman build -t fmartingr/butterrobot -f docker/Dockerfile docker +SOURCE_FILES ?=./... -podman@build-dev: - podman build -t fmartingr/butterrobot:dev -f Dockerfile.dev . +TEST_OPTIONS ?= -v -failfast -race -bench=. -benchtime=100000x -cover -coverprofile=coverage.out +TEST_TIMEOUT ?=1m -podman@tag-dev: - podman tag fmartingr/butterrobot:dev registry.int.fmartingr.network/fmartingr/butterrobot:dev +GOLANGCI_LINT_VERSION ?= v1.64.5 -podman@push-dev: - podman push registry.int.fmartingr.network/fmartingr/butterrobot:dev --tls-verify=false +CLEAN_OPTIONS ?=-modcache -testcache -podman@dev: - make podman@build-dev - make podman@tag-dev - make podman@push-dev +CGO_ENABLED := 0 -test: - poetry run pytest --cov=butterrobot --cov=butterrobot_plugins_contrib +BUILDS_PATH := ./dist +FROM_MAKEFILE := y -clean: - rm -rf dist - rm -rf butterrobot.egg-info +CONTAINERFILE_NAME := Containerfile +CONTAINER_ALPINE_VERSION := 3.21 +CONTAINER_SOURCE_URL := "https://git.nakama.town/fmartingr/${PROJECT_NAME}" +CONTAINER_MAINTAINER := "Felipe Martin " +CONTAINER_BIN_NAME := ${PROJECT_NAME} + +BUILDX_PLATFORMS := linux/amd64,linux/arm64,linux/arm/v7 + +export PROJECT_NAME +export FROM_MAKEFILE + +export CGO_ENABLED + +export SOURCE_FILES +export TEST_OPTIONS +export TEST_TIMEOUT +export BUILDS_PATH + +export CONTAINERFILE_NAME +export CONTAINER_ALPINE_VERSION +export CONTAINER_SOURCE_URL +export CONTAINER_MAINTAINER +export CONTAINER_BIN_NAME + +export BUILDX_PLATFORMS + +.PHONY: all +all: help + +# this is godly +# https://news.ycombinator.com/item?id=11939200 +.PHONY: help +help: ### this screen. Keep it first target to be default +ifeq ($(UNAME), Linux) + @grep -P '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | \ + awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}' +else + @# this is not tested, but prepared in advance for you, Mac drivers + @awk -F ':.*###' '$$0 ~ FS {printf "%15s%s\n", $$1 ":", $$2}' \ + $(MAKEFILE_LIST) | grep -v '@awk' | sort +endif + +.PHONY: clean +clean: ### clean test cache, build files + $(info: Make: Clean) + @rm -rf ${BUILDS_PATH} + @go clean ${CLEAN_OPTIONS} + @-docker buildx rm ${PROJECT_NAME}_builder + +.PHONY: build +build: clean ### builds the project for the setup os/arch combinations + $(info: Make: Build) + @goreleaser --clean --snapshot + +.PHONY: quick-run +quick-run: ### Executes the project using golang + CGO_ENABLED=${CGO_ENABLED} go run ./cmd/${PROJECT_NAME}/*.go + +.PHONY: run +run: ### Executes the project build locally + @make build + ${BUILDS_PATH}/${PROJECT_NAME} + +.PHONY: format +format: ### Executes the formatting pipeline on the project + $(info: Make: Format) + @go fmt ./... + @go mod tidy + +.PHONY: ci-lint +ci-lint: ### Check the project for errors + $(info: Make: Lint) + @go install github.com/golangci/golangci-lint/cmd/golangci-lint@${GOLANGCI_LINT_VERSION} + @golangci-lint run ./... + +.PHONY: lint +lint: ### Check the project for errors + $(info: Make: Lint) + @golangci-lint run ./... + +.PHONY: test +test: ### Runs the test suite + $(info: Make: Test) + CGO_ENABLED=1 go test ${TEST_OPTIONS} -timeout=${TEST_TIMEOUT} ${SOURCE_FILES} diff --git a/README.md b/README.md index 7fb78d6..36ec708 100644 --- a/README.md +++ b/README.md @@ -2,52 +2,78 @@ | Stable | Master | | --- | --- | -| ![Build stable tag docker image](https://github.com/fmartingr/butterrobot/workflows/Build%20stable%20tag%20docker%20image/badge.svg?branch=stable) | ![Build latest tag docker image](https://github.com/fmartingr/butterrobot/workflows/Build%20latest%20tag%20docker%20image/badge.svg?branch=master) | -| ![Pytest](https://github.com/fmartingr/butterrobot/workflows/Pytest/badge.svg?branch=stable) | ![Pytest](https://github.com/fmartingr/butterrobot/workflows/Pytest/badge.svg?branch=master) | +| ![Build stable tag docker image](https://git.nakama.town/fmartingr/butterrobot/workflows/Build%20stable%20tag%20docker%20image/badge.svg?branch=stable) | ![Build latest tag docker image](https://git.nakama.town/fmartingr/butterrobot/workflows/Build%20latest%20tag%20docker%20image/badge.svg?branch=master) | +| ![Test](https://git.nakama.town/fmartingr/butterrobot/workflows/Test/badge.svg?branch=stable) | ![Test](https://git.nakama.town/fmartingr/butterrobot/workflows/Test/badge.svg?branch=master) | -Python framework to create bots for several platforms. +Go framework to create bots for several platforms. ![Butter Robot](./assets/icon@120.png) > What is my purpose? +## Features + +- Support for multiple chat platforms (Slack, Telegram) +- Plugin system for easy extension +- Admin interface for managing channels and plugins +- Message queue for asynchronous processing + ## Documentation [Go to documentation](./docs) ## Installation -### PyPi +### From Source -You can run it directly by installing the package and calling it -with `python` though this is not recommended and only intended for -development purposes. +```bash +# Clone the repository +git clone https://git.nakama.town/fmartingr/butterrobot.git +cd butterrobot -``` -$ pip install --user butterrobot -$ python -m butterrobot +# Build the application +go build -o butterrobot ./cmd/butterrobot ``` ### Containers -The `fmartingr/butterrobot/butterrobot` container image is published on Github packages to use with your favourite tool: +The `fmartingr/butterrobot/butterrobot` container image is published on Github packages: +```bash +docker pull docker.pkg.git.nakama.town/fmartingr/butterrobot/butterrobot:latest +docker run -d --name butterrobot -p 8080:8080 docker.pkg.git.nakama.town/fmartingr/butterrobot/butterrobot:latest ``` -docker pull docker.pkg.github.com/fmartingr/butterrobot/butterrobot:latest -podman run -d --name fmartingr/butterrobot/butterrobot -p 8080:8080 -``` + +## Configuration + +Configuration is done through environment variables: + +- `DEBUG`: Set to "y" to enable debug mode +- `BUTTERROBOT_HOSTNAME`: Hostname for webhook URLs +- `LOG_LEVEL`: Logging level (DEBUG, INFO, WARN, ERROR) +- `SECRET_KEY`: Secret key for sessions and password hashing +- `DATABASE_PATH`: Path to SQLite database file + +### Platform-specific configuration + +#### Slack + +- `SLACK_TOKEN`: Slack app access token +- `SLACK_BOT_OAUTH_ACCESS_TOKEN`: Slack bot OAuth access token + +#### Telegram + +- `TELEGRAM_TOKEN`: Telegram bot token ## Contributing -To run the project locally you will need [poetry](https://python-poetry.org/). - -``` +```bash git clone git@github.com:fmartingr/butterrobot.git cd butterrobot -poetry install +go mod download ``` -Create a `.env-local` file with the required environment variables, you have [an example file](.env-example). +Create a `.env-local` file with the required environment variables: ``` SLACK_TOKEN=xxx @@ -55,8 +81,12 @@ TELEGRAM_TOKEN=xxx ... ``` -And then you can run it directly with poetry +And then you can run it directly: +```bash +go run ./cmd/butterrobot/main.go ``` -docker run -it --rm --env-file .env-local -p 5000:5000 -v $PWD/butterrobot:/etc/app/butterrobot local/butterrobot python -m butterrobot -``` + +## License + +GPL-2.0 diff --git a/butterrobot/__init__.py b/butterrobot/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/butterrobot/__main__.py b/butterrobot/__main__.py deleted file mode 100644 index 2f0182a..0000000 --- a/butterrobot/__main__.py +++ /dev/null @@ -1,6 +0,0 @@ -from butterrobot.app import app -from butterrobot.config import DEBUG - -# Only used for local development! -# python -m butterrobot -app.run(debug=DEBUG, host="0.0.0.0") diff --git a/butterrobot/admin/__init__.py b/butterrobot/admin/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/butterrobot/admin/blueprint.py b/butterrobot/admin/blueprint.py deleted file mode 100644 index b9442fd..0000000 --- a/butterrobot/admin/blueprint.py +++ /dev/null @@ -1,156 +0,0 @@ -import os.path -from functools import wraps - -import structlog -from flask import ( - Blueprint, - g, - flash, - request, - session, - url_for, - redirect, - render_template, -) - -from butterrobot.db import UserQuery, ChannelQuery, ChannelPluginQuery -from butterrobot.plugins import get_available_plugins - -admin = Blueprint("admin", __name__, url_prefix="/admin") -admin.template_folder = os.path.join(os.path.dirname(__name__), "templates") -logger = structlog.get_logger(__name__) - - -def login_required(f): - @wraps(f) - def decorated_function(*args, **kwargs): - if g.user is None: - return redirect(url_for("admin.login_view", next=request.path)) - return f(*args, **kwargs) - - return decorated_function - - -@admin.before_app_request -def load_logged_in_user(): - user_id = session.get("user_id") - - if user_id is None: - g.user = None - else: - try: - user = UserQuery.get(id=user_id) - g.user = user - except UserQuery.NotFound: - g.user = None - - -@admin.route("/") -@login_required -def index_view(): - if not session.get("logged_in", False): - return redirect(url_for("admin.login_view")) - return redirect(url_for("admin.channel_list_view")) - - -@admin.route("/login", methods=["GET", "POST"]) -def login_view(): - error = None - if request.method == "POST": - user = UserQuery.check_credentials( - request.form["username"], request.form["password"] - ) - if not user: - flash("Incorrect credentials", category="danger") - else: - session["logged_in"] = True - session["user_id"] = user.id - flash("You were logged in", category="success") - _next = request.args.get("next", url_for("admin.index_view")) - return redirect(_next) - return render_template("login.j2", error=error) - - -@admin.route("/logout") -@login_required -def logout_view(): - session.clear() - flash("You were logged out", category="success") - return redirect(url_for("admin.index_view")) - - -@admin.route("/plugins") -@login_required -def plugin_list_view(): - return render_template("plugin_list.j2", plugins=get_available_plugins().values()) - - -@admin.route("/channels") -@login_required -def channel_list_view(): - return render_template("channel_list.j2", channels=ChannelQuery.all()) - - -@admin.route("/channels/", methods=["GET", "POST"]) -@login_required -def channel_detail_view(channel_id): - if request.method == "POST": - ChannelQuery.update( - channel_id, - enabled=request.form["enabled"] == "true", - ) - flash("Channel updated", "success") - - channel = ChannelQuery.get(channel_id) - return render_template( - "channel_detail.j2", channel=channel, plugins=get_available_plugins() - ) - - -@admin.route("/channel//delete", methods=["POST"]) -@login_required -def channel_delete_view(channel_id): - ChannelQuery.delete(channel_id) - flash("Channel removed", category="success") - return redirect(url_for("admin.channel_list_view")) - - -@admin.route("/channelplugins", methods=["GET", "POST"]) -@login_required -def channel_plugin_list_view(): - if request.method == "POST": - data = request.form - try: - ChannelPluginQuery.create( - data["channel_id"], data["plugin_id"], enabled=data["enabled"] == "y" - ) - flash(f"Plugin {data['plugin_id']} added to the channel", "success") - except ChannelPluginQuery.Duplicated: - flash( - f"Plugin {data['plugin_id']} is already present on the channel", "error" - ) - return redirect(request.headers.get("Referer")) - - channel_plugins = ChannelPluginQuery.all() - return render_template("channel_plugins_list.j2", channel_plugins=channel_plugins) - - -@admin.route("/channelplugins/", methods=["GET", "POST"]) -@login_required -def channel_plugin_detail_view(channel_plugin_id): - if request.method == "POST": - ChannelPluginQuery.update( - channel_plugin_id, - enabled=request.form["enabled"] == "true", - ) - flash("Plugin updated", category="success") - - return redirect(request.headers.get("Referer")) - - -@admin.route("/channelplugins//delete", methods=["POST"]) -@login_required -def channel_plugin_delete_view(channel_plugin_id): - ChannelPluginQuery.delete(channel_plugin_id) - flash("Plugin removed", category="success") - return redirect(request.headers.get("Referer")) diff --git a/butterrobot/admin/templates/channel_detail.j2 b/butterrobot/admin/templates/channel_detail.j2 deleted file mode 100644 index 409a230..0000000 --- a/butterrobot/admin/templates/channel_detail.j2 +++ /dev/null @@ -1,140 +0,0 @@ -{% extends "_base.j2" %} - -{% block content %} - -
-
-
-
- -
-
- - - - - - - - - - - - - - - - - - - -
ID{{ channel.id }}
Platform{{ channel.platform }}
Platform Channel ID{{ channel.platform_channel_id }}
RAW -
{{ channel.channel_raw }}
-
-
-
-
-
-
-
-

Plugins

-
-
-
- - -

-

-
- Enable plugin -
-
- -
-
- -
-
-

-
-
- - - - - - - - - - - {% for channel_plugin in channel.plugins.values() %} - - - - - - {% else %} - - - - {% endfor %} - -
NameConfigurationActions
{{ plugins[channel_plugin.plugin_id].name }} -
{{ channel_plugin.config }}
-
-
-
-
- - -
-
-
-
- -
-
-
-
No plugin is enabled on this channel
-
-
-
-
-
-{% endblock %} diff --git a/butterrobot/admin/templates/channel_list.j2 b/butterrobot/admin/templates/channel_list.j2 deleted file mode 100644 index 6bb0887..0000000 --- a/butterrobot/admin/templates/channel_list.j2 +++ /dev/null @@ -1,45 +0,0 @@ -{% extends "_base.j2" %} - -{% block content %} - - -
-
- - - - - - - - - - - - - {% for channel in channels %} - - - - - - - - {% endfor %} - -
PlatformChannel nameChannel IDEnabled
{{ channel.platform }}{{ channel.channel_name }} - {{ channel.platform_channel_id }} - {{ channel.enabled }} - Edit -
-
-
-{% endblock %} diff --git a/butterrobot/admin/templates/channel_plugins_list.j2 b/butterrobot/admin/templates/channel_plugins_list.j2 deleted file mode 100644 index 2ee69bb..0000000 --- a/butterrobot/admin/templates/channel_plugins_list.j2 +++ /dev/null @@ -1,41 +0,0 @@ -{% extends "_base.j2" %} - -{% block content %} - - -
-
- - - - - - - - - - - - {% for channel_plugin in channel_plugins %} - - - - - - - {% endfor %} - -
IDChannel IDPlugin IDEnabled
{{ channel_plugin.id }}{{ channel_plugin.channel_id }} - {{ channel_plugin.plugin_id }} - {{ channel_plugin.enabled }}
-
-
-{% endblock %} diff --git a/butterrobot/admin/templates/index.j2 b/butterrobot/admin/templates/index.j2 deleted file mode 100644 index 70b55ea..0000000 --- a/butterrobot/admin/templates/index.j2 +++ /dev/null @@ -1,5 +0,0 @@ -{% extends "_base.j2" %} - -{% block content %} - -{% endblock %} diff --git a/butterrobot/admin/templates/login.j2 b/butterrobot/admin/templates/login.j2 deleted file mode 100644 index eb78117..0000000 --- a/butterrobot/admin/templates/login.j2 +++ /dev/null @@ -1,32 +0,0 @@ -{% extends "_base.j2" %} - -{% block content %} -
- - {% if error %}

Error: {{ error }}{% endif %} -

-
-

Login

-
-
-
-
- -
- -
-
-
- -
- -
-
- -
-
-
-
-{% endblock %} diff --git a/butterrobot/admin/templates/plugin_list.j2 b/butterrobot/admin/templates/plugin_list.j2 deleted file mode 100644 index 68532fb..0000000 --- a/butterrobot/admin/templates/plugin_list.j2 +++ /dev/null @@ -1,33 +0,0 @@ -{% extends "_base.j2" %} - -{% block content %} - - -
-
- - - - - - - - - {% for plugin in plugins %} - - - - {% endfor %} - -
Name
{{ plugin.name }}
-
-
-{% endblock %} diff --git a/butterrobot/app.py b/butterrobot/app.py deleted file mode 100644 index 22344c0..0000000 --- a/butterrobot/app.py +++ /dev/null @@ -1,39 +0,0 @@ -import asyncio - -import structlog -from flask import Flask, request - -import butterrobot.logging # noqa -from butterrobot.http import ExternalProxyFix -from butterrobot.queue import q -from butterrobot.config import SECRET_KEY -from butterrobot.platforms import get_available_platforms -from butterrobot.admin.blueprint import admin as admin_bp - -loop = asyncio.get_event_loop() -logger = structlog.get_logger(__name__) -app = Flask(__name__) -app.config.update(SECRET_KEY=SECRET_KEY) -app.register_blueprint(admin_bp) -app.wsgi_app = ExternalProxyFix(app.wsgi_app) - - -@app.route("//incoming", methods=["POST"]) -@app.route("//incoming/", methods=["POST"]) -def incoming_platform_message_view(platform, path=None): - if platform not in get_available_platforms(): - return {"error": "Unknown platform"}, 400 - - q.put( - { - "platform": platform, - "request": {"path": request.path, "json": request.get_json()}, - } - ) - - return {} - - -@app.route("/healthz") -def healthz(): - return {} diff --git a/butterrobot/config.py b/butterrobot/config.py deleted file mode 100644 index cefa366..0000000 --- a/butterrobot/config.py +++ /dev/null @@ -1,31 +0,0 @@ -import os - -# --- Butter Robot ----------------------------------------------------------------- -DEBUG = os.environ.get("DEBUG", "n") == "y" - -HOSTNAME = os.environ.get( - "BUTTERROBOT_HOSTNAME", "butterrobot-dev.int.fmartingr.network" -) - -LOG_LEVEL = os.environ.get("LOG_LEVEL", "ERROR") - -SECRET_KEY = os.environ.get("SECRET_KEY", "1234") - -# --- DATABASE --------------------------------------------------------------------- -DATABASE_PATH = os.environ.get("DATABASE_PATH", "sqlite:///butterrobot.sqlite") - -# --- PLATFORMS --------------------------------------------------------------------- -# --- -# Slack -# --- -# Slack app access token -SLACK_TOKEN = os.environ.get("SLACK_TOKEN") - -# Slack app oauth access token to send messages on the bot behalf -SLACK_BOT_OAUTH_ACCESS_TOKEN = os.environ.get("SLACK_BOT_OAUTH_ACCESS_TOKEN") - -# --- -# Telegram -# --- -# Telegram auth token -TELEGRAM_TOKEN = os.environ.get("TELEGRAM_TOKEN") diff --git a/butterrobot/db.py b/butterrobot/db.py deleted file mode 100644 index fe29920..0000000 --- a/butterrobot/db.py +++ /dev/null @@ -1,163 +0,0 @@ -import hashlib -from typing import Union - -import dataset - -from butterrobot.config import SECRET_KEY, DATABASE_PATH -from butterrobot.objects import User, Channel, ChannelPlugin - -db = dataset.connect(DATABASE_PATH) - - -class Query: - class NotFound(Exception): - pass - - class Duplicated(Exception): - pass - - @classmethod - def all(cls): - """ - Iterate over all rows on a table. - """ - for row in db[cls.tablename].all(): - yield cls.obj(**row) - - @classmethod - def get(cls, **kwargs): - """ - Returns the object representation of an specific row in a table. - Allows retrieving object by multiple columns. - Raises `NotFound` error if query return no results. - """ - row = db[cls.tablename].find_one(**kwargs) - if not row: - raise cls.NotFound - return cls.obj(**row) - - @classmethod - def create(cls, **kwargs): - """ - Creates a new row in the table with the provided arguments. - Returns the row_id - TODO: Return obj? - """ - return db[cls.tablename].insert(kwargs) - - @classmethod - def exists(cls, **kwargs) -> bool: - """ - Check for the existence of a row with the provided columns. - """ - try: - cls.get(**kwargs) - except cls.NotFound: - return False - return True - - @classmethod - def update(cls, row_id, **fields): - fields.update({"id": row_id}) - return db[cls.tablename].update(fields, ("id",)) - - @classmethod - def delete(cls, id): - return db[cls.tablename].delete(id=id) - - -class UserQuery(Query): - tablename = "users" - obj = User - - @classmethod - def _hash_password(cls, password): - return hashlib.pbkdf2_hmac( - "sha256", password.encode("utf-8"), str.encode(SECRET_KEY), 100000 - ).hex() - - @classmethod - def check_credentials(cls, username, password) -> Union[User, "False"]: - user = db[cls.tablename].find_one(username=username) - if user: - hash_password = cls._hash_password(password) - if user["password"] == hash_password: - return cls.obj(**user) - return False - - @classmethod - def create(cls, **kwargs): - kwargs["password"] = cls._hash_password(kwargs["password"]) - return super().create(**kwargs) - - -class ChannelQuery(Query): - tablename = "channels" - obj = Channel - - @classmethod - def create(cls, platform, platform_channel_id, enabled=False, channel_raw={}): - params = { - "platform": platform, - "platform_channel_id": platform_channel_id, - "enabled": enabled, - "channel_raw": channel_raw, - } - super().create(**params) - return cls.obj(**params) - - @classmethod - def get(cls, _id): - channel = super().get(id=_id) - plugins = ChannelPluginQuery.get_from_channel_id(_id) - channel.plugins = {plugin.plugin_id: plugin for plugin in plugins} - return channel - - @classmethod - def get_by_platform(cls, platform, platform_channel_id): - result = db[cls.tablename].find_one( - platform=platform, platform_channel_id=platform_channel_id - ) - if not result: - raise cls.NotFound - - plugins = ChannelPluginQuery.get_from_channel_id(result["id"]) - - return cls.obj( - plugins={plugin.plugin_id: plugin for plugin in plugins}, **result - ) - - @classmethod - def delete(cls, _id): - ChannelPluginQuery.delete_by_channel(channel_id=_id) - super().delete(_id) - - -class ChannelPluginQuery(Query): - tablename = "channel_plugin" - obj = ChannelPlugin - - @classmethod - def create(cls, channel_id, plugin_id, enabled=False, config={}): - if cls.exists(channel_id=channel_id, plugin_id=plugin_id): - raise cls.Duplicated - - params = { - "channel_id": channel_id, - "plugin_id": plugin_id, - "enabled": enabled, - "config": config, - } - obj_id = super().create(**params) - return cls.obj(id=obj_id, **params) - - @classmethod - def get_from_channel_id(cls, channel_id): - yield from [ - cls.obj(**row) for row in db[cls.tablename].find(channel_id=channel_id) - ] - - @classmethod - def delete_by_channel(cls, channel_id): - channel_plugins = cls.get_from_channel_id(channel_id) - [cls.delete(item.id) for item in channel_plugins] diff --git a/butterrobot/http.py b/butterrobot/http.py deleted file mode 100644 index 9086155..0000000 --- a/butterrobot/http.py +++ /dev/null @@ -1,15 +0,0 @@ -class ExternalProxyFix(object): - """ - Custom proxy helper to get the external hostname from the `X-External-Host` header - used by one of the reverse proxies in front of this in production. - It does nothing if the header is not present. - """ - - def __init__(self, app): - self.app = app - - def __call__(self, environ, start_response): - host = environ.get("HTTP_X_EXTERNAL_HOST", "") - if host: - environ["HTTP_HOST"] = host - return self.app(environ, start_response) diff --git a/butterrobot/lib/__init__.py b/butterrobot/lib/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/butterrobot/lib/slack.py b/butterrobot/lib/slack.py deleted file mode 100644 index b8cc7d3..0000000 --- a/butterrobot/lib/slack.py +++ /dev/null @@ -1,61 +0,0 @@ -from typing import Optional, Text - -import requests -import structlog - -from butterrobot.config import SLACK_BOT_OAUTH_ACCESS_TOKEN - - -logger = structlog.get_logger() - - -class SlackAPI: - BASE_URL = "https://slack.com/api" - HEADERS = {"Authorization": f"Bearer {SLACK_BOT_OAUTH_ACCESS_TOKEN}"} - - class SlackError(Exception): - pass - - class SlackClientError(Exception): - pass - - @classmethod - def get_conversations_info(cls, chat_id) -> dict: - params = {"channel": chat_id} - response = requests.get( - f"{cls.BASE_URL}/conversations.info", params=params, headers=cls.HEADERS, - ) - response_json = response.json() - if not response_json["ok"]: - raise cls.SlackClientError(response_json) - - return response_json["channel"] - - @classmethod - def get_user_info(cls, chat_id) -> dict: - params = {"user": chat_id} - response = requests.get( - f"{cls.BASE_URL}/users.info", params=params, headers=cls.HEADERS, - ) - response_json = response.json() - if not response_json["ok"]: - raise cls.SlackClientError(response_json) - - return response_json["user"] - - @classmethod - def send_message(cls, channel, message, thread: Optional[Text] = None): - payload = { - "text": message, - "channel": channel, - } - - if thread: - payload["thread_ts"] = thread - - response = requests.post( - f"{cls.BASE_URL}/chat.postMessage", data=payload, headers=cls.HEADERS, - ) - response_json = response.json() - if not response_json["ok"]: - raise cls.SlackClientError(response_json) diff --git a/butterrobot/lib/telegram.py b/butterrobot/lib/telegram.py deleted file mode 100644 index a10ecfa..0000000 --- a/butterrobot/lib/telegram.py +++ /dev/null @@ -1,58 +0,0 @@ -import requests -import structlog - -from butterrobot.config import TELEGRAM_TOKEN - - -logger = structlog.get_logger(__name__) - - -class TelegramAPI: - BASE_URL = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}" - - DEFAULT_ALLOWED_UPDATES = ["message"] - - class TelegramError(Exception): - pass - - class TelegramClientError(Exception): - pass - - @classmethod - def set_webhook(cls, webhook_url, max_connections=40, allowed_updates=None): - allowed_updates = allowed_updates or cls.DEFAULT_ALLOWED_UPDATES - url = f"{cls.BASE_URL}/setWebhook" - payload = { - "url": webhook_url, - "max_connections": max_connections, - "allowed_updates": allowed_updates, - } - response = requests.post(url, json=payload) - response_json = response.json() - if not response_json["ok"]: - raise cls.TelegramClientError(response_json) - - @classmethod - def send_message( - cls, - chat_id, - text, - parse_mode="markdown", - disable_web_page_preview=False, - disable_notification=False, - reply_to_message_id=None, - ): - url = f"{cls.BASE_URL}/sendMessage" - payload = { - "chat_id": chat_id, - "text": text, - "parse_mode": parse_mode, - "disable_web_page_preview": disable_web_page_preview, - "disable_notification": disable_notification, - "reply_to_message_id": reply_to_message_id, - } - - response = requests.post(url, json=payload) - response_json = response.json() - if not response_json["ok"]: - raise cls.TelegramClientError(response_json) diff --git a/butterrobot/logging.py b/butterrobot/logging.py deleted file mode 100644 index f31e5b8..0000000 --- a/butterrobot/logging.py +++ /dev/null @@ -1,25 +0,0 @@ -import logging - -import structlog - -from butterrobot.config import LOG_LEVEL, DEBUG - - -logging.basicConfig(format="%(message)s", level=LOG_LEVEL) -structlog.configure( - processors=[ - structlog.stdlib.add_log_level, - structlog.stdlib.add_logger_name, - structlog.dev.set_exc_info, - structlog.processors.StackInfoRenderer(), - structlog.processors.TimeStamper(fmt="%Y-%m-%d %H:%M.%S"), - structlog.processors.format_exc_info, - structlog.dev.ConsoleRenderer() - if DEBUG - else structlog.processors.JSONRenderer(), - ], - context_class=dict, - logger_factory=structlog.stdlib.LoggerFactory(), - wrapper_class=structlog.BoundLogger, - cache_logger_on_first_use=True, -) diff --git a/butterrobot/objects.py b/butterrobot/objects.py deleted file mode 100644 index 215924b..0000000 --- a/butterrobot/objects.py +++ /dev/null @@ -1,61 +0,0 @@ -from datetime import datetime -from dataclasses import dataclass, field -from typing import Text, Optional, Dict - -import structlog - - -logger = structlog.get_logger(__name__) - - -@dataclass -class ChannelPlugin: - id: int - channel_id: int - plugin_id: str - enabled: bool = False - config: dict = field(default_factory=dict) - - -@dataclass -class Channel: - platform: str - platform_channel_id: str - channel_raw: dict - enabled: bool = False - id: Optional[int] = None - plugins: Dict[str, ChannelPlugin] = field(default_factory=dict) - - def has_enabled_plugin(self, plugin_id): - if plugin_id not in self.plugins: - logger.debug("No enabled!", plugin_id=plugin_id, plugins=self.plugins) - return False - - return self.plugins[plugin_id].enabled - - @property - def channel_name(self): - from butterrobot.platforms import PLATFORMS - - return PLATFORMS[self.platform].parse_channel_name_from_raw(self.channel_raw) - - -@dataclass -class Message: - text: Text - chat: Text - # TODO: Move chat references to `.channel.platform_channel_id` - channel: Optional[Channel] = None - author: Text = None - from_bot: bool = False - date: Optional[datetime] = None - id: Optional[Text] = None - reply_to: Optional[Text] = None - raw: dict = field(default_factory=dict) - - -@dataclass -class User: - id: int - username: Text - password: Text diff --git a/butterrobot/platforms/__init__.py b/butterrobot/platforms/__init__.py deleted file mode 100644 index dad1360..0000000 --- a/butterrobot/platforms/__init__.py +++ /dev/null @@ -1,30 +0,0 @@ -from functools import lru_cache - -import structlog - -from butterrobot.platforms.slack import SlackPlatform -from butterrobot.platforms.telegram import TelegramPlatform -from butterrobot.platforms.debug import DebugPlatform - - -logger = structlog.get_logger(__name__) -PLATFORMS = { - platform.ID: platform - for platform in (SlackPlatform, TelegramPlatform, DebugPlatform) -} - - -@lru_cache -def get_available_platforms(): - from butterrobot.platforms import PLATFORMS - - available_platforms = {} - for platform in PLATFORMS.values(): - logger.debug("Setting up", platform=platform.ID) - try: - platform.init(app=None) - available_platforms[platform.ID] = platform - logger.info("platform setup completed", platform=platform.ID) - except platform.PlatformInitError as error: - logger.error("Platform init error", error=error, platform=platform.ID) - return available_platforms diff --git a/butterrobot/platforms/base.py b/butterrobot/platforms/base.py deleted file mode 100644 index a5d778e..0000000 --- a/butterrobot/platforms/base.py +++ /dev/null @@ -1,67 +0,0 @@ -from abc import abstractmethod -from dataclasses import dataclass - - -class Platform: - class PlatformError(Exception): - pass - - class PlatformInitError(PlatformError): - pass - - class PlatformAuthError(PlatformError): - pass - - @dataclass - class PlatformAuthResponse(PlatformError): - """ - Used when the platform needs to make a response right away instead of async. - """ - - data: dict - status_code: int = 200 - - @classmethod - def init(cls, app): - """ - Initialises the platform. - - Used at the application launch to prepare anything required for - the platform to work.. - - It receives the flask application via parameter in case the platform - requires for custom webservice endpoints or configuration. - """ - pass - - @classmethod - @abstractmethod - def parse_incoming_message(cls, request): - """ - Parses the incoming request and returns a :class:`butterrobot.objects.Message` instance. - """ - pass - - @classmethod - @abstractmethod - def parse_channel_name_from_raw(cls, channel_raw) -> str: - """ - Extracts the Channel name from :class:`butterrobot.objects.Channel.channel_raw`. - """ - pass - - @classmethod - @abstractmethod - def parse_channel_from_message(cls, channel_raw): - """ - Extracts the Channel raw data from the message received in the incoming webhook. - """ - pass - - -class PlatformMethods: - @classmethod - @abstractmethod - def send_message(cls, message): - """Method used to send a message via the platform""" - pass diff --git a/butterrobot/platforms/debug.py b/butterrobot/platforms/debug.py deleted file mode 100644 index 9982011..0000000 --- a/butterrobot/platforms/debug.py +++ /dev/null @@ -1,44 +0,0 @@ -import uuid -from datetime import datetime - -import structlog - -from butterrobot.platforms.base import Platform, PlatformMethods -from butterrobot.objects import Message, Channel - - -logger = structlog.get_logger(__name__) - - -class DebugMethods(PlatformMethods): - @classmethod - def send_message(self, message: Message): - logger.debug( - "Outgoing message", message=message.__dict__, platform=DebugPlatform.ID - ) - - -class DebugPlatform(Platform): - ID = "debug" - - methods = DebugMethods - - @classmethod - def parse_incoming_message(cls, request): - request_data = request["json"] - logger.debug("Parsing message", data=request_data, platform=cls.ID) - - return Message( - id=str(uuid.uuid4()), - date=datetime.now(), - text=request_data["text"], - from_bot=bool(request_data.get("from_bot", False)), - author=request_data.get("author", "Debug author"), - chat=request_data.get("chat", "Debug chat ID"), - channel=Channel( - platform=cls.ID, - platform_channel_id=request_data.get("chat"), - channel_raw={}, - ), - raw={}, - ) diff --git a/butterrobot/platforms/slack.py b/butterrobot/platforms/slack.py deleted file mode 100644 index aa1b133..0000000 --- a/butterrobot/platforms/slack.py +++ /dev/null @@ -1,105 +0,0 @@ -from datetime import datetime - -import structlog - -from butterrobot.platforms.base import Platform, PlatformMethods -from butterrobot.config import SLACK_TOKEN, SLACK_BOT_OAUTH_ACCESS_TOKEN -from butterrobot.objects import Message, Channel -from butterrobot.lib.slack import SlackAPI - - -logger = structlog.get_logger(__name__) - - -class SlackMethods(PlatformMethods): - @classmethod - def send_message(self, message: Message): - logger.debug( - "Outgoing message", message=message.__dict__, platform=SlackPlatform.ID - ) - try: - SlackAPI.send_message( - channel=message.chat, message=message.text, thread=message.reply_to - ) - except SlackAPI.SlackClientError as error: - logger.error( - "Send message error", - platform=SlackPlatform.ID, - error=error, - message=message.__dict__, - ) - - -class SlackPlatform(Platform): - ID = "slack" - - methods = SlackMethods - - @classmethod - def init(cls, app): - if not (SLACK_TOKEN and SLACK_BOT_OAUTH_ACCESS_TOKEN): - logger.error("Missing token. platform not enabled.", platform=cls.ID) - return - - @classmethod - def parse_channel_name_from_raw(cls, channel_raw): - return channel_raw["name"] - - @classmethod - def parse_channel_from_message(cls, message): - # Call different APIs for a channel or DM - if message["event"]["channel_type"] == "im": - chat_raw = SlackAPI.get_user_info(message["event"]["user"]) - else: - chat_raw = SlackAPI.get_conversations_info(message["event"]["channel"]) - - return Channel( - platform=cls.ID, - platform_channel_id=message["event"]["channel"], - channel_raw=chat_raw, - ) - - @classmethod - def parse_incoming_message(cls, request): - data = request["json"] - - # Auth - if data.get("token") != SLACK_TOKEN: - raise cls.PlatformAuthError("Authentication error") - - # Confirms challenge request to configure webhook - if "challenge" in data: - raise cls.PlatformAuthResponse(data={"challenge": data["challenge"]}) - - # Discard messages by webhooks and apps - if "bot_id" in data["event"]: - logger.debug("Discarding message", data=data) - return - - logger.debug("Parsing message", platform=cls.ID, data=data) - - if data["event"]["type"] not in ("message", "message.groups"): - return - - # Surprisingly, this *can* happen. - if "text" not in data["event"]: - return - - message = Message( - id=data["event"].get("thread_ts", data["event"]["ts"]), - author=data["event"].get("user"), - from_bot="bot_id" in data["event"], - date=datetime.fromtimestamp(int(float(data["event"]["event_ts"]))), - text=data["event"]["text"], - chat=data["event"]["channel"], - channel=cls.parse_channel_from_message(data), - raw=data, - ) - - logger.info( - "New message", - platform=message.channel.platform, - channel=cls.parse_channel_name_from_raw(message.channel.channel_raw), - ) - - return message diff --git a/butterrobot/platforms/telegram.py b/butterrobot/platforms/telegram.py deleted file mode 100644 index ddf7607..0000000 --- a/butterrobot/platforms/telegram.py +++ /dev/null @@ -1,87 +0,0 @@ -from datetime import datetime - -import structlog - -from butterrobot.platforms.base import Platform, PlatformMethods -from butterrobot.config import TELEGRAM_TOKEN, HOSTNAME -from butterrobot.lib.telegram import TelegramAPI -from butterrobot.objects import Message, Channel - - -logger = structlog.get_logger(__name__) - - -class TelegramMethods(PlatformMethods): - @classmethod - def send_message(self, message: Message): - logger.debug( - "Outgoing message", message=message.__dict__, platform=TelegramPlatform.ID - ) - TelegramAPI.send_message( - chat_id=message.chat, - text=message.text, - reply_to_message_id=message.reply_to, - ) - - -class TelegramPlatform(Platform): - ID = "telegram" - - methods = TelegramMethods - - @classmethod - def init(cls, app): - """ - Initializes the Telegram webhook endpoint to receive updates - """ - - if not TELEGRAM_TOKEN: - logger.error("Missing token. platform not enabled.", platform=cls.ID) - return - - webhook_url = f"https://{HOSTNAME}/telegram/incoming/{TELEGRAM_TOKEN}" - try: - TelegramAPI.set_webhook(webhook_url) - except TelegramAPI.TelegramError as error: - logger.error(f"Error setting Telegram webhook: {error}", platform=cls.ID) - raise Platform.PlatformInitError() - - @classmethod - def parse_channel_name_from_raw(cls, channel_raw): - if channel_raw["id"] < 0: - return channel_raw["title"] - else: - if channel_raw["username"]: - return f"@{channel_raw['username']}" - return f"{channel_raw['first_name']} {channel_raw['last_name']}" - - @classmethod - def parse_channel_from_message(cls, channel_raw): - return Channel( - platform=cls.ID, - platform_channel_id=channel_raw["id"], - channel_raw=channel_raw, - ) - - @classmethod - def parse_incoming_message(cls, request): - token = request["path"].split("/")[-1] - if token != TELEGRAM_TOKEN: - raise cls.PlatformAuthError("Authentication error") - - logger.debug("Parsing message", data=request["json"], platform=cls.ID) - - if "text" in request["json"]["message"]: - # Ignore all messages but text messages - return Message( - id=request["json"]["message"]["message_id"], - date=datetime.fromtimestamp(request["json"]["message"]["date"]), - text=str(request["json"]["message"]["text"]), - from_bot=request["json"]["message"]["from"]["is_bot"], - author=request["json"]["message"]["from"]["id"], - chat=str(request["json"]["message"]["chat"]["id"]), - channel=cls.parse_channel_from_message( - request["json"]["message"]["chat"] - ), - raw=request["json"], - ) diff --git a/butterrobot/plugins.py b/butterrobot/plugins.py deleted file mode 100644 index 0ee3b55..0000000 --- a/butterrobot/plugins.py +++ /dev/null @@ -1,67 +0,0 @@ -import traceback -import pkg_resources -from abc import abstractclassmethod -from functools import lru_cache -from typing import Optional, Dict - -import structlog - -from butterrobot.objects import Message - - -logger = structlog.get_logger(__name__) - - -class Plugin: - """ - Base Plugin class. - - All attributes are required except for `requires_config`. - """ - - id: str - name: str - help: str - requires_config: bool = False - - @abstractclassmethod - def on_message(cls, message: Message, channel_config: Optional[Dict] = None): - """ - Function called for each message received on the chat. - - It should exit as soon as possible (usually checking for a keyword or something) - similar just at the start. - - If the plugin needs to be executed (keyword matches), keep it as fast as possible - as this currently blocks the execution of the rest of the plugins on the channel - until this does not finish. - TODO: Update this once we go proper async plugin/message integration - - In case something needs to be answered to the channel, you can `yield` a `Message` - instance and it will be relayed using the appropriate provider. - """ - pass - - -@lru_cache -def get_available_plugins(): - """ - Retrieves every available auto discovered plugin - """ - plugins = {} - for ep in pkg_resources.iter_entry_points("butterrobot.plugins"): - try: - plugin_cls = ep.load() - plugins[plugin_cls.id] = plugin_cls - except Exception as error: - logger.error( - "Error loading plugin", - exception=str(error), - traceback=traceback.format_exc(), - plugin=ep.name, - project_name=ep.dist.project_name, - entry_point=ep, - module=ep.module_name, - ) - - return plugins diff --git a/butterrobot/queue.py b/butterrobot/queue.py deleted file mode 100644 index 82f99a7..0000000 --- a/butterrobot/queue.py +++ /dev/null @@ -1,64 +0,0 @@ -import threading -import traceback -import queue - -import structlog - -from butterrobot.db import ChannelQuery -from butterrobot.platforms import get_available_platforms -from butterrobot.platforms.base import Platform -from butterrobot.plugins import get_available_plugins - -logger = structlog.get_logger(__name__) -q = queue.Queue() - - -def handle_message(platform: str, request: dict): - try: - message = get_available_platforms()[platform].parse_incoming_message( - request=request - ) - except Platform.PlatformAuthResponse as response: - return response.data, response.status_code - except Exception as error: - logger.error( - "Error parsing message", - platform=platform, - error=error, - traceback=traceback.format_exc(), - ) - return - - if not message or message.from_bot: - return - - try: - channel = ChannelQuery.get_by_platform(platform, message.chat) - except ChannelQuery.NotFound: - # If channel is still not present on the database, create it (defaults to disabled) - channel = ChannelQuery.create( - platform, message.chat, channel_raw=message.channel.channel_raw - ) - - if not channel.enabled: - return - - for plugin_id, channel_plugin in channel.plugins.items(): - if not channel.has_enabled_plugin(plugin_id): - continue - - for response_message in get_available_plugins()[plugin_id].on_message( - message, plugin_config=channel_plugin.config - ): - get_available_platforms()[platform].methods.send_message(response_message) - - -def worker_thread(): - while True: - item = q.get() - handle_message(item["platform"], item["request"]) - q.task_done() - - -# turn-on the worker thread -worker = threading.Thread(target=worker_thread, daemon=True).start() diff --git a/butterrobot_plugins_contrib/__init__.py b/butterrobot_plugins_contrib/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/butterrobot_plugins_contrib/dev.py b/butterrobot_plugins_contrib/dev.py deleted file mode 100644 index c03f6c7..0000000 --- a/butterrobot_plugins_contrib/dev.py +++ /dev/null @@ -1,18 +0,0 @@ -from datetime import datetime - -from butterrobot.plugins import Plugin -from butterrobot.objects import Message - - -class PingPlugin(Plugin): - name = "Ping command" - id = "contrib.dev.ping" - - @classmethod - def on_message(cls, message, **kwargs): - if message.text == "!ping": - delta = datetime.now() - message.date - delta_ms = delta.seconds * 1000 + delta.microseconds / 1000 - yield Message( - chat=message.chat, reply_to=message.id, text=f"pong! ({delta_ms}ms)", - ) diff --git a/butterrobot_plugins_contrib/fun.py b/butterrobot_plugins_contrib/fun.py deleted file mode 100644 index 4a5b3bf..0000000 --- a/butterrobot_plugins_contrib/fun.py +++ /dev/null @@ -1,51 +0,0 @@ -import random - -import dice -import structlog - -from butterrobot.plugins import Plugin -from butterrobot.objects import Message - - -logger = structlog.get_logger(__name__) - - -class LoquitoPlugin(Plugin): - name = "Loquito reply" - id = "contrib.fun.loquito" - - @classmethod - def on_message(cls, message, **kwargs): - if "lo quito" in message.text.lower(): - yield Message( - chat=message.chat, reply_to=message.id, text="Loquito tu.", - ) - - -class DicePlugin(Plugin): - name = "Dice command" - id = "contrib.fun.dice" - DEFAULT_FORMULA = "1d20" - - @classmethod - def on_message(cls, message: Message, **kwargs): - if message.text.startswith("!dice"): - dice_formula = message.text.replace("!dice", "").strip() - if not dice_formula: - dice_formula = cls.DEFAULT_FORMULA - roll = int(dice.roll(dice_formula)) - yield Message(chat=message.chat, reply_to=message.id, text=roll) - - -class CoinPlugin(Plugin): - name = "Coin command" - id = "contrib.fun.coin" - - @classmethod - def on_message(cls, message: Message, **kwargs): - if message.text.startswith("!coin"): - yield Message( - chat=message.chat, - reply_to=message.id, - text=random.choice(("heads", "tails")), - ) diff --git a/cmd/butterrobot/main.go b/cmd/butterrobot/main.go new file mode 100644 index 0000000..5cf57f9 --- /dev/null +++ b/cmd/butterrobot/main.go @@ -0,0 +1,33 @@ +package main + +import ( + "log/slog" + "os" + + "git.nakama.town/fmartingr/butterrobot/internal/app" + "git.nakama.town/fmartingr/butterrobot/internal/config" +) + +func main() { + // Initialize logger + logger := slog.New(slog.NewTextHandler(os.Stdout, nil)) + + // Load configuration + cfg, err := config.Load() + if err != nil { + logger.Error("Failed to load configuration", "error", err) + os.Exit(1) + } + + // Initialize and run application + application, err := app.New(cfg, logger) + if err != nil { + logger.Error("Failed to initialize application", "error", err) + os.Exit(1) + } + + if err := application.Run(); err != nil { + logger.Error("Application error", "error", err) + os.Exit(1) + } +} \ No newline at end of file diff --git a/docker/Dockerfile b/docker/Dockerfile deleted file mode 100644 index 7c95591..0000000 --- a/docker/Dockerfile +++ /dev/null @@ -1,17 +0,0 @@ -FROM alpine:3.11 - -ENV PYTHON_VERSION=3.8.2-r1 -ENV APP_PORT 8080 -ENV BUTTERROBOT_VERSION 0.0.3 -ENV EXTRA_DEPENDENCIES "" -ENV APP_PATH /etc/butterrobot - -COPY bin/start-server.sh /usr/local/bin/start-server -RUN apk --update add curl python3-dev==${PYTHON_VERSION} gcc musl-dev libffi-dev openssl-dev && \ - pip3 install butterrobot==${BUTTERROBOT_VERSION} ${EXTRA_DEPENDENCIES} && \ - mkdir ${APP_PATH} && \ - chown -R 1000:1000 ${APP_PATH} - -USER 1000 - -CMD ["/usr/local/bin/start-server"] diff --git a/docker/bin/start-server.sh b/docker/bin/start-server.sh deleted file mode 100755 index aa5ea13..0000000 --- a/docker/bin/start-server.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/sh -xe - -waitress-serve --port=${APP_PORT} 'butterrobot.app:app' \ No newline at end of file diff --git a/docs/contributing.md b/docs/contributing.md index ae11cef..8c7ff76 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -1,11 +1,12 @@ ## Contributing -To run the project locally you will need [poetry](https://python-poetry.org/). +To run the project locally you will need Go 1.19 or higher. -``` +```bash git clone git@github.com:fmartingr/butterrobot.git cd butterrobot make setup +make build ``` Create a `.env-local` file with the required environment variables, you have [an example file](.env-example). @@ -13,11 +14,16 @@ Create a `.env-local` file with the required environment variables, you have [an ``` SLACK_TOKEN=xxx TELEGRAM_TOKEN=xxx +HOSTNAME=myhostname.com ... ``` -And then you can run it directly with poetry: +And then you can run it directly: -``` -poetry run python -m butterrobot +```bash +# Run directly with Go +go run ./cmd/butterrobot/main.go + +# Or run the built binary +./bin/butterrobot ``` diff --git a/docs/creating-a-plugin.md b/docs/creating-a-plugin.md index 0f4cee6..945d03c 100644 --- a/docs/creating-a-plugin.md +++ b/docs/creating-a-plugin.md @@ -2,36 +2,61 @@ ## Example -This simple "Marco Polo" plugin will answer _Polo_ to the user that say _Marco_: +This simple "Marco Polo" plugin will answer _Polo_ to the user that says _Marco_: -``` python -# mypackage/plugins.py -from butterrobot.plugins import Plugin -from butterrobot.objects import Message +```go +package myplugin +import ( + "strings" -class PingPlugin(Plugin): - name = "Marco/Polo" - id = "test.marco" + "git.nakama.town/fmartingr/butterrobot/internal/model" + "git.nakama.town/fmartingr/butterrobot/internal/plugin" +) - @classmethod - def on_message(cls, message, **kwargs): - if message.text == "Marco": - yield Message( - chat=message.chat, reply_to=message.id, text=f"polo", - ) -``` - -``` python -# setup.py -# ... -entrypoints = { - "test.marco" = "mypackage.plugins:MarcoPlugin" +// MarcoPlugin is a simple Marco/Polo plugin +type MarcoPlugin struct { + plugin.BasePlugin } -setup( - # ... - entry_points=entrypoints, - # ... -) +// New creates a new MarcoPlugin instance +func New() *MarcoPlugin { + return &MarcoPlugin{ + BasePlugin: plugin.BasePlugin{ + ID: "test.marco", + Name: "Marco/Polo", + Help: "Responds to 'Marco' with 'Polo'", + }, + } +} + +// OnMessage handles incoming messages +func (p *MarcoPlugin) OnMessage(msg *model.Message, config map[string]interface{}) []*model.Message { + if !strings.EqualFold(strings.TrimSpace(msg.Text), "Marco") { + return nil + } + + response := &model.Message{ + Text: "Polo", + Chat: msg.Chat, + ReplyTo: msg.ID, + Channel: msg.Channel, + } + + return []*model.Message{response} +} +``` + +To use the plugin, register it in your application: + +```go +// In app.go or similar initialization file +func (a *App) Run() error { + // ... + + // Register plugins + plugin.Register(myplugin.New()) + + // ... +} ``` diff --git a/docs/plugins.md b/docs/plugins.md index e4fcd29..11e3d16 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -2,10 +2,10 @@ ### Development -- `!ping`: Say `!ping` to get response with time elapsed. +- `ping`: Say `ping` to get response with time elapsed. ### Fun and entertainment - - Lo quito: What happens when you say _"lo quito"_...? (Spanish pun) - Dice: Put `!dice` and wathever roll you want to perform. +- Coin: Flip a coin and get heads or tails. diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..ab85fc8 --- /dev/null +++ b/go.mod @@ -0,0 +1,22 @@ +module git.nakama.town/fmartingr/butterrobot + +go 1.24 + +require ( + github.com/gorilla/sessions v1.4.0 + modernc.org/sqlite v1.37.0 +) + +require ( + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/gorilla/securecookie v1.1.2 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/ncruces/go-strftime v0.1.9 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0 // indirect + golang.org/x/sys v0.32.0 // indirect + modernc.org/libc v1.63.0 // indirect + modernc.org/mathutil v1.7.1 // indirect + modernc.org/memory v1.10.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..248cd40 --- /dev/null +++ b/go.sum @@ -0,0 +1,53 @@ +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= +github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs= +github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA= +github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo= +github.com/gorilla/sessions v1.4.0 h1:kpIYOp/oi6MG/p5PgxApU8srsSw9tuFbt46Lt7auzqQ= +github.com/gorilla/sessions v1.4.0/go.mod h1:FLWm50oby91+hl7p/wRxDth9bWSuk0qVL2emc7lT5ik= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4= +github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0 h1:R84qjqJb5nVJMxqWYb3np9L5ZsaDtB+a39EqjV0JSUM= +golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0/go.mod h1:S9Xr4PYopiDyqSyp5NjCrhFrqg6A5zA2E/iPHPhqnS8= +golang.org/x/mod v0.24.0 h1:ZfthKaKaT4NrhGVZHO1/WDTwGES4De8KtWO0SIbNJMU= +golang.org/x/mod v0.24.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww= +golang.org/x/sync v0.13.0 h1:AauUjRAJ9OSnvULf/ARrrVywoJDy0YS2AwQ98I37610= +golang.org/x/sync v0.13.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20= +golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/tools v0.32.0 h1:Q7N1vhpkQv7ybVzLFtTjvQya2ewbwNDZzUgfXGqtMWU= +golang.org/x/tools v0.32.0/go.mod h1:ZxrU41P/wAbZD8EDa6dDCa6XfpkhJ7HFMjHJXfBDu8s= +modernc.org/cc/v4 v4.26.0 h1:QMYvbVduUGH0rrO+5mqF/PSPPRZNpRtg2CLELy7vUpA= +modernc.org/cc/v4 v4.26.0/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0= +modernc.org/ccgo/v4 v4.26.0 h1:gVzXaDzGeBYJ2uXTOpR8FR7OlksDOe9jxnjhIKCsiTc= +modernc.org/ccgo/v4 v4.26.0/go.mod h1:Sem8f7TFUtVXkG2fiaChQtyyfkqhJBg/zjEJBkmuAVY= +modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE= +modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ= +modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI= +modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= +modernc.org/libc v1.63.0 h1:wKzb61wOGCzgahQBORb1b0dZonh8Ufzl/7r4Yf1D5YA= +modernc.org/libc v1.63.0/go.mod h1:wDzH1mgz1wUIEwottFt++POjGRO9sgyQKrpXaz3x89E= +modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= +modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= +modernc.org/memory v1.10.0 h1:fzumd51yQ1DxcOxSO+S6X7+QTuVU+n8/Aj7swYjFfC4= +modernc.org/memory v1.10.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8= +modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= +modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= +modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= +modernc.org/sqlite v1.37.0 h1:s1TMe7T3Q3ovQiK2Ouz4Jwh7dw4ZDqbebSDTlSJdfjI= +modernc.org/sqlite v1.37.0/go.mod h1:5YiWv+YviqGMuGw4V+PNplcyaJ5v+vQd7TQOgkACoJM= +modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= +modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= diff --git a/internal/admin/admin.go b/internal/admin/admin.go new file mode 100644 index 0000000..715c5e1 --- /dev/null +++ b/internal/admin/admin.go @@ -0,0 +1,563 @@ +package admin + +import ( + "html/template" + "net/http" + "path/filepath" + "strconv" + "strings" + + "git.nakama.town/fmartingr/butterrobot/internal/config" + "git.nakama.town/fmartingr/butterrobot/internal/db" + "git.nakama.town/fmartingr/butterrobot/internal/model" + "git.nakama.town/fmartingr/butterrobot/internal/plugin" + "github.com/gorilla/sessions" +) + +const ( + // Session store key + sessionKey = "butterrobot-session" + + // Template directory + templateDir = "./internal/admin/templates" +) + +// FlashMessage represents a flash message +type FlashMessage struct { + Category string + Message string +} + +// TemplateData holds data for rendering templates +type TemplateData struct { + User *model.User + LoggedIn bool + Title string + Path string + Flash []FlashMessage + Plugins map[string]model.Plugin + Channels []*model.Channel + Channel *model.Channel + ChannelPlugin *model.ChannelPlugin +} + +// Admin represents the admin interface +type Admin struct { + config *config.Config + db *db.Database + store *sessions.CookieStore + templates map[string]*template.Template + baseTemplate *template.Template +} + +// New creates a new Admin instance +func New(cfg *config.Config, database *db.Database) *Admin { + // Create session store + store := sessions.NewCookieStore([]byte(cfg.SecretKey)) + + // Load templates + templates := make(map[string]*template.Template) + + // Create a template function map with helper functions + funcMap := template.FuncMap{ + "contains": strings.Contains, + } + + // Create a custom template with functions + baseTemplate := template.New("_base.html").Funcs(funcMap) + baseTemplate = template.Must(baseTemplate.ParseFiles(filepath.Join(templateDir, "_base.html"))) + + // Parse and register all templates + templateFiles := []string{ + "index.html", + "login.html", + "channel_list.html", + "channel_detail.html", + "plugin_list.html", + "channel_plugins_list.html", + } + + for _, tf := range templateFiles { + // Create a clone of the base template + t, err := template.Must(baseTemplate.Clone()).ParseFiles(filepath.Join(templateDir, tf)) + if err != nil { + panic(err) + } + templates[tf] = t + } + + return &Admin{ + config: cfg, + db: database, + store: store, + templates: templates, + baseTemplate: baseTemplate, + } +} + +// RegisterRoutes registers admin routes on the given router +func (a *Admin) RegisterRoutes(mux *http.ServeMux) { + // Register admin routes + mux.HandleFunc("/admin/", a.handleIndex) + mux.HandleFunc("/admin/login", a.handleLogin) + mux.HandleFunc("/admin/logout", a.handleLogout) + mux.HandleFunc("/admin/plugins", a.handlePluginList) + mux.HandleFunc("/admin/channels", a.handleChannelList) + mux.HandleFunc("/admin/channels/", a.handleChannelDetail) + mux.HandleFunc("/admin/channelplugins", a.handleChannelPluginList) + mux.HandleFunc("/admin/channelplugins/", a.handleChannelPluginDetailOrDelete) +} + +// getCurrentUser gets the current user from the session +func (a *Admin) getCurrentUser(r *http.Request) *model.User { + session, _ := a.store.Get(r, sessionKey) + + // Check if user is logged in + userID, ok := session.Values["user_id"].(int64) + if !ok { + return nil + } + + // Get user from database + user, err := a.db.GetUserByID(userID) + if err != nil { + return nil + } + + return user +} + +// isLoggedIn checks if the user is logged in +func (a *Admin) isLoggedIn(r *http.Request) bool { + session, _ := a.store.Get(r, sessionKey) + return session.Values["logged_in"] == true +} + +// addFlash adds a flash message to the session +func (a *Admin) addFlash(w http.ResponseWriter, r *http.Request, message string, category string) { + session, _ := a.store.Get(r, sessionKey) + + // Add flash message + flashes := session.Flashes() + if flashes == nil { + flashes = make([]interface{}, 0) + } + + flash := FlashMessage{ + Category: category, + Message: message, + } + + session.AddFlash(flash) + session.Save(r, w) +} + +// getFlashes gets all flash messages from the session +func (a *Admin) getFlashes(w http.ResponseWriter, r *http.Request) []FlashMessage { + session, _ := a.store.Get(r, sessionKey) + + // Get flash messages + flashes := session.Flashes() + messages := make([]FlashMessage, 0, len(flashes)) + + for _, f := range flashes { + if flash, ok := f.(FlashMessage); ok { + messages = append(messages, flash) + } + } + + // Save session to clear flashes + session.Save(r, w) + + return messages +} + +// requireLogin middleware checks if the user is logged in +func (a *Admin) requireLogin(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if !a.isLoggedIn(r) { + http.Redirect(w, r, "/admin/login", http.StatusSeeOther) + return + } + next(w, r) + } +} + +// render renders a template with the given data +func (a *Admin) render(w http.ResponseWriter, r *http.Request, templateName string, data TemplateData) { + // Add current user data + data.User = a.getCurrentUser(r) + data.LoggedIn = a.isLoggedIn(r) + data.Path = r.URL.Path + data.Flash = a.getFlashes(w, r) + + // Get template + tmpl, ok := a.templates[templateName] + if !ok { + http.Error(w, "Template not found", http.StatusInternalServerError) + return + } + + // Render template + w.Header().Set("Content-Type", "text/html; charset=utf-8") + if err := tmpl.Execute(w, data); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + } +} + +// handleIndex handles the admin index route +func (a *Admin) handleIndex(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/admin/" { + http.NotFound(w, r) + return + } + + // Redirect to login if not logged in + if !a.isLoggedIn(r) { + http.Redirect(w, r, "/admin/login", http.StatusSeeOther) + return + } + + // Redirect to channel list + http.Redirect(w, r, "/admin/channels", http.StatusSeeOther) +} + +// handleLogin handles the login route +func (a *Admin) handleLogin(w http.ResponseWriter, r *http.Request) { + // If already logged in, redirect to index + if a.isLoggedIn(r) { + http.Redirect(w, r, "/admin/", http.StatusSeeOther) + return + } + + // Handle login form submission + if r.Method == http.MethodPost { + // Parse form + if err := r.ParseForm(); err != nil { + http.Error(w, "Bad request", http.StatusBadRequest) + return + } + + // Check credentials + username := r.FormValue("username") + password := r.FormValue("password") + + user, err := a.db.CheckCredentials(username, password) + if err != nil || user == nil { + a.addFlash(w, r, "Incorrect credentials", "danger") + http.Redirect(w, r, "/admin/login", http.StatusSeeOther) + return + } + + // Set session + session, _ := a.store.Get(r, sessionKey) + session.Values["logged_in"] = true + session.Values["user_id"] = user.ID + + // Set session expiration + session.Options.MaxAge = 3600 * 24 * 7 // 1 week + session.Save(r, w) + + a.addFlash(w, r, "You were logged in", "success") + + // Redirect to index + next := r.URL.Query().Get("next") + if next == "" { + next = "/admin/" + } + http.Redirect(w, r, next, http.StatusSeeOther) + return + } + + // Render login template + a.render(w, r, "login.html", TemplateData{ + Title: "Login", + }) +} + +// handleLogout handles the logout route +func (a *Admin) handleLogout(w http.ResponseWriter, r *http.Request) { + // Clear session + session, _ := a.store.Get(r, sessionKey) + session.Values = make(map[interface{}]interface{}) + session.Options.MaxAge = -1 // Delete session + session.Save(r, w) + + a.addFlash(w, r, "You were logged out", "success") + + // Redirect to login + http.Redirect(w, r, "/admin/login", http.StatusSeeOther) +} + +// handlePluginList handles the plugin list route +func (a *Admin) handlePluginList(w http.ResponseWriter, r *http.Request) { + // Check if user is logged in + if !a.isLoggedIn(r) { + http.Redirect(w, r, "/admin/login", http.StatusSeeOther) + return + } + + // Get available plugins + plugins := plugin.GetAvailablePlugins() + + // Render template + a.render(w, r, "plugin_list.html", TemplateData{ + Title: "Plugins", + Plugins: plugins, + }) +} + +// handleChannelList handles the channel list route +func (a *Admin) handleChannelList(w http.ResponseWriter, r *http.Request) { + // Check if user is logged in + if !a.isLoggedIn(r) { + http.Redirect(w, r, "/admin/login", http.StatusSeeOther) + return + } + + // Get all channels + channels, err := a.db.GetAllChannels() + if err != nil { + http.Error(w, "Failed to get channels", http.StatusInternalServerError) + return + } + + // Render template + a.render(w, r, "channel_list.html", TemplateData{ + Title: "Channels", + Channels: channels, + }) +} + +// handleChannelDetail handles the channel detail route +func (a *Admin) handleChannelDetail(w http.ResponseWriter, r *http.Request) { + // Check if user is logged in + if !a.isLoggedIn(r) { + http.Redirect(w, r, "/admin/login", http.StatusSeeOther) + return + } + + // Extract channel ID from path + path := r.URL.Path + if path == "/admin/channels/" { + http.Redirect(w, r, "/admin/channels", http.StatusSeeOther) + return + } + + channelID := strings.TrimPrefix(path, "/admin/channels/") + if strings.Contains(channelID, "/") { + // Handle delete request + if strings.HasSuffix(path, "/delete") && r.Method == http.MethodPost { + channelID = strings.TrimSuffix(channelID, "/delete") + + // Delete channel + id, err := strconv.ParseInt(channelID, 10, 64) + if err != nil { + http.Error(w, "Invalid channel ID", http.StatusBadRequest) + return + } + + if err := a.db.DeleteChannel(id); err != nil { + http.Error(w, "Failed to delete channel", http.StatusInternalServerError) + return + } + + a.addFlash(w, r, "Channel removed", "success") + http.Redirect(w, r, "/admin/channels", http.StatusSeeOther) + return + } + + http.NotFound(w, r) + return + } + + // Convert channel ID to int64 + id, err := strconv.ParseInt(channelID, 10, 64) + if err != nil { + http.Error(w, "Invalid channel ID", http.StatusBadRequest) + return + } + + // Handle form submission + if r.Method == http.MethodPost { + // Parse form + if err := r.ParseForm(); err != nil { + http.Error(w, "Bad request", http.StatusBadRequest) + return + } + + // Check if the form was submitted + if r.FormValue("form_submitted") == "true" { + // Update channel + enabled := r.FormValue("enabled") == "true" + if err := a.db.UpdateChannel(id, enabled); err != nil { + http.Error(w, "Failed to update channel", http.StatusInternalServerError) + return + } + + a.addFlash(w, r, "Channel updated", "success") + http.Redirect(w, r, "/admin/channels/"+channelID, http.StatusSeeOther) + return + } + } + + // Get channel + channel, err := a.db.GetChannelByID(id) + if err != nil { + http.Error(w, "Channel not found", http.StatusNotFound) + return + } + + // Get available plugins + plugins := plugin.GetAvailablePlugins() + + // Render template + a.render(w, r, "channel_detail.html", TemplateData{ + Title: "Channel: " + channel.PlatformChannelID, + Channel: channel, + Plugins: plugins, + }) +} + +// handleChannelPluginList handles the channel plugin list route +func (a *Admin) handleChannelPluginList(w http.ResponseWriter, r *http.Request) { + // Check if user is logged in + if !a.isLoggedIn(r) { + http.Redirect(w, r, "/admin/login", http.StatusSeeOther) + return + } + + // Handle form submission + if r.Method == http.MethodPost { + // Parse form + if err := r.ParseForm(); err != nil { + http.Error(w, "Bad request", http.StatusBadRequest) + return + } + + // Extract form data + channelID, err := strconv.ParseInt(r.FormValue("channel_id"), 10, 64) + if err != nil { + http.Error(w, "Invalid channel ID", http.StatusBadRequest) + return + } + + pluginID := r.FormValue("plugin_id") + enabled := r.FormValue("enabled") == "y" + + // Create channel plugin + config := make(map[string]interface{}) + _, err = a.db.CreateChannelPlugin(channelID, pluginID, enabled, config) + if err == db.ErrDuplicated { + a.addFlash(w, r, "Plugin "+pluginID+" is already present on the channel", "danger") + } else if err != nil { + http.Error(w, "Failed to create channel plugin", http.StatusInternalServerError) + return + } else { + a.addFlash(w, r, "Plugin "+pluginID+" added to the channel", "success") + } + + // Redirect back + referer := r.Header.Get("Referer") + if referer == "" { + referer = "/admin/channelplugins" + } + http.Redirect(w, r, referer, http.StatusSeeOther) + return + } + + // Get all channels + channels, err := a.db.GetAllChannels() + if err != nil { + http.Error(w, "Failed to get channels", http.StatusInternalServerError) + return + } + + // Render template + a.render(w, r, "channel_plugins_list.html", TemplateData{ + Title: "Channel Plugins", + Channels: channels, + Plugins: plugin.GetAvailablePlugins(), + }) +} + +// handleChannelPluginDetailOrDelete handles the channel plugin detail or delete route +func (a *Admin) handleChannelPluginDetailOrDelete(w http.ResponseWriter, r *http.Request) { + // Check if user is logged in + if !a.isLoggedIn(r) { + http.Redirect(w, r, "/admin/login", http.StatusSeeOther) + return + } + + // Extract channel plugin ID from path + path := r.URL.Path + if path == "/admin/channelplugins/" { + http.Redirect(w, r, "/admin/channelplugins", http.StatusSeeOther) + return + } + + channelPluginID := strings.TrimPrefix(path, "/admin/channelplugins/") + + // Handle delete request + if strings.HasSuffix(channelPluginID, "/delete") && r.Method == http.MethodPost { + channelPluginID = strings.TrimSuffix(channelPluginID, "/delete") + + // Delete channel plugin + id, err := strconv.ParseInt(channelPluginID, 10, 64) + if err != nil { + http.Error(w, "Invalid channel plugin ID", http.StatusBadRequest) + return + } + + if err := a.db.DeleteChannelPlugin(id); err != nil { + http.Error(w, "Failed to delete channel plugin", http.StatusInternalServerError) + return + } + + a.addFlash(w, r, "Plugin removed", "success") + + // Redirect back + referer := r.Header.Get("Referer") + if referer == "" { + referer = "/admin/channelplugins" + } + http.Redirect(w, r, referer, http.StatusSeeOther) + return + } + + // Handle update request + if r.Method == http.MethodPost { + // Parse form + if err := r.ParseForm(); err != nil { + http.Error(w, "Bad request", http.StatusBadRequest) + return + } + + // Convert channel plugin ID to int64 + id, err := strconv.ParseInt(channelPluginID, 10, 64) + if err != nil { + http.Error(w, "Invalid channel plugin ID", http.StatusBadRequest) + return + } + + // Update channel plugin + enabled := r.FormValue("enabled") == "true" + if err := a.db.UpdateChannelPlugin(id, enabled); err != nil { + http.Error(w, "Failed to update channel plugin", http.StatusInternalServerError) + return + } + + a.addFlash(w, r, "Plugin updated", "success") + + // Redirect back + referer := r.Header.Get("Referer") + if referer == "" { + referer = "/admin/channelplugins" + } + http.Redirect(w, r, referer, http.StatusSeeOther) + return + } + + // Redirect to channel plugins list + http.Redirect(w, r, "/admin/channelplugins", http.StatusSeeOther) +} diff --git a/butterrobot/admin/templates/_base.j2 b/internal/admin/templates/_base.html similarity index 79% rename from butterrobot/admin/templates/_base.j2 rename to internal/admin/templates/_base.html index d1db800..d056ab5 100644 --- a/butterrobot/admin/templates/_base.j2 +++ b/internal/admin/templates/_base.html @@ -4,7 +4,7 @@ - ButterRobot Admin + {{.Title}} - ButterRobot Admin @@ -24,27 +24,27 @@ - {% if session.logged_in %} + {{if .LoggedIn}} + + - + \ No newline at end of file diff --git a/internal/admin/templates/channel_detail.html b/internal/admin/templates/channel_detail.html new file mode 100644 index 0000000..764d7b1 --- /dev/null +++ b/internal/admin/templates/channel_detail.html @@ -0,0 +1,114 @@ +{{define "content"}} +
+ +
+
+
+

Channel Plugins

+
+
+
+ + + + + + + + + + {{range $pluginID, $channelPlugin := .Channel.Plugins}} + + + + + + {{else}} + + + + {{end}} + +
PluginEnabledActions
{{$pluginID}} + {{if $channelPlugin.Enabled}} + Enabled + {{else}} + Disabled + {{end}} + +
+ + +
+
+ +
+
No plugins for this channel
+
+ +
+ +

Add Plugin

+
+ +
+ + +
+
+ +
+ +
+
+
+
+
+{{end}} \ No newline at end of file diff --git a/internal/admin/templates/channel_list.html b/internal/admin/templates/channel_list.html new file mode 100644 index 0000000..c13f2fc --- /dev/null +++ b/internal/admin/templates/channel_list.html @@ -0,0 +1,64 @@ +{{define "content"}} +
+
+
+
+

Channels

+
+
+
+ + + + + + + + + + + + + + {{range .Channels}} + + + + + + + + + + {{else}} + + + + {{end}} + +
IDPlatformChannel IDNameEnabledPluginsActions
{{.ID}}{{.Platform}}{{.PlatformChannelID}}{{.ChannelName}} + {{if .Enabled}} + Enabled + {{else}} + Disabled + {{end}} + + {{$count := len .Plugins}} + {{if eq $count 0}} + No plugins + {{else}} + {{$count}} plugins + {{end}} + + Edit +
+ +
+
No channels found
+
+
+
+
+
+{{end}} \ No newline at end of file diff --git a/internal/admin/templates/channel_plugins_list.html b/internal/admin/templates/channel_plugins_list.html new file mode 100644 index 0000000..b57c60e --- /dev/null +++ b/internal/admin/templates/channel_plugins_list.html @@ -0,0 +1,93 @@ +{{define "content"}} +
+
+
+
+

Channel Plugins

+
+
+
+ + + + + + + + + + + + {{range .Channels}} + {{range $pluginID, $channelPlugin := .Plugins}} + + + + + + + + {{end}} + {{else}} + + + + {{end}} + +
IDChannelPluginEnabledActions
{{$channelPlugin.ID}}{{.ChannelName}}{{$pluginID}} + {{if $channelPlugin.Enabled}} + Enabled + {{else}} + Disabled + {{end}} + +
+ + +
+
+ +
+
No channel plugins found
+
+ +
+ +

Add Plugin to Channel

+
+
+ + +
+
+ + +
+
+ +
+ +
+
+
+
+
+{{end}} \ No newline at end of file diff --git a/internal/admin/templates/index.html b/internal/admin/templates/index.html new file mode 100644 index 0000000..c352721 --- /dev/null +++ b/internal/admin/templates/index.html @@ -0,0 +1,15 @@ +{{define "content"}} +
+
+
+
+

ButterRobot Admin

+
+
+

Welcome to the ButterRobot admin interface.

+

Use the navigation above to manage channels and plugins.

+
+
+
+
+{{end}} \ No newline at end of file diff --git a/internal/admin/templates/login.html b/internal/admin/templates/login.html new file mode 100644 index 0000000..2484a5c --- /dev/null +++ b/internal/admin/templates/login.html @@ -0,0 +1,26 @@ +{{define "content"}} +
+
+
+
+

Login

+
+
+
+
+ + +
+
+ + +
+ +
+
+
+
+
+{{end}} \ No newline at end of file diff --git a/internal/admin/templates/plugin_list.html b/internal/admin/templates/plugin_list.html new file mode 100644 index 0000000..bbb860c --- /dev/null +++ b/internal/admin/templates/plugin_list.html @@ -0,0 +1,45 @@ +{{define "content"}} +
+
+
+
+

Available Plugins

+
+
+
+ + + + + + + + + + + {{range $id, $plugin := .Plugins}} + + + + + + + {{else}} + + + + {{end}} + +
IDNameHelpRequires Config
{{$id}}{{$plugin.GetName}}{{$plugin.GetHelp}} + {{if $plugin.RequiresConfig}} + Yes + {{else}} + No + {{end}} +
No plugins found
+
+
+
+
+
+{{end}} \ No newline at end of file diff --git a/internal/app/app.go b/internal/app/app.go new file mode 100644 index 0000000..8d4ffcd --- /dev/null +++ b/internal/app/app.go @@ -0,0 +1,293 @@ +package app + +import ( + "context" + "encoding/json" + "fmt" + "io" + "log/slog" + "net/http" + "os" + "os/signal" + "strings" + "syscall" + "time" + + "git.nakama.town/fmartingr/butterrobot/internal/admin" + "git.nakama.town/fmartingr/butterrobot/internal/config" + "git.nakama.town/fmartingr/butterrobot/internal/db" + "git.nakama.town/fmartingr/butterrobot/internal/platform" + "git.nakama.town/fmartingr/butterrobot/internal/plugin" + "git.nakama.town/fmartingr/butterrobot/internal/plugin/fun" + "git.nakama.town/fmartingr/butterrobot/internal/plugin/ping" + "git.nakama.town/fmartingr/butterrobot/internal/queue" +) + +// App represents the application +type App struct { + config *config.Config + logger *slog.Logger + db *db.Database + router *http.ServeMux + queue *queue.Queue + admin *admin.Admin +} + +// New creates a new App instance +func New(cfg *config.Config, logger *slog.Logger) (*App, error) { + // Initialize router + router := http.NewServeMux() + + // Initialize database + database, err := db.New(cfg.DatabasePath) + if err != nil { + return nil, fmt.Errorf("failed to initialize database: %w", err) + } + + // Initialize message queue + messageQueue := queue.New(logger) + + // Initialize admin interface + adminInterface := admin.New(cfg, database) + + return &App{ + config: cfg, + logger: logger, + db: database, + router: router, + queue: messageQueue, + admin: adminInterface, + }, nil +} + +// Run starts the application +func (a *App) Run() error { + // Initialize platforms + if err := platform.InitializePlatforms(a.config); err != nil { + return err + } + + // Register built-in plugins + plugin.Register(ping.New()) + plugin.Register(fun.NewCoin()) + plugin.Register(fun.NewDice()) + plugin.Register(fun.NewLoquito()) + + // Initialize routes + a.initializeRoutes() + + // Start message queue worker + a.queue.Start(a.handleMessage) + + // Create server + addr := fmt.Sprintf(":%s", a.config.Port) + srv := &http.Server{ + Addr: addr, + Handler: a.router, + } + + // Start server in a goroutine + go func() { + a.logger.Info("Server starting on", "addr", addr) + if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { + a.logger.Error("Server error", "error", err) + os.Exit(1) + } + }() + + // Wait for interrupt signal + quit := make(chan os.Signal, 1) + signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) + <-quit + + a.logger.Info("Shutting down server...") + + // Create shutdown context with timeout + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + // Shutdown server + if err := srv.Shutdown(ctx); err != nil { + return err + } + + // Stop message queue + a.queue.Stop() + + // Close database connection + if err := a.db.Close(); err != nil { + return err + } + + a.logger.Info("Server stopped") + + return nil +} + +// Initialize HTTP routes +func (a *App) initializeRoutes() { + // Health check endpoint + a.router.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode(map[string]interface{}{}) + }) + + // Platform webhook endpoints + for name := range platform.GetAvailablePlatforms() { + a.logger.Info("Registering webhook endpoint for platform", "platform", name) + platformName := name // Create a copy to avoid closure issues + a.router.HandleFunc("/"+platformName+"/incoming/", a.handleIncomingWebhook) + } + + // Register admin routes + a.admin.RegisterRoutes(a.router) +} + +// Handle incoming webhook +func (a *App) handleIncomingWebhook(w http.ResponseWriter, r *http.Request) { + // Extract platform name from path + platformName := extractPlatformName(r.URL.Path) + + // Check if platform exists + if _, err := platform.Get(platformName); err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(map[string]string{"error": "Unknown platform"}) + return + } + + // Read request body + body, err := io.ReadAll(r.Body) + if err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(map[string]string{"error": "Failed to read request body"}) + return + } + + // Queue message for processing + a.queue.Add(queue.Item{ + Platform: platformName, + Request: map[string]any{ + "path": r.URL.Path, + "json": json.RawMessage(body), + }, + }) + + // Respond with success + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode(map[string]any{}) +} + +// extractPlatformName extracts the platform name from the URL path +func extractPlatformName(path string) string { + // Remove leading slash + path = strings.TrimPrefix(path, "/") + + // Split by slash + parts := strings.Split(path, "/") + + // First part is the platform name + if len(parts) > 0 { + // Special case for Telegram with token in the URL + if parts[0] == "telegram" && len(parts) > 1 && parts[1] == "incoming" { + return "telegram" + } + return parts[0] + } + + return "" +} + +// Handle message processing +func (a *App) handleMessage(item queue.Item) { + // Get platform + p, err := platform.Get(item.Platform) + if err != nil { + a.logger.Error("Error getting platform", "error", err) + return + } + + // Create a new request with the body + bodyJSON, ok := item.Request["json"].(json.RawMessage) + if !ok { + a.logger.Error("Invalid JSON in request") + return + } + + reqPath, ok := item.Request["path"].(string) + if !ok { + a.logger.Error("Invalid path in request") + return + } + + req, err := http.NewRequest("POST", reqPath, strings.NewReader(string(bodyJSON))) + if err != nil { + a.logger.Error("Error creating request", "error", err) + return + } + + req.Header.Set("Content-Type", "application/json") + + // Parse message + message, err := p.ParseIncomingMessage(req) + if err != nil { + a.logger.Error("Error parsing message", "error", err) + return + } + + // Skip if message is from a bot + if message == nil || message.FromBot { + return + } + + // Get or create channel + channel, err := a.db.GetChannelByPlatform(item.Platform, message.Chat) + if err == db.ErrNotFound { + channel, err = a.db.CreateChannel(item.Platform, message.Chat, false, message.Channel.ChannelRaw) + if err != nil { + a.logger.Error("Error creating channel", "error", err) + return + } + } else if err != nil { + a.logger.Error("Error getting channel", "error", err) + return + } + + // Skip if channel is disabled + if !channel.Enabled { + return + } + + // Process message with plugins + for pluginID, channelPlugin := range channel.Plugins { + if !channel.HasEnabledPlugin(pluginID) { + continue + } + + // Get plugin + p, err := plugin.Get(pluginID) + if err != nil { + a.logger.Error("Error getting plugin", "error", err) + continue + } + + // Process message + responses := p.OnMessage(message, channelPlugin.Config) + + // Send responses + platform, err := platform.Get(item.Platform) + if err != nil { + a.logger.Error("Error getting platform", "error", err) + continue + } + + for _, response := range responses { + if err := platform.SendMessage(response); err != nil { + a.logger.Error("Error sending message", "error", err) + } + } + } +} diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..b10f653 --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,59 @@ +package config + +import ( + "os" + "strings" +) + +// Config holds all application configuration +type Config struct { + Debug bool + Hostname string + Port string + LogLevel string + SecretKey string + DatabasePath string + SlackConfig SlackConfig + TelegramConfig TelegramConfig +} + +// SlackConfig holds Slack platform configuration +type SlackConfig struct { + Token string + BotOAuthAccessToken string +} + +// TelegramConfig holds Telegram platform configuration +type TelegramConfig struct { + Token string +} + +// Load loads configuration from environment variables +func Load() (*Config, error) { + config := &Config{ + Debug: getEnv("DEBUG", "n") == "y", + Hostname: getEnv("BUTTERROBOT_HOSTNAME", "butterrobot-dev.int.fmartingr.network"), + Port: getEnv("PORT", "8080"), + LogLevel: getEnv("LOG_LEVEL", "ERROR"), + SecretKey: getEnv("SECRET_KEY", "1234"), + DatabasePath: getEnv("DATABASE_PATH", "butterrobot.db"), + SlackConfig: SlackConfig{ + Token: getEnv("SLACK_TOKEN", ""), + BotOAuthAccessToken: getEnv("SLACK_BOT_OAUTH_ACCESS_TOKEN", ""), + }, + TelegramConfig: TelegramConfig{ + Token: getEnv("TELEGRAM_TOKEN", ""), + }, + } + + return config, nil +} + +// getEnv retrieves an environment variable value or returns a default value +func getEnv(key, defaultValue string) string { + value := os.Getenv(key) + if strings.TrimSpace(value) == "" { + return defaultValue + } + return value +} diff --git a/internal/db/db.go b/internal/db/db.go new file mode 100644 index 0000000..e288bb3 --- /dev/null +++ b/internal/db/db.go @@ -0,0 +1,641 @@ +package db + +import ( + "crypto/sha256" + "database/sql" + "encoding/hex" + "encoding/json" + "errors" + + _ "modernc.org/sqlite" + + "git.nakama.town/fmartingr/butterrobot/internal/model" +) + +var ( + // ErrNotFound is returned when a record is not found + ErrNotFound = errors.New("record not found") + + // ErrDuplicated is returned when a record already exists + ErrDuplicated = errors.New("record already exists") +) + +// Database handles database operations +type Database struct { + db *sql.DB +} + +// New creates a new Database instance +func New(dbPath string) (*Database, error) { + // Open database connection + db, err := sql.Open("sqlite", dbPath) + if err != nil { + return nil, err + } + + // Initialize database + if err := initDatabase(db); err != nil { + return nil, err + } + + return &Database{db: db}, nil +} + +// Close closes the database connection +func (d *Database) Close() error { + return d.db.Close() +} + +// GetChannelByID retrieves a channel by ID +func (d *Database) GetChannelByID(id int64) (*model.Channel, error) { + query := ` + SELECT id, platform, platform_channel_id, enabled, channel_raw + FROM channels + WHERE id = ? + ` + + row := d.db.QueryRow(query, id) + + var ( + platform string + platformChannelID string + enabled bool + channelRawJSON string + ) + + err := row.Scan(&id, &platform, &platformChannelID, &enabled, &channelRawJSON) + if err == sql.ErrNoRows { + return nil, ErrNotFound + } + if err != nil { + return nil, err + } + + // Parse channel_raw JSON + var channelRaw map[string]interface{} + if err := json.Unmarshal([]byte(channelRawJSON), &channelRaw); err != nil { + return nil, err + } + + // Create channel + channel := &model.Channel{ + ID: id, + Platform: platform, + PlatformChannelID: platformChannelID, + Enabled: enabled, + ChannelRaw: channelRaw, + Plugins: make(map[string]*model.ChannelPlugin), + } + + // Get channel plugins + plugins, err := d.GetChannelPlugins(id) + if err != nil && err != ErrNotFound { + return nil, err + } + + for _, plugin := range plugins { + channel.Plugins[plugin.PluginID] = plugin + } + + return channel, nil +} + +// GetChannelByPlatform retrieves a channel by platform and platform channel ID +func (d *Database) GetChannelByPlatform(platform, platformChannelID string) (*model.Channel, error) { + query := ` + SELECT id, platform, platform_channel_id, enabled, channel_raw + FROM channels + WHERE platform = ? AND platform_channel_id = ? + ` + + row := d.db.QueryRow(query, platform, platformChannelID) + + var ( + id int64 + enabled bool + channelRawJSON string + ) + + err := row.Scan(&id, &platform, &platformChannelID, &enabled, &channelRawJSON) + if err == sql.ErrNoRows { + return nil, ErrNotFound + } + if err != nil { + return nil, err + } + + // Parse channel_raw JSON + var channelRaw map[string]interface{} + if err := json.Unmarshal([]byte(channelRawJSON), &channelRaw); err != nil { + return nil, err + } + + // Create channel + channel := &model.Channel{ + ID: id, + Platform: platform, + PlatformChannelID: platformChannelID, + Enabled: enabled, + ChannelRaw: channelRaw, + Plugins: make(map[string]*model.ChannelPlugin), + } + + // Get channel plugins + plugins, err := d.GetChannelPlugins(id) + if err != nil && err != ErrNotFound { + return nil, err + } + + for _, plugin := range plugins { + channel.Plugins[plugin.PluginID] = plugin + } + + return channel, nil +} + +// CreateChannel creates a new channel +func (d *Database) CreateChannel(platform, platformChannelID string, enabled bool, channelRaw map[string]interface{}) (*model.Channel, error) { + // Convert channelRaw to JSON + channelRawJSON, err := json.Marshal(channelRaw) + if err != nil { + return nil, err + } + + // Insert channel + query := ` + INSERT INTO channels (platform, platform_channel_id, enabled, channel_raw) + VALUES (?, ?, ?, ?) + ` + + result, err := d.db.Exec(query, platform, platformChannelID, enabled, string(channelRawJSON)) + if err != nil { + return nil, err + } + + // Get inserted ID + id, err := result.LastInsertId() + if err != nil { + return nil, err + } + + // Create channel + channel := &model.Channel{ + ID: id, + Platform: platform, + PlatformChannelID: platformChannelID, + Enabled: enabled, + ChannelRaw: channelRaw, + Plugins: make(map[string]*model.ChannelPlugin), + } + + return channel, nil +} + +// UpdateChannel updates a channel's enabled status +func (d *Database) UpdateChannel(id int64, enabled bool) error { + query := ` + UPDATE channels + SET enabled = ? + WHERE id = ? + ` + + _, err := d.db.Exec(query, enabled, id) + return err +} + +// DeleteChannel deletes a channel +func (d *Database) DeleteChannel(id int64) error { + // First delete all channel plugins + if err := d.DeleteChannelPluginsByChannel(id); err != nil { + return err + } + + // Then delete the channel + query := ` + DELETE FROM channels + WHERE id = ? + ` + + _, err := d.db.Exec(query, id) + return err +} + +// GetChannelPlugins retrieves all plugins for a channel +func (d *Database) GetChannelPlugins(channelID int64) ([]*model.ChannelPlugin, error) { + query := ` + SELECT id, channel_id, plugin_id, enabled, config + FROM channel_plugin + WHERE channel_id = ? + ` + + rows, err := d.db.Query(query, channelID) + if err != nil { + return nil, err + } + defer rows.Close() + + var plugins []*model.ChannelPlugin + + for rows.Next() { + var ( + id int64 + channelID int64 + pluginID string + enabled bool + configJSON string + ) + + if err := rows.Scan(&id, &channelID, &pluginID, &enabled, &configJSON); err != nil { + return nil, err + } + + // Parse config JSON + var config map[string]interface{} + if err := json.Unmarshal([]byte(configJSON), &config); err != nil { + return nil, err + } + + plugin := &model.ChannelPlugin{ + ID: id, + ChannelID: channelID, + PluginID: pluginID, + Enabled: enabled, + Config: config, + } + + plugins = append(plugins, plugin) + } + + if err := rows.Err(); err != nil { + return nil, err + } + + if len(plugins) == 0 { + return nil, ErrNotFound + } + + return plugins, nil +} + +// GetChannelPluginByID retrieves a channel plugin by ID +func (d *Database) GetChannelPluginByID(id int64) (*model.ChannelPlugin, error) { + query := ` + SELECT id, channel_id, plugin_id, enabled, config + FROM channel_plugin + WHERE id = ? + ` + + row := d.db.QueryRow(query, id) + + var ( + channelID int64 + pluginID string + enabled bool + configJSON string + ) + + err := row.Scan(&id, &channelID, &pluginID, &enabled, &configJSON) + if err == sql.ErrNoRows { + return nil, ErrNotFound + } + if err != nil { + return nil, err + } + + // Parse config JSON + var config map[string]interface{} + if err := json.Unmarshal([]byte(configJSON), &config); err != nil { + return nil, err + } + + return &model.ChannelPlugin{ + ID: id, + ChannelID: channelID, + PluginID: pluginID, + Enabled: enabled, + Config: config, + }, nil +} + +// CreateChannelPlugin creates a new channel plugin +func (d *Database) CreateChannelPlugin(channelID int64, pluginID string, enabled bool, config map[string]interface{}) (*model.ChannelPlugin, error) { + // Check if plugin already exists for this channel + query := ` + SELECT COUNT(*) + FROM channel_plugin + WHERE channel_id = ? AND plugin_id = ? + ` + + var count int + err := d.db.QueryRow(query, channelID, pluginID).Scan(&count) + if err != nil { + return nil, err + } + + if count > 0 { + return nil, ErrDuplicated + } + + // Convert config to JSON + configJSON, err := json.Marshal(config) + if err != nil { + return nil, err + } + + // Insert channel plugin + insertQuery := ` + INSERT INTO channel_plugin (channel_id, plugin_id, enabled, config) + VALUES (?, ?, ?, ?) + ` + + result, err := d.db.Exec(insertQuery, channelID, pluginID, enabled, string(configJSON)) + if err != nil { + return nil, err + } + + // Get inserted ID + id, err := result.LastInsertId() + if err != nil { + return nil, err + } + + return &model.ChannelPlugin{ + ID: id, + ChannelID: channelID, + PluginID: pluginID, + Enabled: enabled, + Config: config, + }, nil +} + +// UpdateChannelPlugin updates a channel plugin's enabled status +func (d *Database) UpdateChannelPlugin(id int64, enabled bool) error { + query := ` + UPDATE channel_plugin + SET enabled = ? + WHERE id = ? + ` + + _, err := d.db.Exec(query, enabled, id) + return err +} + +// DeleteChannelPlugin deletes a channel plugin +func (d *Database) DeleteChannelPlugin(id int64) error { + query := ` + DELETE FROM channel_plugin + WHERE id = ? + ` + + _, err := d.db.Exec(query, id) + return err +} + +// DeleteChannelPluginsByChannel deletes all plugins for a channel +func (d *Database) DeleteChannelPluginsByChannel(channelID int64) error { + query := ` + DELETE FROM channel_plugin + WHERE channel_id = ? + ` + + _, err := d.db.Exec(query, channelID) + return err +} + +// GetAllChannels retrieves all channels +func (d *Database) GetAllChannels() ([]*model.Channel, error) { + query := ` + SELECT id, platform, platform_channel_id, enabled, channel_raw + FROM channels + ` + + rows, err := d.db.Query(query) + if err != nil { + return nil, err + } + defer rows.Close() + + var channels []*model.Channel + + for rows.Next() { + var ( + id int64 + platform string + platformChannelID string + enabled bool + channelRawJSON string + ) + + if err := rows.Scan(&id, &platform, &platformChannelID, &enabled, &channelRawJSON); err != nil { + return nil, err + } + + // Parse channel_raw JSON + var channelRaw map[string]interface{} + if err := json.Unmarshal([]byte(channelRawJSON), &channelRaw); err != nil { + return nil, err + } + + // Create channel + channel := &model.Channel{ + ID: id, + Platform: platform, + PlatformChannelID: platformChannelID, + Enabled: enabled, + ChannelRaw: channelRaw, + Plugins: make(map[string]*model.ChannelPlugin), + } + + // Get channel plugins + plugins, err := d.GetChannelPlugins(id) + if err != nil && err != ErrNotFound { + continue // Skip this channel if plugins can't be retrieved + } + + if plugins != nil { + for _, plugin := range plugins { + channel.Plugins[plugin.PluginID] = plugin + } + } + + channels = append(channels, channel) + } + + if err := rows.Err(); err != nil { + return nil, err + } + + if len(channels) == 0 { + channels = make([]*model.Channel, 0) + } + + return channels, nil +} + +// GetUserByID retrieves a user by ID +func (d *Database) GetUserByID(id int64) (*model.User, error) { + query := ` + SELECT id, username, password + FROM users + WHERE id = ? + ` + + row := d.db.QueryRow(query, id) + + var ( + username string + password string + ) + + err := row.Scan(&id, &username, &password) + if err == sql.ErrNoRows { + return nil, ErrNotFound + } + if err != nil { + return nil, err + } + + return &model.User{ + ID: id, + Username: username, + Password: password, + }, nil +} + +// CreateUser creates a new user +func (d *Database) CreateUser(username, password string) (*model.User, error) { + // Hash password + hashedPassword := hashPassword(password) + + // Insert user + query := ` + INSERT INTO users (username, password) + VALUES (?, ?) + ` + + result, err := d.db.Exec(query, username, hashedPassword) + if err != nil { + return nil, err + } + + // Get inserted ID + id, err := result.LastInsertId() + if err != nil { + return nil, err + } + + return &model.User{ + ID: id, + Username: username, + Password: hashedPassword, + }, nil +} + +// CheckCredentials checks if the username and password are valid +func (d *Database) CheckCredentials(username, password string) (*model.User, error) { + query := ` + SELECT id, username, password + FROM users + WHERE username = ? + ` + + row := d.db.QueryRow(query, username) + + var ( + id int64 + dbUsername string + dbPassword string + ) + + err := row.Scan(&id, &dbUsername, &dbPassword) + if err == sql.ErrNoRows { + return nil, ErrNotFound + } + if err != nil { + return nil, err + } + + // Check password + hashedPassword := hashPassword(password) + if dbPassword != hashedPassword { + return nil, errors.New("invalid credentials") + } + + return &model.User{ + ID: id, + Username: dbUsername, + Password: dbPassword, + }, nil +} + +// Helper function to hash password +func hashPassword(password string) string { + // In a real implementation, use a proper password hashing library like bcrypt + // This is a simplified version for demonstration + hasher := sha256.New() + hasher.Write([]byte(password)) + return hex.EncodeToString(hasher.Sum(nil)) +} + +// Initialize database tables +func initDatabase(db *sql.DB) error { + // Create channels table + _, err := db.Exec(` + CREATE TABLE IF NOT EXISTS channels ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + platform TEXT NOT NULL, + platform_channel_id TEXT NOT NULL, + enabled BOOLEAN NOT NULL DEFAULT 0, + channel_raw TEXT NOT NULL, + UNIQUE(platform, platform_channel_id) + ) + `) + if err != nil { + return err + } + + // Create channel_plugin table + _, err = db.Exec(` + CREATE TABLE IF NOT EXISTS channel_plugin ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + channel_id INTEGER NOT NULL, + plugin_id TEXT NOT NULL, + enabled BOOLEAN NOT NULL DEFAULT 0, + config TEXT NOT NULL DEFAULT '{}', + UNIQUE(channel_id, plugin_id), + FOREIGN KEY (channel_id) REFERENCES channels (id) ON DELETE CASCADE + ) + `) + if err != nil { + return err + } + + // Create users table + _, err = db.Exec(` + CREATE TABLE IF NOT EXISTS users ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + username TEXT NOT NULL UNIQUE, + password TEXT NOT NULL + ) + `) + if err != nil { + return err + } + + // Create default admin user if it doesn't exist + var count int + err = db.QueryRow("SELECT COUNT(*) FROM users").Scan(&count) + if err != nil { + return err + } + + if count == 0 { + hashedPassword := hashPassword("admin") + _, err = db.Exec("INSERT INTO users (username, password) VALUES (?, ?)", "admin", hashedPassword) + if err != nil { + return err + } + } + + return nil +} diff --git a/internal/model/message.go b/internal/model/message.go new file mode 100644 index 0000000..fe8c5e4 --- /dev/null +++ b/internal/model/message.go @@ -0,0 +1,86 @@ +package model + +import ( + "time" +) + +// Message represents a chat message +type Message struct { + Text string + Chat string + Channel *Channel + Author string + FromBot bool + Date time.Time + ID string + ReplyTo string + Raw map[string]interface{} +} + +// Channel represents a chat channel +type Channel struct { + ID int64 + Platform string + PlatformChannelID string + ChannelRaw map[string]interface{} + Enabled bool + Plugins map[string]*ChannelPlugin +} + +// HasEnabledPlugin checks if a plugin is enabled for this channel +func (c *Channel) HasEnabledPlugin(pluginID string) bool { + plugin, exists := c.Plugins[pluginID] + if !exists { + return false + } + return plugin.Enabled +} + +// ChannelName returns the channel name +func (c *Channel) ChannelName() string { + // In a real implementation, this would use the platform-specific + // ParseChannelNameFromRaw function + + // For simplicity, we'll just use the PlatformChannelID if we can't extract a name + // Check if ChannelRaw has a name field + if c.ChannelRaw == nil { + return c.PlatformChannelID + } + + // Check common name fields in ChannelRaw + if name, ok := c.ChannelRaw["name"].(string); ok && name != "" { + return name + } + + // Check for nested objects like "chat" (used by Telegram) + if chat, ok := c.ChannelRaw["chat"].(map[string]interface{}); ok { + // Try different fields in order of preference + if title, ok := chat["title"].(string); ok && title != "" { + return title + } + if username, ok := chat["username"].(string); ok && username != "" { + return username + } + if firstName, ok := chat["first_name"].(string); ok && firstName != "" { + return firstName + } + } + + return c.PlatformChannelID +} + +// ChannelPlugin represents a plugin enabled for a channel +type ChannelPlugin struct { + ID int64 + ChannelID int64 + PluginID string + Enabled bool + Config map[string]interface{} +} + +// User represents an admin user +type User struct { + ID int64 + Username string + Password string +} \ No newline at end of file diff --git a/internal/model/platform.go b/internal/model/platform.go new file mode 100644 index 0000000..01318eb --- /dev/null +++ b/internal/model/platform.go @@ -0,0 +1,46 @@ +package model + +import ( + "errors" + "net/http" + + "git.nakama.town/fmartingr/butterrobot/internal/config" +) + +var ( + // ErrPlatform is a general platform error + ErrPlatform = errors.New("platform error") + + // ErrPlatformInit is an error during platform initialization + ErrPlatformInit = errors.New("platform initialization error") + + // ErrPlatformAuth is an authentication error + ErrPlatformAuth = errors.New("platform authentication error") + + // ErrPlatformNotFound is returned when a requested platform doesn't exist + ErrPlatformNotFound = errors.New("platform not found") +) + +// AuthResponse represents a platform authentication response +type AuthResponse struct { + Data map[string]any + StatusCode int +} + +// Platform defines the interface all chat platforms must implement +type Platform interface { + // Init initializes the platform + Init(cfg *config.Config) error + + // ParseIncomingMessage parses the incoming HTTP request into a Message + ParseIncomingMessage(r *http.Request) (*Message, error) + + // ParseChannelNameFromRaw extracts a human-readable channel name from raw data + ParseChannelNameFromRaw(channelRaw map[string]any) string + + // ParseChannelFromMessage extracts channel data from a message + ParseChannelFromMessage(body []byte) (map[string]any, error) + + // SendMessage sends a message through the platform + SendMessage(msg *Message) error +} diff --git a/internal/model/plugin.go b/internal/model/plugin.go new file mode 100644 index 0000000..ffc3c2f --- /dev/null +++ b/internal/model/plugin.go @@ -0,0 +1,28 @@ +package model + +import ( + "errors" +) + +var ( + // ErrPluginNotFound is returned when a requested plugin doesn't exist + ErrPluginNotFound = errors.New("plugin not found") +) + +// Plugin defines the interface all chat plugins must implement +type Plugin interface { + // GetID returns the plugin ID + GetID() string + + // GetName returns the plugin name + GetName() string + + // GetHelp returns the plugin help text + GetHelp() string + + // RequiresConfig indicates if the plugin requires configuration + RequiresConfig() bool + + // OnMessage processes an incoming message and returns response messages + OnMessage(msg *Message, config map[string]interface{}) []*Message +} \ No newline at end of file diff --git a/internal/platform/init.go b/internal/platform/init.go new file mode 100644 index 0000000..63625ca --- /dev/null +++ b/internal/platform/init.go @@ -0,0 +1,32 @@ +package platform + +import ( + "fmt" + + "git.nakama.town/fmartingr/butterrobot/internal/config" + "git.nakama.town/fmartingr/butterrobot/internal/platform/slack" + "git.nakama.town/fmartingr/butterrobot/internal/platform/telegram" +) + +// InitializePlatforms initializes all available platforms +func InitializePlatforms(cfg *config.Config) error { + // Initialize Slack platform + if cfg.SlackConfig.Token != "" && cfg.SlackConfig.BotOAuthAccessToken != "" { + slackPlatform := slack.New(&cfg.SlackConfig) + if err := slackPlatform.Init(cfg); err == nil { + Register("slack", slackPlatform) + } + } + + // Initialize Telegram platform + if cfg.TelegramConfig.Token != "" { + telegramPlatform := telegram.New(&cfg.TelegramConfig) + if err := telegramPlatform.Init(cfg); err == nil { + Register("telegram", telegramPlatform) + } + } else { + return fmt.Errorf("telegram token is required") + } + + return nil +} diff --git a/internal/platform/registry.go b/internal/platform/registry.go new file mode 100644 index 0000000..b6ce05c --- /dev/null +++ b/internal/platform/registry.go @@ -0,0 +1,49 @@ +package platform + +import ( + "sync" + + "git.nakama.town/fmartingr/butterrobot/internal/model" +) + +var ( + // platforms holds all registered chat platforms + platforms = make(map[string]model.Platform) + + // platformsMu protects the platforms map + platformsMu sync.RWMutex +) + +// Register registers a platform with the given ID +func Register(id string, platform model.Platform) { + platformsMu.Lock() + defer platformsMu.Unlock() + platforms[id] = platform +} + +// Get returns a platform by ID +func Get(id string) (model.Platform, error) { + platformsMu.RLock() + defer platformsMu.RUnlock() + + platform, exists := platforms[id] + if !exists { + return nil, model.ErrPlatformNotFound + } + + return platform, nil +} + +// GetAvailablePlatforms returns all registered platforms +func GetAvailablePlatforms() map[string]model.Platform { + platformsMu.RLock() + defer platformsMu.RUnlock() + + // Create a copy to avoid race conditions + result := make(map[string]model.Platform, len(platforms)) + for id, platform := range platforms { + result[id] = platform + } + + return result +} diff --git a/internal/platform/slack/slack.go b/internal/platform/slack/slack.go new file mode 100644 index 0000000..3683ada --- /dev/null +++ b/internal/platform/slack/slack.go @@ -0,0 +1,212 @@ +package slack + +import ( + "encoding/json" + "errors" + "fmt" + "io/ioutil" + "net/http" + "strings" + "time" + + "git.nakama.town/fmartingr/butterrobot/internal/config" + "git.nakama.town/fmartingr/butterrobot/internal/model" +) + +// SlackPlatform implements the Platform interface for Slack +type SlackPlatform struct { + config *config.SlackConfig +} + +// New creates a new SlackPlatform instance +func New(cfg *config.SlackConfig) *SlackPlatform { + return &SlackPlatform{ + config: cfg, + } +} + +// Init initializes the Slack platform +func (s *SlackPlatform) Init(_ *config.Config) error { + // Validate config + if s.config.Token == "" || s.config.BotOAuthAccessToken == "" { + return model.ErrPlatformInit + } + return nil +} + +// ParseIncomingMessage parses an incoming Slack message +func (s *SlackPlatform) ParseIncomingMessage(r *http.Request) (*model.Message, error) { + // Read request body + body, err := ioutil.ReadAll(r.Body) + if err != nil { + return nil, err + } + defer r.Body.Close() + + // Parse JSON + var requestData map[string]interface{} + if err := json.Unmarshal(body, &requestData); err != nil { + return nil, err + } + + // Verify Slack request + // This is a simplified version, production should include signature verification + urlVerify, ok := requestData["type"] + if ok && urlVerify == "url_verification" { + return nil, errors.New("url verification") // Handle separately + } + + // Process event + event, ok := requestData["event"].(map[string]interface{}) + if !ok { + return nil, errors.New("invalid event") + } + + // Create message + msg := &model.Message{ + Raw: requestData, + } + + // Get text + if text, ok := event["text"].(string); ok { + msg.Text = text + } + + // Get channel + if channel, ok := event["channel"].(string); ok { + msg.Chat = channel + + // Create Channel object + channelRaw, err := s.ParseChannelFromMessage(body) + if err != nil { + return nil, err + } + + msg.Channel = &model.Channel{ + Platform: "slack", + PlatformChannelID: channel, + ChannelRaw: channelRaw, + } + } + + // Check if from bot + if botID, ok := event["bot_id"].(string); ok && botID != "" { + msg.FromBot = true + } + + // Get user + if user, ok := event["user"].(string); ok { + msg.Author = user + } + + // Get timestamp + if ts, ok := event["ts"].(string); ok { + // Convert Unix timestamp + parts := strings.Split(ts, ".") + if len(parts) > 0 { + if sec, err := parseInt64(parts[0]); err == nil { + msg.Date = time.Unix(sec, 0) + msg.ID = ts + } + } + } + + return msg, nil +} + +// ParseChannelNameFromRaw extracts a human-readable channel name from raw data +func (s *SlackPlatform) ParseChannelNameFromRaw(channelRaw map[string]interface{}) string { + // Extract name from channel raw data + if name, ok := channelRaw["name"].(string); ok { + return name + } + + // Fallback to ID if available + if id, ok := channelRaw["id"].(string); ok { + return id + } + + return "unknown" +} + +// ParseChannelFromMessage extracts channel data from a message +func (s *SlackPlatform) ParseChannelFromMessage(body []byte) (map[string]any, error) { + // Parse JSON + var requestData map[string]interface{} + if err := json.Unmarshal(body, &requestData); err != nil { + return nil, err + } + + // Extract channel info from event + event, ok := requestData["event"].(map[string]interface{}) + if !ok { + return nil, errors.New("invalid event data") + } + + channelID, ok := event["channel"].(string) + if !ok { + return nil, errors.New("channel ID not found") + } + + // In a real implementation, you might want to fetch more details about the channel + // using the Slack API, but for simplicity we'll just return the ID + channelRaw := map[string]interface{}{ + "id": channelID, + } + + return channelRaw, nil +} + +// SendMessage sends a message to Slack +func (s *SlackPlatform) SendMessage(msg *model.Message) error { + if s.config.BotOAuthAccessToken == "" { + return errors.New("bot token not configured") + } + + // Prepare payload + payload := map[string]interface{}{ + "channel": msg.Chat, + "text": msg.Text, + } + + // Add thread_ts if it's a reply + if msg.ReplyTo != "" { + payload["thread_ts"] = msg.ReplyTo + } + + // Convert payload to JSON + data, err := json.Marshal(payload) + if err != nil { + return err + } + + // Send HTTP request + req, err := http.NewRequest("POST", "https://slack.com/api/chat.postMessage", strings.NewReader(string(data))) + if err != nil { + return err + } + + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", s.config.BotOAuthAccessToken)) + + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + + // Check response + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("slack API error: %d", resp.StatusCode) + } + + return nil +} + +// Helper function to parse int64 +func parseInt64(s string) (int64, error) { + var n int64 + _, err := fmt.Sscanf(s, "%d", &n) + return n, err +} diff --git a/internal/platform/telegram/telegram.go b/internal/platform/telegram/telegram.go new file mode 100644 index 0000000..a9ff2db --- /dev/null +++ b/internal/platform/telegram/telegram.go @@ -0,0 +1,262 @@ +package telegram + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" + "net/http" + "os" + "strconv" + "time" + + "git.nakama.town/fmartingr/butterrobot/internal/config" + "git.nakama.town/fmartingr/butterrobot/internal/model" +) + +// TelegramPlatform implements the Platform interface for Telegram +type TelegramPlatform struct { + config *config.TelegramConfig + apiURL string + log *slog.Logger +} + +// New creates a new TelegramPlatform instance +func New(cfg *config.TelegramConfig) *TelegramPlatform { + return &TelegramPlatform{ + config: cfg, + apiURL: "https://api.telegram.org/bot" + cfg.Token, + log: slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug})).With(slog.String("platform", "telegram")), + } +} + +// Init initializes the Telegram platform +func (t *TelegramPlatform) Init(cfg *config.Config) error { + if t.config.Token == "" { + t.log.Error("Missing Telegram token") + return model.ErrPlatformInit + } + + // Set webhook URL based on hostname + webhookURL := fmt.Sprintf("https://%s/telegram/incoming/%s", cfg.Hostname, t.config.Token) + t.log.Info("Setting Telegram webhook", "url", webhookURL) + + // Create webhook setup request + url := fmt.Sprintf("%s/setWebhook", t.apiURL) + payload := map[string]interface{}{ + "url": webhookURL, + "max_connections": 40, + "allowed_updates": []string{"message"}, + } + + data, err := json.Marshal(payload) + if err != nil { + t.log.Error("Failed to marshal webhook payload", "error", err) + return fmt.Errorf("failed to marshal webhook payload: %w", err) + } + + resp, err := http.Post(url, "application/json", bytes.NewBuffer(data)) + if err != nil { + t.log.Error("Failed to set webhook", "error", err) + return fmt.Errorf("failed to set webhook: %w", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + bodyBytes, _ := io.ReadAll(resp.Body) + errMsg := string(bodyBytes) + t.log.Error("Telegram API error", "status", resp.StatusCode, "response", errMsg) + return fmt.Errorf("telegram API error: %d - %s", resp.StatusCode, errMsg) + } + + t.log.Info("Telegram webhook successfully set") + return nil +} + +// ParseIncomingMessage parses an incoming Telegram message +func (t *TelegramPlatform) ParseIncomingMessage(r *http.Request) (*model.Message, error) { + t.log.Debug("Parsing incoming Telegram message") + + // Read request body + body, err := io.ReadAll(r.Body) + if err != nil { + t.log.Error("Failed to read request body", "error", err) + return nil, err + } + defer r.Body.Close() + + // Parse JSON + var update struct { + Message struct { + MessageID int `json:"message_id"` + From struct { + ID int `json:"id"` + IsBot bool `json:"is_bot"` + Username string `json:"username"` + FirstName string `json:"first_name"` + } `json:"from"` + Chat struct { + ID int64 `json:"id"` + Type string `json:"type"` + Title string `json:"title,omitempty"` + Username string `json:"username,omitempty"` + } `json:"chat"` + Date int `json:"date"` + Text string `json:"text"` + } `json:"message"` + } + + if err := json.Unmarshal(body, &update); err != nil { + t.log.Error("Failed to unmarshal update", "error", err) + return nil, err + } + + // Convert to raw map for storage + var raw map[string]interface{} + if err := json.Unmarshal(body, &raw); err != nil { + t.log.Error("Failed to unmarshal raw data", "error", err) + return nil, err + } + + // Create message + msg := &model.Message{ + Text: update.Message.Text, + Chat: strconv.FormatInt(update.Message.Chat.ID, 10), + Author: update.Message.From.Username, + FromBot: update.Message.From.IsBot, + Date: time.Unix(int64(update.Message.Date), 0), + ID: strconv.Itoa(update.Message.MessageID), + Raw: raw, + } + + t.log.Debug("Parsed message", + "id", msg.ID, + "chat", msg.Chat, + "author", msg.Author, + "from_bot", msg.FromBot, + "text_length", len(msg.Text)) + + // Create Channel object + channelRaw, err := t.ParseChannelFromMessage(body) + if err != nil { + t.log.Error("Failed to parse channel data", "error", err) + return nil, err + } + + msg.Channel = &model.Channel{ + Platform: "telegram", + PlatformChannelID: msg.Chat, + ChannelRaw: channelRaw, + } + + return msg, nil +} + +// ParseChannelNameFromRaw extracts a human-readable channel name from raw data +func (t *TelegramPlatform) ParseChannelNameFromRaw(channelRaw map[string]interface{}) string { + // Try to get the title first (for groups) + if chatInfo, ok := channelRaw["chat"].(map[string]interface{}); ok { + if title, ok := chatInfo["title"].(string); ok && title != "" { + return title + } + + // For private chats, use username + if username, ok := chatInfo["username"].(string); ok && username != "" { + return username + } + + // Fallback to first_name if available + if firstName, ok := chatInfo["first_name"].(string); ok && firstName != "" { + return firstName + } + + // Last resort: use the ID + if id, ok := chatInfo["id"].(float64); ok { + return strconv.FormatInt(int64(id), 10) + } + } + + return "unknown" +} + +// ParseChannelFromMessage extracts channel data from a message +func (t *TelegramPlatform) ParseChannelFromMessage(body []byte) (map[string]any, error) { + // Parse JSON to extract chat info + var update struct { + Message struct { + Chat map[string]any `json:"chat"` + } `json:"message"` + } + + if err := json.Unmarshal(body, &update); err != nil { + return nil, err + } + + if update.Message.Chat == nil { + return nil, errors.New("chat information not found") + } + + return map[string]any{ + "chat": update.Message.Chat, + }, nil +} + +// SendMessage sends a message to Telegram +func (t *TelegramPlatform) SendMessage(msg *model.Message) error { + // Convert chat ID to int64 + chatID, err := strconv.ParseInt(msg.Chat, 10, 64) + if err != nil { + t.log.Error("Failed to parse chat ID", "chat", msg.Chat, "error", err) + return err + } + + // Prepare payload + payload := map[string]interface{}{ + "chat_id": chatID, + "text": msg.Text, + } + + // Add reply if needed + if msg.ReplyTo != "" { + replyToID, err := strconv.Atoi(msg.ReplyTo) + if err == nil { + payload["reply_to_message_id"] = replyToID + } else { + t.log.Warn("Failed to parse reply_to ID", "reply_to", msg.ReplyTo, "error", err) + } + } + + t.log.Debug("Sending message to Telegram", "chat_id", chatID, "length", len(msg.Text)) + + // Convert payload to JSON + data, err := json.Marshal(payload) + if err != nil { + t.log.Error("Failed to marshal message payload", "error", err) + return err + } + + // Send HTTP request + resp, err := http.Post( + t.apiURL+"/sendMessage", + "application/json", + bytes.NewBuffer(data), + ) + if err != nil { + t.log.Error("Failed to send message", "error", err) + return err + } + defer resp.Body.Close() + + // Check response + if resp.StatusCode != http.StatusOK { + bodyBytes, _ := io.ReadAll(resp.Body) + errMsg := string(bodyBytes) + t.log.Error("Telegram API error", "status", resp.StatusCode, "response", errMsg) + return fmt.Errorf("telegram API error: %d - %s", resp.StatusCode, errMsg) + } + + t.log.Debug("Message sent successfully") + return nil +} \ No newline at end of file diff --git a/internal/plugin/fun/coin.go b/internal/plugin/fun/coin.go new file mode 100644 index 0000000..8e12a8d --- /dev/null +++ b/internal/plugin/fun/coin.go @@ -0,0 +1,50 @@ +package fun + +import ( + "math/rand" + "strings" + "time" + + "git.nakama.town/fmartingr/butterrobot/internal/model" + "git.nakama.town/fmartingr/butterrobot/internal/plugin" +) + +// CoinPlugin flips a coin +type CoinPlugin struct { + plugin.BasePlugin + rand *rand.Rand +} + +// NewCoin creates a new CoinPlugin instance +func NewCoin() *CoinPlugin { + source := rand.NewSource(time.Now().UnixNano()) + return &CoinPlugin{ + BasePlugin: plugin.BasePlugin{ + ID: "fun.coin", + Name: "Coin Flip", + Help: "Flips a coin when you type 'flip a coin'", + }, + rand: rand.New(source), + } +} + +// OnMessage handles incoming messages +func (p *CoinPlugin) OnMessage(msg *model.Message, config map[string]interface{}) []*model.Message { + if !strings.Contains(strings.ToLower(msg.Text), "flip a coin") { + return nil + } + + result := "Heads" + if p.rand.Intn(2) == 0 { + result = "Tails" + } + + response := &model.Message{ + Text: result, + Chat: msg.Chat, + ReplyTo: msg.ID, + Channel: msg.Channel, + } + + return []*model.Message{response} +} diff --git a/internal/plugin/fun/dice.go b/internal/plugin/fun/dice.go new file mode 100644 index 0000000..00fc7cc --- /dev/null +++ b/internal/plugin/fun/dice.go @@ -0,0 +1,118 @@ +package fun + +import ( + "fmt" + "math/rand" + "regexp" + "strconv" + "strings" + "time" + + "git.nakama.town/fmartingr/butterrobot/internal/model" + "git.nakama.town/fmartingr/butterrobot/internal/plugin" +) + +// DicePlugin rolls dice based on standard dice notation +type DicePlugin struct { + plugin.BasePlugin + rand *rand.Rand +} + +// NewDice creates a new DicePlugin instance +func NewDice() *DicePlugin { + source := rand.NewSource(time.Now().UnixNano()) + return &DicePlugin{ + BasePlugin: plugin.BasePlugin{ + ID: "fun.dice", + Name: "Dice Roller", + Help: "Rolls dice when you type '!dice [formula]' (default: 1d20)", + }, + rand: rand.New(source), + } +} + +// OnMessage handles incoming messages +func (p *DicePlugin) OnMessage(msg *model.Message, config map[string]interface{}) []*model.Message { + if !strings.HasPrefix(strings.TrimSpace(strings.ToLower(msg.Text)), "!dice") { + return nil + } + + // Extract dice formula + formula := strings.TrimSpace(strings.TrimPrefix(msg.Text, "!dice")) + formula = strings.TrimSpace(strings.TrimPrefix(formula, "!dice")) + + if formula == "" { + formula = "1d20" // Default formula + } + + // Parse and roll the dice + result, err := p.rollDice(formula) + responseText := "" + + if err != nil { + responseText = fmt.Sprintf("Error: %s", err.Error()) + } else { + responseText = fmt.Sprintf("%d", result) + } + + response := &model.Message{ + Text: responseText, + Chat: msg.Chat, + ReplyTo: msg.ID, + Channel: msg.Channel, + } + + return []*model.Message{response} +} + +// rollDice parses a dice formula string and returns the result +func (p *DicePlugin) rollDice(formula string) (int, error) { + // Support basic dice notation like "2d6", "1d20+5", etc. + diceRegex := regexp.MustCompile(`^(\d+)d(\d+)(?:([+-])(\d+))?$`) + matches := diceRegex.FindStringSubmatch(formula) + + if matches == nil { + return 0, fmt.Errorf("invalid dice formula: %s", formula) + } + + // Parse number of dice + numDice, err := strconv.Atoi(matches[1]) + if err != nil || numDice < 1 { + return 0, fmt.Errorf("invalid number of dice") + } + if numDice > 100 { + return 0, fmt.Errorf("too many dice (max 100)") + } + + // Parse number of sides + sides, err := strconv.Atoi(matches[2]) + if err != nil || sides < 1 { + return 0, fmt.Errorf("invalid number of sides") + } + if sides > 1000 { + return 0, fmt.Errorf("too many sides (max 1000)") + } + + // Roll the dice + total := 0 + for i := 0; i < numDice; i++ { + roll := p.rand.Intn(sides) + 1 + total += roll + } + + // Apply modifier if present + if len(matches) > 3 && matches[3] != "" { + modifier, err := strconv.Atoi(matches[4]) + if err != nil { + return 0, fmt.Errorf("invalid modifier") + } + + if matches[3] == "+" { + total += modifier + } else if matches[3] == "-" { + total -= modifier + } + } + + return total, nil +} diff --git a/internal/plugin/fun/loquito.go b/internal/plugin/fun/loquito.go new file mode 100644 index 0000000..7b0ea43 --- /dev/null +++ b/internal/plugin/fun/loquito.go @@ -0,0 +1,40 @@ +package fun + +import ( + "strings" + + "git.nakama.town/fmartingr/butterrobot/internal/model" + "git.nakama.town/fmartingr/butterrobot/internal/plugin" +) + +// LoquitoPlugin replies with "Loquito tu." when someone says "lo quito" +type LoquitoPlugin struct { + plugin.BasePlugin +} + +// NewLoquito creates a new LoquitoPlugin instance +func NewLoquito() *LoquitoPlugin { + return &LoquitoPlugin{ + BasePlugin: plugin.BasePlugin{ + ID: "fun.loquito", + Name: "Loquito Reply", + Help: "Replies with 'Loquito tu.' when someone says 'lo quito'", + }, + } +} + +// OnMessage handles incoming messages +func (p *LoquitoPlugin) OnMessage(msg *model.Message, config map[string]interface{}) []*model.Message { + if !strings.Contains(strings.ToLower(msg.Text), "lo quito") { + return nil + } + + response := &model.Message{ + Text: "Loquito tu.", + Chat: msg.Chat, + ReplyTo: msg.ID, + Channel: msg.Channel, + } + + return []*model.Message{response} +} diff --git a/internal/plugin/ping/ping.go b/internal/plugin/ping/ping.go new file mode 100644 index 0000000..b09caaf --- /dev/null +++ b/internal/plugin/ping/ping.go @@ -0,0 +1,40 @@ +package ping + +import ( + "strings" + + "git.nakama.town/fmartingr/butterrobot/internal/model" + "git.nakama.town/fmartingr/butterrobot/internal/plugin" +) + +// PingPlugin is a simple ping/pong plugin +type PingPlugin struct { + plugin.BasePlugin +} + +// New creates a new PingPlugin instance +func New() *PingPlugin { + return &PingPlugin{ + BasePlugin: plugin.BasePlugin{ + ID: "dev.ping", + Name: "Ping", + Help: "Responds to 'ping' with 'pong'", + }, + } +} + +// OnMessage handles incoming messages +func (p *PingPlugin) OnMessage(msg *model.Message, config map[string]interface{}) []*model.Message { + if !strings.EqualFold(strings.TrimSpace(msg.Text), "ping") { + return nil + } + + response := &model.Message{ + Text: "pong", + Chat: msg.Chat, + ReplyTo: msg.ID, + Channel: msg.Channel, + } + + return []*model.Message{response} +} diff --git a/internal/plugin/plugin.go b/internal/plugin/plugin.go new file mode 100644 index 0000000..69da2c2 --- /dev/null +++ b/internal/plugin/plugin.go @@ -0,0 +1,82 @@ +package plugin + +import ( + "sync" + + "git.nakama.town/fmartingr/butterrobot/internal/model" +) + +var ( + // plugins holds all registered plugins + plugins = make(map[string]model.Plugin) + + // pluginsMu protects the plugins map + pluginsMu sync.RWMutex +) + +// Register registers a plugin with the given ID +func Register(plugin model.Plugin) { + pluginsMu.Lock() + defer pluginsMu.Unlock() + plugins[plugin.GetID()] = plugin +} + +// Get returns a plugin by ID +func Get(id string) (model.Plugin, error) { + pluginsMu.RLock() + defer pluginsMu.RUnlock() + + plugin, exists := plugins[id] + if !exists { + return nil, model.ErrPluginNotFound + } + + return plugin, nil +} + +// GetAvailablePlugins returns all registered plugins +func GetAvailablePlugins() map[string]model.Plugin { + pluginsMu.RLock() + defer pluginsMu.RUnlock() + + // Create a copy to avoid race conditions + result := make(map[string]model.Plugin, len(plugins)) + for id, plugin := range plugins { + result[id] = plugin + } + + return result +} + +// BasePlugin provides a common base for plugins +type BasePlugin struct { + ID string + Name string + Help string + ConfigRequired bool +} + +// GetID returns the plugin ID +func (p *BasePlugin) GetID() string { + return p.ID +} + +// GetName returns the plugin name +func (p *BasePlugin) GetName() string { + return p.Name +} + +// GetHelp returns the plugin help text +func (p *BasePlugin) GetHelp() string { + return p.Help +} + +// RequiresConfig indicates if the plugin requires configuration +func (p *BasePlugin) RequiresConfig() bool { + return p.ConfigRequired +} + +// OnMessage is the default implementation that does nothing +func (p *BasePlugin) OnMessage(msg *model.Message, config map[string]interface{}) []*model.Message { + return nil +} diff --git a/internal/queue/queue.go b/internal/queue/queue.go new file mode 100644 index 0000000..668bf60 --- /dev/null +++ b/internal/queue/queue.go @@ -0,0 +1,99 @@ +package queue + +import ( + "log/slog" + "sync" +) + +// Item represents a queue item +type Item struct { + Platform string + Request map[string]interface{} +} + +// HandlerFunc defines a function that processes queue items +type HandlerFunc func(item Item) + +// Queue represents a message queue +type Queue struct { + items chan Item + wg sync.WaitGroup + quit chan struct{} + logger *slog.Logger + running bool + runMutex sync.Mutex +} + +// New creates a new Queue instance +func New(logger *slog.Logger) *Queue { + return &Queue{ + items: make(chan Item, 100), + quit: make(chan struct{}), + logger: logger, + } +} + +// Start starts processing queue items +func (q *Queue) Start(handler HandlerFunc) { + q.runMutex.Lock() + defer q.runMutex.Unlock() + + if q.running { + return + } + + q.running = true + + // Start worker + q.wg.Add(1) + go q.worker(handler) +} + +// Stop stops processing queue items +func (q *Queue) Stop() { + q.runMutex.Lock() + defer q.runMutex.Unlock() + + if !q.running { + return + } + + q.running = false + close(q.quit) + q.wg.Wait() +} + +// Add adds an item to the queue +func (q *Queue) Add(item Item) { + select { + case q.items <- item: + // Item added successfully + default: + // Queue is full + q.logger.Info("Queue is full, dropping message") + } +} + +// worker processes queue items +func (q *Queue) worker(handler HandlerFunc) { + defer q.wg.Done() + + for { + select { + case item := <-q.items: + // Process item + func() { + defer func() { + if r := recover(); r != nil { + q.logger.Error("Panic in queue worker", "error", r) + } + }() + + handler(item) + }() + case <-q.quit: + // Quit worker + return + } + } +} \ No newline at end of file diff --git a/poetry.lock b/poetry.lock deleted file mode 100644 index 35ed11d..0000000 --- a/poetry.lock +++ /dev/null @@ -1,1327 +0,0 @@ -# This file is automatically @generated by Poetry and should not be changed by hand. - -[[package]] -name = "alembic" -version = "1.4.3" -description = "A database migration tool for SQLAlchemy." -category = "main" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" -files = [ - {file = "alembic-1.4.3-py2.py3-none-any.whl", hash = "sha256:4e02ed2aa796bd179965041afa092c55b51fb077de19d61835673cc80672c01c"}, - {file = "alembic-1.4.3.tar.gz", hash = "sha256:5334f32314fb2a56d86b4c4dd1ae34b08c03cae4cb888bc699942104d66bc245"}, -] - -[package.dependencies] -Mako = "*" -python-dateutil = "*" -python-editor = ">=0.3" -SQLAlchemy = ">=1.1.0" - -[[package]] -name = "appdirs" -version = "1.4.4" -description = "A small Python module for determining appropriate platform-specific dirs, e.g. a \"user data dir\"." -category = "dev" -optional = false -python-versions = "*" -files = [ - {file = "appdirs-1.4.4-py2.py3-none-any.whl", hash = "sha256:a841dacd6b99318a741b166adb07e19ee71a274450e68237b4650ca1055ab128"}, - {file = "appdirs-1.4.4.tar.gz", hash = "sha256:7d5d0167b2b1ba821647616af46a749d1c653740dd0d2415100fe26e27afdf41"}, -] - -[[package]] -name = "appnope" -version = "0.1.2" -description = "Disable App Nap on macOS >= 10.9" -category = "dev" -optional = false -python-versions = "*" -files = [ - {file = "appnope-0.1.2-py2.py3-none-any.whl", hash = "sha256:93aa393e9d6c54c5cd570ccadd8edad61ea0c4b9ea7a01409020c9aa019eb442"}, - {file = "appnope-0.1.2.tar.gz", hash = "sha256:dd83cd4b5b460958838f6eb3000c660b1f9caf2a5b1de4264e941512f603258a"}, -] - -[[package]] -name = "atomicwrites" -version = "1.4.0" -description = "Atomic file writes." -category = "dev" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" -files = [ - {file = "atomicwrites-1.4.0-py2.py3-none-any.whl", hash = "sha256:6d1784dea7c0c8d4a5172b6c620f40b6e4cbfdf96d783691f2e1302a7b88e197"}, - {file = "atomicwrites-1.4.0.tar.gz", hash = "sha256:ae70396ad1a434f9c7046fd2dd196fc04b12f9e91ffb859164193be8b6168a7a"}, -] - -[[package]] -name = "attrs" -version = "20.3.0" -description = "Classes Without Boilerplate" -category = "dev" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" -files = [ - {file = "attrs-20.3.0-py2.py3-none-any.whl", hash = "sha256:31b2eced602aa8423c2aea9c76a724617ed67cf9513173fd3a4f03e3a929c7e6"}, - {file = "attrs-20.3.0.tar.gz", hash = "sha256:832aa3cde19744e49938b91fea06d69ecb9e649c93ba974535d08ad92164f700"}, -] - -[package.extras] -dev = ["coverage[toml] (>=5.0.2)", "furo", "hypothesis", "pre-commit", "pympler", "pytest (>=4.3.0)", "six", "sphinx", "zope.interface"] -docs = ["furo", "sphinx", "zope.interface"] -tests = ["coverage[toml] (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "six", "zope.interface"] -tests-no-zope = ["coverage[toml] (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "six"] - -[[package]] -name = "backcall" -version = "0.2.0" -description = "Specifications for callback functions passed in to an API" -category = "dev" -optional = false -python-versions = "*" -files = [ - {file = "backcall-0.2.0-py2.py3-none-any.whl", hash = "sha256:fbbce6a29f263178a1f7915c1940bde0ec2b2a967566fe1c65c1dfb7422bd255"}, - {file = "backcall-0.2.0.tar.gz", hash = "sha256:5cbdbf27be5e7cfadb448baf0aa95508f91f2bbc6c6437cd9cd06e2a4c215e1e"}, -] - -[[package]] -name = "banal" -version = "1.0.1" -description = "Commons of banal micro-functions for Python." -category = "main" -optional = false -python-versions = "*" -files = [ - {file = "banal-1.0.1-py2.py3-none-any.whl", hash = "sha256:6431876cda7b8ff27b1a64fef3a4bdc1f3f54f8dff7beaa93241e01336a0e91d"}, - {file = "banal-1.0.1.tar.gz", hash = "sha256:5541e7c98ea04841f4ff2887bbc3f2dccf982549a99d01c0939aac250fffcf7a"}, -] - -[[package]] -name = "black" -version = "19.10b0" -description = "The uncompromising code formatter." -category = "dev" -optional = false -python-versions = ">=3.6" -files = [ - {file = "black-19.10b0-py36-none-any.whl", hash = "sha256:1b30e59be925fafc1ee4565e5e08abef6b03fe455102883820fe5ee2e4734e0b"}, - {file = "black-19.10b0.tar.gz", hash = "sha256:c2edb73a08e9e0e6f65a0e6af18b059b8b1cdd5bef997d7a0b181df93dc81539"}, -] - -[package.dependencies] -appdirs = "*" -attrs = ">=18.1.0" -click = ">=6.5" -pathspec = ">=0.6,<1" -regex = "*" -toml = ">=0.9.4" -typed-ast = ">=1.4.0" - -[package.extras] -d = ["aiohttp (>=3.3.2)", "aiohttp-cors"] - -[[package]] -name = "certifi" -version = "2022.12.7" -description = "Python package for providing Mozilla's CA Bundle." -category = "main" -optional = false -python-versions = ">=3.6" -files = [ - {file = "certifi-2022.12.7-py3-none-any.whl", hash = "sha256:4ad3232f5e926d6718ec31cfc1fcadfde020920e278684144551c91769c7bc18"}, - {file = "certifi-2022.12.7.tar.gz", hash = "sha256:35824b4c3a97115964b408844d64aa14db1cc518f6562e8d7261699d1350a9e3"}, -] - -[[package]] -name = "cfgv" -version = "3.2.0" -description = "Validate configuration and produce human readable error messages." -category = "dev" -optional = false -python-versions = ">=3.6.1" -files = [ - {file = "cfgv-3.2.0-py2.py3-none-any.whl", hash = "sha256:32e43d604bbe7896fe7c248a9c2276447dbef840feb28fe20494f62af110211d"}, - {file = "cfgv-3.2.0.tar.gz", hash = "sha256:cf22deb93d4bcf92f345a5c3cd39d3d41d6340adc60c78bbbd6588c384fda6a1"}, -] - -[[package]] -name = "chardet" -version = "3.0.4" -description = "Universal encoding detector for Python 2 and 3" -category = "main" -optional = false -python-versions = "*" -files = [ - {file = "chardet-3.0.4-py2.py3-none-any.whl", hash = "sha256:fc323ffcaeaed0e0a02bf4d117757b98aed530d9ed4531e3e15460124c106691"}, - {file = "chardet-3.0.4.tar.gz", hash = "sha256:84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae"}, -] - -[[package]] -name = "click" -version = "7.1.2" -description = "Composable command line interface toolkit" -category = "main" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" -files = [ - {file = "click-7.1.2-py2.py3-none-any.whl", hash = "sha256:dacca89f4bfadd5de3d7489b7c8a566eee0d3676333fbb50030263894c38c0dc"}, - {file = "click-7.1.2.tar.gz", hash = "sha256:d2b5255c7c6349bc1bd1e59e08cd12acbbd63ce649f2588755783aa94dfb6b1a"}, -] - -[[package]] -name = "colorama" -version = "0.4.4" -description = "Cross-platform colored terminal text." -category = "main" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" -files = [ - {file = "colorama-0.4.4-py2.py3-none-any.whl", hash = "sha256:9f47eda37229f68eee03b24b9748937c7dc3868f906e8ba69fbcbdd3bc5dc3e2"}, - {file = "colorama-0.4.4.tar.gz", hash = "sha256:5941b2b48a20143d2267e95b1c2a7603ce057ee39fd88e7329b0c292aa16869b"}, -] - -[[package]] -name = "coverage" -version = "5.3" -description = "Code coverage measurement for Python" -category = "dev" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, <4" -files = [ - {file = "coverage-5.3-cp27-cp27m-macosx_10_13_intel.whl", hash = "sha256:bd3166bb3b111e76a4f8e2980fa1addf2920a4ca9b2b8ca36a3bc3dedc618270"}, - {file = "coverage-5.3-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:9342dd70a1e151684727c9c91ea003b2fb33523bf19385d4554f7897ca0141d4"}, - {file = "coverage-5.3-cp27-cp27m-manylinux1_i686.whl", hash = "sha256:63808c30b41f3bbf65e29f7280bf793c79f54fb807057de7e5238ffc7cc4d7b9"}, - {file = "coverage-5.3-cp27-cp27m-manylinux1_x86_64.whl", hash = "sha256:4d6a42744139a7fa5b46a264874a781e8694bb32f1d76d8137b68138686f1729"}, - {file = "coverage-5.3-cp27-cp27m-win32.whl", hash = "sha256:86e9f8cd4b0cdd57b4ae71a9c186717daa4c5a99f3238a8723f416256e0b064d"}, - {file = "coverage-5.3-cp27-cp27m-win_amd64.whl", hash = "sha256:7858847f2d84bf6e64c7f66498e851c54de8ea06a6f96a32a1d192d846734418"}, - {file = "coverage-5.3-cp27-cp27mu-manylinux1_i686.whl", hash = "sha256:530cc8aaf11cc2ac7430f3614b04645662ef20c348dce4167c22d99bec3480e9"}, - {file = "coverage-5.3-cp27-cp27mu-manylinux1_x86_64.whl", hash = "sha256:381ead10b9b9af5f64646cd27107fb27b614ee7040bb1226f9c07ba96625cbb5"}, - {file = "coverage-5.3-cp35-cp35m-macosx_10_13_x86_64.whl", hash = "sha256:71b69bd716698fa62cd97137d6f2fdf49f534decb23a2c6fc80813e8b7be6822"}, - {file = "coverage-5.3-cp35-cp35m-manylinux1_i686.whl", hash = "sha256:1d44bb3a652fed01f1f2c10d5477956116e9b391320c94d36c6bf13b088a1097"}, - {file = "coverage-5.3-cp35-cp35m-manylinux1_x86_64.whl", hash = "sha256:1c6703094c81fa55b816f5ae542c6ffc625fec769f22b053adb42ad712d086c9"}, - {file = "coverage-5.3-cp35-cp35m-win32.whl", hash = "sha256:cedb2f9e1f990918ea061f28a0f0077a07702e3819602d3507e2ff98c8d20636"}, - {file = "coverage-5.3-cp35-cp35m-win_amd64.whl", hash = "sha256:7f43286f13d91a34fadf61ae252a51a130223c52bfefb50310d5b2deb062cf0f"}, - {file = "coverage-5.3-cp36-cp36m-macosx_10_13_x86_64.whl", hash = "sha256:c851b35fc078389bc16b915a0a7c1d5923e12e2c5aeec58c52f4aa8085ac8237"}, - {file = "coverage-5.3-cp36-cp36m-manylinux1_i686.whl", hash = "sha256:aac1ba0a253e17889550ddb1b60a2063f7474155465577caa2a3b131224cfd54"}, - {file = "coverage-5.3-cp36-cp36m-manylinux1_x86_64.whl", hash = "sha256:2b31f46bf7b31e6aa690d4c7a3d51bb262438c6dcb0d528adde446531d0d3bb7"}, - {file = "coverage-5.3-cp36-cp36m-win32.whl", hash = "sha256:c5f17ad25d2c1286436761b462e22b5020d83316f8e8fcb5deb2b3151f8f1d3a"}, - {file = "coverage-5.3-cp36-cp36m-win_amd64.whl", hash = "sha256:aef72eae10b5e3116bac6957de1df4d75909fc76d1499a53fb6387434b6bcd8d"}, - {file = "coverage-5.3-cp37-cp37m-macosx_10_13_x86_64.whl", hash = "sha256:e8caf961e1b1a945db76f1b5fa9c91498d15f545ac0ababbe575cfab185d3bd8"}, - {file = "coverage-5.3-cp37-cp37m-manylinux1_i686.whl", hash = "sha256:29a6272fec10623fcbe158fdf9abc7a5fa032048ac1d8631f14b50fbfc10d17f"}, - {file = "coverage-5.3-cp37-cp37m-manylinux1_x86_64.whl", hash = "sha256:2d43af2be93ffbad25dd959899b5b809618a496926146ce98ee0b23683f8c51c"}, - {file = "coverage-5.3-cp37-cp37m-win32.whl", hash = "sha256:c3888a051226e676e383de03bf49eb633cd39fc829516e5334e69b8d81aae751"}, - {file = "coverage-5.3-cp37-cp37m-win_amd64.whl", hash = "sha256:9669179786254a2e7e57f0ecf224e978471491d660aaca833f845b72a2df3709"}, - {file = "coverage-5.3-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:0203acd33d2298e19b57451ebb0bed0ab0c602e5cf5a818591b4918b1f97d516"}, - {file = "coverage-5.3-cp38-cp38-manylinux1_i686.whl", hash = "sha256:582ddfbe712025448206a5bc45855d16c2e491c2dd102ee9a2841418ac1c629f"}, - {file = "coverage-5.3-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:0f313707cdecd5cd3e217fc68c78a960b616604b559e9ea60cc16795c4304259"}, - {file = "coverage-5.3-cp38-cp38-win32.whl", hash = "sha256:78e93cc3571fd928a39c0b26767c986188a4118edc67bc0695bc7a284da22e82"}, - {file = "coverage-5.3-cp38-cp38-win_amd64.whl", hash = "sha256:8f264ba2701b8c9f815b272ad568d555ef98dfe1576802ab3149c3629a9f2221"}, - {file = "coverage-5.3-cp39-cp39-macosx_10_13_x86_64.whl", hash = "sha256:50691e744714856f03a86df3e2bff847c2acede4c191f9a1da38f088df342978"}, - {file = "coverage-5.3-cp39-cp39-manylinux1_i686.whl", hash = "sha256:9361de40701666b034c59ad9e317bae95c973b9ff92513dd0eced11c6adf2e21"}, - {file = "coverage-5.3-cp39-cp39-manylinux1_x86_64.whl", hash = "sha256:c1b78fb9700fc961f53386ad2fd86d87091e06ede5d118b8a50dea285a071c24"}, - {file = "coverage-5.3-cp39-cp39-win32.whl", hash = "sha256:cb7df71de0af56000115eafd000b867d1261f786b5eebd88a0ca6360cccfaca7"}, - {file = "coverage-5.3-cp39-cp39-win_amd64.whl", hash = "sha256:47a11bdbd8ada9b7ee628596f9d97fbd3851bd9999d398e9436bd67376dbece7"}, - {file = "coverage-5.3.tar.gz", hash = "sha256:280baa8ec489c4f542f8940f9c4c2181f0306a8ee1a54eceba071a449fb870a0"}, -] - -[package.extras] -toml = ["toml"] - -[[package]] -name = "dataset" -version = "1.4.1" -description = "Toolkit for Python-based database access." -category = "main" -optional = false -python-versions = "*" -files = [ - {file = "dataset-1.4.1-py2.py3-none-any.whl", hash = "sha256:b6b93662e4fb4240d4d68da4156b7b0713cd3d639455d9c2411636ad0ead59de"}, - {file = "dataset-1.4.1.tar.gz", hash = "sha256:97902a3d4d62a506c74904fa7c2512a982f12f9892786f2e77b2cdfbd9f72388"}, -] - -[package.dependencies] -alembic = ">=0.6.2" -banal = ">=1.0.1" -sqlalchemy = ">=1.3.2" - -[package.extras] -dev = ["PyMySQL", "coverage", "cryptography", "flake8", "nose", "pip", "psycopg2-binary", "wheel"] - -[[package]] -name = "decorator" -version = "4.4.2" -description = "Decorators for Humans" -category = "dev" -optional = false -python-versions = ">=2.6, !=3.0.*, !=3.1.*" -files = [ - {file = "decorator-4.4.2-py2.py3-none-any.whl", hash = "sha256:41fa54c2a0cc4ba648be4fd43cff00aedf5b9465c9bf18d64325bc225f08f760"}, - {file = "decorator-4.4.2.tar.gz", hash = "sha256:e3a62f0520172440ca0dcc823749319382e377f37f140a0b99ef45fecb84bfe7"}, -] - -[[package]] -name = "dice" -version = "3.1.1" -description = "A library for parsing and evaluating dice notation" -category = "main" -optional = false -python-versions = "*" -files = [ - {file = "dice-3.1.1-py2.py3-none-any.whl", hash = "sha256:43c427532d64baefda5bb5d29a4bba1adad1f4b5cc2b8ec28dfcbb7228765385"}, - {file = "dice-3.1.1.tar.gz", hash = "sha256:99d9c3a90c4f0d016911526c1ea5a10394e047cc3ce61eab22fd34c0f4bc9f60"}, -] - -[package.dependencies] -docopt = ">=0.6.1" -pyparsing = ">=2.4.1" - -[[package]] -name = "distlib" -version = "0.3.1" -description = "Distribution utilities" -category = "dev" -optional = false -python-versions = "*" -files = [ - {file = "distlib-0.3.1-py2.py3-none-any.whl", hash = "sha256:8c09de2c67b3e7deef7184574fc060ab8a793e7adbb183d942c389c8b13c52fb"}, - {file = "distlib-0.3.1.zip", hash = "sha256:edf6116872c863e1aa9d5bb7cb5e05a022c519a4594dc703843343a9ddd9bff1"}, -] - -[[package]] -name = "docopt" -version = "0.6.2" -description = "Pythonic argument parser, that will make you smile" -category = "main" -optional = false -python-versions = "*" -files = [ - {file = "docopt-0.6.2.tar.gz", hash = "sha256:49b3a825280bd66b3aa83585ef59c4a8c82f2c8a522dbe754a8bc8d08c85c491"}, -] - -[[package]] -name = "filelock" -version = "3.0.12" -description = "A platform independent file lock." -category = "dev" -optional = false -python-versions = "*" -files = [ - {file = "filelock-3.0.12-py3-none-any.whl", hash = "sha256:929b7d63ec5b7d6b71b0fa5ac14e030b3f70b75747cef1b10da9b879fef15836"}, - {file = "filelock-3.0.12.tar.gz", hash = "sha256:18d82244ee114f543149c66a6e0c14e9c4f8a1044b5cdaadd0f82159d6a6ff59"}, -] - -[[package]] -name = "flake8" -version = "3.8.4" -description = "the modular source code checker: pep8 pyflakes and co" -category = "dev" -optional = false -python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,>=2.7" -files = [ - {file = "flake8-3.8.4-py2.py3-none-any.whl", hash = "sha256:749dbbd6bfd0cf1318af27bf97a14e28e5ff548ef8e5b1566ccfb25a11e7c839"}, - {file = "flake8-3.8.4.tar.gz", hash = "sha256:aadae8761ec651813c24be05c6f7b4680857ef6afaae4651a4eccaef97ce6c3b"}, -] - -[package.dependencies] -importlib-metadata = {version = "*", markers = "python_version < \"3.8\""} -mccabe = ">=0.6.0,<0.7.0" -pycodestyle = ">=2.6.0a1,<2.7.0" -pyflakes = ">=2.2.0,<2.3.0" - -[[package]] -name = "flask" -version = "1.1.2" -description = "A simple framework for building complex web applications." -category = "main" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" -files = [ - {file = "Flask-1.1.2-py2.py3-none-any.whl", hash = "sha256:8a4fdd8936eba2512e9c85df320a37e694c93945b33ef33c89946a340a238557"}, - {file = "Flask-1.1.2.tar.gz", hash = "sha256:4efa1ae2d7c9865af48986de8aeb8504bf32c7f3d6fdc9353d34b21f4b127060"}, -] - -[package.dependencies] -click = ">=5.1" -itsdangerous = ">=0.24" -Jinja2 = ">=2.10.1" -Werkzeug = ">=0.15" - -[package.extras] -dev = ["coverage", "pallets-sphinx-themes", "pytest", "sphinx", "sphinx-issues", "sphinxcontrib-log-cabinet", "tox"] -docs = ["pallets-sphinx-themes", "sphinx", "sphinx-issues", "sphinxcontrib-log-cabinet"] -dotenv = ["python-dotenv"] - -[[package]] -name = "identify" -version = "1.5.13" -description = "File identification library for Python" -category = "dev" -optional = false -python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,>=2.7" -files = [ - {file = "identify-1.5.13-py2.py3-none-any.whl", hash = "sha256:9dfb63a2e871b807e3ba62f029813552a24b5289504f5b071dea9b041aee9fe4"}, - {file = "identify-1.5.13.tar.gz", hash = "sha256:70b638cf4743f33042bebb3b51e25261a0a10e80f978739f17e7fd4837664a66"}, -] - -[package.extras] -license = ["editdistance"] - -[[package]] -name = "idna" -version = "2.10" -description = "Internationalized Domain Names in Applications (IDNA)" -category = "main" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" -files = [ - {file = "idna-2.10-py2.py3-none-any.whl", hash = "sha256:b97d804b1e9b523befed77c48dacec60e6dcb0b5391d57af6a65a312a90648c0"}, - {file = "idna-2.10.tar.gz", hash = "sha256:b307872f855b18632ce0c21c5e45be78c0ea7ae4c15c828c20788b26921eb3f6"}, -] - -[[package]] -name = "importlib-metadata" -version = "3.1.1" -description = "Read metadata from Python packages" -category = "dev" -optional = false -python-versions = ">=3.6" -files = [ - {file = "importlib_metadata-3.1.1-py3-none-any.whl", hash = "sha256:6112e21359ef8f344e7178aa5b72dc6e62b38b0d008e6d3cb212c5b84df72013"}, - {file = "importlib_metadata-3.1.1.tar.gz", hash = "sha256:b0c2d3b226157ae4517d9625decf63591461c66b3a808c2666d538946519d170"}, -] - -[package.dependencies] -zipp = ">=0.5" - -[package.extras] -docs = ["jaraco.packaging (>=3.2)", "rst.linker (>=1.9)", "sphinx"] -testing = ["flufl.flake8", "importlib-resources (>=1.3)", "jaraco.test (>=3.2.0)", "packaging", "pep517", "pyfakefs", "pytest (>=3.5,!=3.7.3)", "pytest-black (>=0.3.7)", "pytest-checkdocs (>=1.2.3)", "pytest-cov", "pytest-flake8", "pytest-mypy"] - -[[package]] -name = "iniconfig" -version = "1.1.1" -description = "iniconfig: brain-dead simple config-ini parsing" -category = "dev" -optional = false -python-versions = "*" -files = [ - {file = "iniconfig-1.1.1-py2.py3-none-any.whl", hash = "sha256:011e24c64b7f47f6ebd835bb12a743f2fbe9a26d4cecaa7f53bc4f35ee9da8b3"}, - {file = "iniconfig-1.1.1.tar.gz", hash = "sha256:bc3af051d7d14b2ee5ef9969666def0cd1a000e121eaea580d4a313df4b37f32"}, -] - -[[package]] -name = "ipdb" -version = "0.13.4" -description = "IPython-enabled pdb" -category = "dev" -optional = false -python-versions = ">=2.7" -files = [ - {file = "ipdb-0.13.4.tar.gz", hash = "sha256:c85398b5fb82f82399fc38c44fe3532c0dde1754abee727d8f5cfcc74547b334"}, -] - -[package.dependencies] -ipython = {version = ">=5.1.0", markers = "python_version >= \"3.4\""} -setuptools = "*" - -[[package]] -name = "ipython" -version = "7.19.0" -description = "IPython: Productive Interactive Computing" -category = "dev" -optional = false -python-versions = ">=3.7" -files = [ - {file = "ipython-7.19.0-py3-none-any.whl", hash = "sha256:c987e8178ced651532b3b1ff9965925bfd445c279239697052561a9ab806d28f"}, - {file = "ipython-7.19.0.tar.gz", hash = "sha256:cbb2ef3d5961d44e6a963b9817d4ea4e1fa2eb589c371a470fed14d8d40cbd6a"}, -] - -[package.dependencies] -appnope = {version = "*", markers = "sys_platform == \"darwin\""} -backcall = "*" -colorama = {version = "*", markers = "sys_platform == \"win32\""} -decorator = "*" -jedi = ">=0.10" -pexpect = {version = ">4.3", markers = "sys_platform != \"win32\""} -pickleshare = "*" -prompt-toolkit = ">=2.0.0,<3.0.0 || >3.0.0,<3.0.1 || >3.0.1,<3.1.0" -pygments = "*" -setuptools = ">=18.5" -traitlets = ">=4.2" - -[package.extras] -all = ["Sphinx (>=1.3)", "ipykernel", "ipyparallel", "ipywidgets", "nbconvert", "nbformat", "nose (>=0.10.1)", "notebook", "numpy (>=1.14)", "pygments", "qtconsole", "requests", "testpath"] -doc = ["Sphinx (>=1.3)"] -kernel = ["ipykernel"] -nbconvert = ["nbconvert"] -nbformat = ["nbformat"] -notebook = ["ipywidgets", "notebook"] -parallel = ["ipyparallel"] -qtconsole = ["qtconsole"] -test = ["ipykernel", "nbformat", "nose (>=0.10.1)", "numpy (>=1.14)", "pygments", "requests", "testpath"] - -[[package]] -name = "ipython-genutils" -version = "0.2.0" -description = "Vestigial utilities from IPython" -category = "dev" -optional = false -python-versions = "*" -files = [ - {file = "ipython_genutils-0.2.0-py2.py3-none-any.whl", hash = "sha256:72dd37233799e619666c9f639a9da83c34013a73e8bbc79a7a6348d93c61fab8"}, - {file = "ipython_genutils-0.2.0.tar.gz", hash = "sha256:eb2e116e75ecef9d4d228fdc66af54269afa26ab4463042e33785b887c628ba8"}, -] - -[[package]] -name = "isort" -version = "4.3.21" -description = "A Python utility / library to sort Python imports." -category = "dev" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" -files = [ - {file = "isort-4.3.21-py2.py3-none-any.whl", hash = "sha256:6e811fcb295968434526407adb8796944f1988c5b65e8139058f2014cbe100fd"}, - {file = "isort-4.3.21.tar.gz", hash = "sha256:54da7e92468955c4fceacd0c86bd0ec997b0e1ee80d97f67c35a78b719dccab1"}, -] - -[package.extras] -pipfile = ["pipreqs", "requirementslib"] -pyproject = ["toml"] -requirements = ["pip-api", "pipreqs"] -xdg-home = ["appdirs (>=1.4.0)"] - -[[package]] -name = "itsdangerous" -version = "1.1.0" -description = "Various helpers to pass data to untrusted environments and back." -category = "main" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" -files = [ - {file = "itsdangerous-1.1.0-py2.py3-none-any.whl", hash = "sha256:b12271b2047cb23eeb98c8b5622e2e5c5e9abd9784a153e9d8ef9cb4dd09d749"}, - {file = "itsdangerous-1.1.0.tar.gz", hash = "sha256:321b033d07f2a4136d3ec762eac9f16a10ccd60f53c0c91af90217ace7ba1f19"}, -] - -[[package]] -name = "jedi" -version = "0.17.2" -description = "An autocompletion tool for Python that can be used for text editors." -category = "dev" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" -files = [ - {file = "jedi-0.17.2-py2.py3-none-any.whl", hash = "sha256:98cc583fa0f2f8304968199b01b6b4b94f469a1f4a74c1560506ca2a211378b5"}, - {file = "jedi-0.17.2.tar.gz", hash = "sha256:86ed7d9b750603e4ba582ea8edc678657fb4007894a12bcf6f4bb97892f31d20"}, -] - -[package.dependencies] -parso = ">=0.7.0,<0.8.0" - -[package.extras] -qa = ["flake8 (==3.7.9)"] -testing = ["Django (<3.1)", "colorama", "docopt", "pytest (>=3.9.0,<5.0.0)"] - -[[package]] -name = "jinja2" -version = "2.11.2" -description = "A very fast and expressive template engine." -category = "main" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" -files = [ - {file = "Jinja2-2.11.2-py2.py3-none-any.whl", hash = "sha256:f0a4641d3cf955324a89c04f3d94663aa4d638abe8f733ecd3582848e1c37035"}, - {file = "Jinja2-2.11.2.tar.gz", hash = "sha256:89aab215427ef59c34ad58735269eb58b1a5808103067f7bb9d5836c651b3bb0"}, -] - -[package.dependencies] -MarkupSafe = ">=0.23" - -[package.extras] -i18n = ["Babel (>=0.8)"] - -[[package]] -name = "mako" -version = "1.1.3" -description = "A super-fast templating language that borrows the best ideas from the existing templating languages." -category = "main" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" -files = [ - {file = "Mako-1.1.3-py2.py3-none-any.whl", hash = "sha256:93729a258e4ff0747c876bd9e20df1b9758028946e976324ccd2d68245c7b6a9"}, - {file = "Mako-1.1.3.tar.gz", hash = "sha256:8195c8c1400ceb53496064314c6736719c6f25e7479cd24c77be3d9361cddc27"}, -] - -[package.dependencies] -MarkupSafe = ">=0.9.2" - -[package.extras] -babel = ["Babel"] -lingua = ["lingua"] - -[[package]] -name = "markupsafe" -version = "2.1.2" -description = "Safely add untrusted strings to HTML/XML markup." -category = "main" -optional = false -python-versions = ">=3.7" -files = [ - {file = "MarkupSafe-2.1.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:665a36ae6f8f20a4676b53224e33d456a6f5a72657d9c83c2aa00765072f31f7"}, - {file = "MarkupSafe-2.1.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:340bea174e9761308703ae988e982005aedf427de816d1afe98147668cc03036"}, - {file = "MarkupSafe-2.1.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:22152d00bf4a9c7c83960521fc558f55a1adbc0631fbb00a9471e097b19d72e1"}, - {file = "MarkupSafe-2.1.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:28057e985dace2f478e042eaa15606c7efccb700797660629da387eb289b9323"}, - {file = "MarkupSafe-2.1.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ca244fa73f50a800cf8c3ebf7fd93149ec37f5cb9596aa8873ae2c1d23498601"}, - {file = "MarkupSafe-2.1.2-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:d9d971ec1e79906046aa3ca266de79eac42f1dbf3612a05dc9368125952bd1a1"}, - {file = "MarkupSafe-2.1.2-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:7e007132af78ea9df29495dbf7b5824cb71648d7133cf7848a2a5dd00d36f9ff"}, - {file = "MarkupSafe-2.1.2-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:7313ce6a199651c4ed9d7e4cfb4aa56fe923b1adf9af3b420ee14e6d9a73df65"}, - {file = "MarkupSafe-2.1.2-cp310-cp310-win32.whl", hash = "sha256:c4a549890a45f57f1ebf99c067a4ad0cb423a05544accaf2b065246827ed9603"}, - {file = "MarkupSafe-2.1.2-cp310-cp310-win_amd64.whl", hash = "sha256:835fb5e38fd89328e9c81067fd642b3593c33e1e17e2fdbf77f5676abb14a156"}, - {file = "MarkupSafe-2.1.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:2ec4f2d48ae59bbb9d1f9d7efb9236ab81429a764dedca114f5fdabbc3788013"}, - {file = "MarkupSafe-2.1.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:608e7073dfa9e38a85d38474c082d4281f4ce276ac0010224eaba11e929dd53a"}, - {file = "MarkupSafe-2.1.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:65608c35bfb8a76763f37036547f7adfd09270fbdbf96608be2bead319728fcd"}, - {file = "MarkupSafe-2.1.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f2bfb563d0211ce16b63c7cb9395d2c682a23187f54c3d79bfec33e6705473c6"}, - {file = "MarkupSafe-2.1.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:da25303d91526aac3672ee6d49a2f3db2d9502a4a60b55519feb1a4c7714e07d"}, - {file = "MarkupSafe-2.1.2-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:9cad97ab29dfc3f0249b483412c85c8ef4766d96cdf9dcf5a1e3caa3f3661cf1"}, - {file = "MarkupSafe-2.1.2-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:085fd3201e7b12809f9e6e9bc1e5c96a368c8523fad5afb02afe3c051ae4afcc"}, - {file = "MarkupSafe-2.1.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:1bea30e9bf331f3fef67e0a3877b2288593c98a21ccb2cf29b74c581a4eb3af0"}, - {file = "MarkupSafe-2.1.2-cp311-cp311-win32.whl", hash = "sha256:7df70907e00c970c60b9ef2938d894a9381f38e6b9db73c5be35e59d92e06625"}, - {file = "MarkupSafe-2.1.2-cp311-cp311-win_amd64.whl", hash = "sha256:e55e40ff0cc8cc5c07996915ad367fa47da6b3fc091fdadca7f5403239c5fec3"}, - {file = "MarkupSafe-2.1.2-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:a6e40afa7f45939ca356f348c8e23048e02cb109ced1eb8420961b2f40fb373a"}, - {file = "MarkupSafe-2.1.2-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cf877ab4ed6e302ec1d04952ca358b381a882fbd9d1b07cccbfd61783561f98a"}, - {file = "MarkupSafe-2.1.2-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:63ba06c9941e46fa389d389644e2d8225e0e3e5ebcc4ff1ea8506dce646f8c8a"}, - {file = "MarkupSafe-2.1.2-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f1cd098434e83e656abf198f103a8207a8187c0fc110306691a2e94a78d0abb2"}, - {file = "MarkupSafe-2.1.2-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:55f44b440d491028addb3b88f72207d71eeebfb7b5dbf0643f7c023ae1fba619"}, - {file = "MarkupSafe-2.1.2-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:a6f2fcca746e8d5910e18782f976489939d54a91f9411c32051b4aab2bd7c513"}, - {file = "MarkupSafe-2.1.2-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:0b462104ba25f1ac006fdab8b6a01ebbfbce9ed37fd37fd4acd70c67c973e460"}, - {file = "MarkupSafe-2.1.2-cp37-cp37m-win32.whl", hash = "sha256:7668b52e102d0ed87cb082380a7e2e1e78737ddecdde129acadb0eccc5423859"}, - {file = "MarkupSafe-2.1.2-cp37-cp37m-win_amd64.whl", hash = "sha256:6d6607f98fcf17e534162f0709aaad3ab7a96032723d8ac8750ffe17ae5a0666"}, - {file = "MarkupSafe-2.1.2-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:a806db027852538d2ad7555b203300173dd1b77ba116de92da9afbc3a3be3eed"}, - {file = "MarkupSafe-2.1.2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:a4abaec6ca3ad8660690236d11bfe28dfd707778e2442b45addd2f086d6ef094"}, - {file = "MarkupSafe-2.1.2-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f03a532d7dee1bed20bc4884194a16160a2de9ffc6354b3878ec9682bb623c54"}, - {file = "MarkupSafe-2.1.2-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4cf06cdc1dda95223e9d2d3c58d3b178aa5dacb35ee7e3bbac10e4e1faacb419"}, - {file = "MarkupSafe-2.1.2-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:22731d79ed2eb25059ae3df1dfc9cb1546691cc41f4e3130fe6bfbc3ecbbecfa"}, - {file = "MarkupSafe-2.1.2-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:f8ffb705ffcf5ddd0e80b65ddf7bed7ee4f5a441ea7d3419e861a12eaf41af58"}, - {file = "MarkupSafe-2.1.2-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:8db032bf0ce9022a8e41a22598eefc802314e81b879ae093f36ce9ddf39ab1ba"}, - {file = "MarkupSafe-2.1.2-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:2298c859cfc5463f1b64bd55cb3e602528db6fa0f3cfd568d3605c50678f8f03"}, - {file = "MarkupSafe-2.1.2-cp38-cp38-win32.whl", hash = "sha256:50c42830a633fa0cf9e7d27664637532791bfc31c731a87b202d2d8ac40c3ea2"}, - {file = "MarkupSafe-2.1.2-cp38-cp38-win_amd64.whl", hash = "sha256:bb06feb762bade6bf3c8b844462274db0c76acc95c52abe8dbed28ae3d44a147"}, - {file = "MarkupSafe-2.1.2-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:99625a92da8229df6d44335e6fcc558a5037dd0a760e11d84be2260e6f37002f"}, - {file = "MarkupSafe-2.1.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:8bca7e26c1dd751236cfb0c6c72d4ad61d986e9a41bbf76cb445f69488b2a2bd"}, - {file = "MarkupSafe-2.1.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:40627dcf047dadb22cd25ea7ecfe9cbf3bbbad0482ee5920b582f3809c97654f"}, - {file = "MarkupSafe-2.1.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:40dfd3fefbef579ee058f139733ac336312663c6706d1163b82b3003fb1925c4"}, - {file = "MarkupSafe-2.1.2-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:090376d812fb6ac5f171e5938e82e7f2d7adc2b629101cec0db8b267815c85e2"}, - {file = "MarkupSafe-2.1.2-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:2e7821bffe00aa6bd07a23913b7f4e01328c3d5cc0b40b36c0bd81d362faeb65"}, - {file = "MarkupSafe-2.1.2-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:c0a33bc9f02c2b17c3ea382f91b4db0e6cde90b63b296422a939886a7a80de1c"}, - {file = "MarkupSafe-2.1.2-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:b8526c6d437855442cdd3d87eede9c425c4445ea011ca38d937db299382e6fa3"}, - {file = "MarkupSafe-2.1.2-cp39-cp39-win32.whl", hash = "sha256:137678c63c977754abe9086a3ec011e8fd985ab90631145dfb9294ad09c102a7"}, - {file = "MarkupSafe-2.1.2-cp39-cp39-win_amd64.whl", hash = "sha256:0576fe974b40a400449768941d5d0858cc624e3249dfd1e0c33674e5c7ca7aed"}, - {file = "MarkupSafe-2.1.2.tar.gz", hash = "sha256:abcabc8c2b26036d62d4c746381a6f7cf60aafcc653198ad678306986b09450d"}, -] - -[[package]] -name = "mccabe" -version = "0.6.1" -description = "McCabe checker, plugin for flake8" -category = "dev" -optional = false -python-versions = "*" -files = [ - {file = "mccabe-0.6.1-py2.py3-none-any.whl", hash = "sha256:ab8a6258860da4b6677da4bd2fe5dc2c659cff31b3ee4f7f5d64e79735b80d42"}, - {file = "mccabe-0.6.1.tar.gz", hash = "sha256:dd8d182285a0fe56bace7f45b5e7d1a6ebcbf524e8f3bd87eb0f125271b8831f"}, -] - -[[package]] -name = "nodeenv" -version = "1.5.0" -description = "Node.js virtual environment builder" -category = "dev" -optional = false -python-versions = "*" -files = [ - {file = "nodeenv-1.5.0-py2.py3-none-any.whl", hash = "sha256:5304d424c529c997bc888453aeaa6362d242b6b4631e90f3d4bf1b290f1c84a9"}, - {file = "nodeenv-1.5.0.tar.gz", hash = "sha256:ab45090ae383b716c4ef89e690c41ff8c2b257b85b309f01f3654df3d084bd7c"}, -] - -[[package]] -name = "packaging" -version = "20.7" -description = "Core utilities for Python packages" -category = "dev" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" -files = [ - {file = "packaging-20.7-py2.py3-none-any.whl", hash = "sha256:eb41423378682dadb7166144a4926e443093863024de508ca5c9737d6bc08376"}, - {file = "packaging-20.7.tar.gz", hash = "sha256:05af3bb85d320377db281cf254ab050e1a7ebcbf5410685a9a407e18a1f81236"}, -] - -[package.dependencies] -pyparsing = ">=2.0.2" - -[[package]] -name = "parso" -version = "0.7.1" -description = "A Python Parser" -category = "dev" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" -files = [ - {file = "parso-0.7.1-py2.py3-none-any.whl", hash = "sha256:97218d9159b2520ff45eb78028ba8b50d2bc61dcc062a9682666f2dc4bd331ea"}, - {file = "parso-0.7.1.tar.gz", hash = "sha256:caba44724b994a8a5e086460bb212abc5a8bc46951bf4a9a1210745953622eb9"}, -] - -[package.extras] -testing = ["docopt", "pytest (>=3.0.7)"] - -[[package]] -name = "pathspec" -version = "0.8.1" -description = "Utility library for gitignore style pattern matching of file paths." -category = "dev" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" -files = [ - {file = "pathspec-0.8.1-py2.py3-none-any.whl", hash = "sha256:aa0cb481c4041bf52ffa7b0d8fa6cd3e88a2ca4879c533c9153882ee2556790d"}, - {file = "pathspec-0.8.1.tar.gz", hash = "sha256:86379d6b86d75816baba717e64b1a3a3469deb93bb76d613c9ce79edc5cb68fd"}, -] - -[[package]] -name = "pexpect" -version = "4.8.0" -description = "Pexpect allows easy control of interactive console applications." -category = "dev" -optional = false -python-versions = "*" -files = [ - {file = "pexpect-4.8.0-py2.py3-none-any.whl", hash = "sha256:0b48a55dcb3c05f3329815901ea4fc1537514d6ba867a152b581d69ae3710937"}, - {file = "pexpect-4.8.0.tar.gz", hash = "sha256:fc65a43959d153d0114afe13997d439c22823a27cefceb5ff35c2178c6784c0c"}, -] - -[package.dependencies] -ptyprocess = ">=0.5" - -[[package]] -name = "pickleshare" -version = "0.7.5" -description = "Tiny 'shelve'-like database with concurrency support" -category = "dev" -optional = false -python-versions = "*" -files = [ - {file = "pickleshare-0.7.5-py2.py3-none-any.whl", hash = "sha256:9649af414d74d4df115d5d718f82acb59c9d418196b7b4290ed47a12ce62df56"}, - {file = "pickleshare-0.7.5.tar.gz", hash = "sha256:87683d47965c1da65cdacaf31c8441d12b8044cdec9aca500cd78fc2c683afca"}, -] - -[[package]] -name = "pluggy" -version = "0.13.1" -description = "plugin and hook calling mechanisms for python" -category = "dev" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" -files = [ - {file = "pluggy-0.13.1-py2.py3-none-any.whl", hash = "sha256:966c145cd83c96502c3c3868f50408687b38434af77734af1e9ca461a4081d2d"}, - {file = "pluggy-0.13.1.tar.gz", hash = "sha256:15b2acde666561e1298d71b523007ed7364de07029219b604cf808bfa1c765b0"}, -] - -[package.dependencies] -importlib-metadata = {version = ">=0.12", markers = "python_version < \"3.8\""} - -[package.extras] -dev = ["pre-commit", "tox"] - -[[package]] -name = "pre-commit" -version = "2.10.0" -description = "A framework for managing and maintaining multi-language pre-commit hooks." -category = "dev" -optional = false -python-versions = ">=3.6.1" -files = [ - {file = "pre_commit-2.10.0-py2.py3-none-any.whl", hash = "sha256:391ed331fdd0a21d0be48c1b9919921e9d372dfd60f6dc77b8f01dd6b13161c1"}, - {file = "pre_commit-2.10.0.tar.gz", hash = "sha256:f413348d3a8464b77987e36ef6e02c3372dadb823edf0dfe6fb0c3dc2f378ef9"}, -] - -[package.dependencies] -cfgv = ">=2.0.0" -identify = ">=1.0.0" -importlib-metadata = {version = "*", markers = "python_version < \"3.8\""} -nodeenv = ">=0.11.1" -pyyaml = ">=5.1" -toml = "*" -virtualenv = ">=20.0.8" - -[[package]] -name = "prompt-toolkit" -version = "3.0.8" -description = "Library for building powerful interactive command lines in Python" -category = "dev" -optional = false -python-versions = ">=3.6.1" -files = [ - {file = "prompt_toolkit-3.0.8-py3-none-any.whl", hash = "sha256:7debb9a521e0b1ee7d2fe96ee4bd60ef03c6492784de0547337ca4433e46aa63"}, - {file = "prompt_toolkit-3.0.8.tar.gz", hash = "sha256:25c95d2ac813909f813c93fde734b6e44406d1477a9faef7c915ff37d39c0a8c"}, -] - -[package.dependencies] -wcwidth = "*" - -[[package]] -name = "ptyprocess" -version = "0.6.0" -description = "Run a subprocess in a pseudo terminal" -category = "dev" -optional = false -python-versions = "*" -files = [ - {file = "ptyprocess-0.6.0-py2.py3-none-any.whl", hash = "sha256:d7cc528d76e76342423ca640335bd3633420dc1366f258cb31d05e865ef5ca1f"}, - {file = "ptyprocess-0.6.0.tar.gz", hash = "sha256:923f299cc5ad920c68f2bc0bc98b75b9f838b93b599941a6b63ddbc2476394c0"}, -] - -[[package]] -name = "py" -version = "1.9.0" -description = "library with cross-python path, ini-parsing, io, code, log facilities" -category = "dev" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" -files = [ - {file = "py-1.9.0-py2.py3-none-any.whl", hash = "sha256:366389d1db726cd2fcfc79732e75410e5fe4d31db13692115529d34069a043c2"}, - {file = "py-1.9.0.tar.gz", hash = "sha256:9ca6883ce56b4e8da7e79ac18787889fa5206c79dcc67fb065376cd2fe03f342"}, -] - -[[package]] -name = "pycodestyle" -version = "2.6.0" -description = "Python style guide checker" -category = "dev" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" -files = [ - {file = "pycodestyle-2.6.0-py2.py3-none-any.whl", hash = "sha256:2295e7b2f6b5bd100585ebcb1f616591b652db8a741695b3d8f5d28bdc934367"}, - {file = "pycodestyle-2.6.0.tar.gz", hash = "sha256:c58a7d2815e0e8d7972bf1803331fb0152f867bd89adf8a01dfd55085434192e"}, -] - -[[package]] -name = "pyflakes" -version = "2.2.0" -description = "passive checker of Python programs" -category = "dev" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" -files = [ - {file = "pyflakes-2.2.0-py2.py3-none-any.whl", hash = "sha256:0d94e0e05a19e57a99444b6ddcf9a6eb2e5c68d3ca1e98e90707af8152c90a92"}, - {file = "pyflakes-2.2.0.tar.gz", hash = "sha256:35b2d75ee967ea93b55750aa9edbbf72813e06a66ba54438df2cfac9e3c27fc8"}, -] - -[[package]] -name = "pygments" -version = "2.7.3" -description = "Pygments is a syntax highlighting package written in Python." -category = "dev" -optional = false -python-versions = ">=3.5" -files = [ - {file = "Pygments-2.7.3-py3-none-any.whl", hash = "sha256:f275b6c0909e5dafd2d6269a656aa90fa58ebf4a74f8fcf9053195d226b24a08"}, - {file = "Pygments-2.7.3.tar.gz", hash = "sha256:ccf3acacf3782cbed4a989426012f1c535c9a90d3a7fc3f16d231b9372d2b716"}, -] - -[[package]] -name = "pyparsing" -version = "2.4.7" -description = "Python parsing module" -category = "main" -optional = false -python-versions = ">=2.6, !=3.0.*, !=3.1.*, !=3.2.*" -files = [ - {file = "pyparsing-2.4.7-py2.py3-none-any.whl", hash = "sha256:ef9d7589ef3c200abe66653d3f1ab1033c3c419ae9b9bdb1240a85b024efc88b"}, - {file = "pyparsing-2.4.7.tar.gz", hash = "sha256:c203ec8783bf771a155b207279b9bccb8dea02d8f0c9e5f8ead507bc3246ecc1"}, -] - -[[package]] -name = "pytest" -version = "6.1.2" -description = "pytest: simple powerful testing with Python" -category = "dev" -optional = false -python-versions = ">=3.5" -files = [ - {file = "pytest-6.1.2-py3-none-any.whl", hash = "sha256:4288fed0d9153d9646bfcdf0c0428197dba1ecb27a33bb6e031d002fa88653fe"}, - {file = "pytest-6.1.2.tar.gz", hash = "sha256:c0a7e94a8cdbc5422a51ccdad8e6f1024795939cc89159a0ae7f0b316ad3823e"}, -] - -[package.dependencies] -atomicwrites = {version = ">=1.0", markers = "sys_platform == \"win32\""} -attrs = ">=17.4.0" -colorama = {version = "*", markers = "sys_platform == \"win32\""} -importlib-metadata = {version = ">=0.12", markers = "python_version < \"3.8\""} -iniconfig = "*" -packaging = "*" -pluggy = ">=0.12,<1.0" -py = ">=1.8.2" -toml = "*" - -[package.extras] -checkqa-mypy = ["mypy (==0.780)"] -testing = ["argcomplete", "hypothesis (>=3.56)", "mock", "nose", "requests", "xmlschema"] - -[[package]] -name = "pytest-cov" -version = "2.10.1" -description = "Pytest plugin for measuring coverage." -category = "dev" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" -files = [ - {file = "pytest-cov-2.10.1.tar.gz", hash = "sha256:47bd0ce14056fdd79f93e1713f88fad7bdcc583dcd7783da86ef2f085a0bb88e"}, - {file = "pytest_cov-2.10.1-py2.py3-none-any.whl", hash = "sha256:45ec2d5182f89a81fc3eb29e3d1ed3113b9e9a873bcddb2a71faaab066110191"}, -] - -[package.dependencies] -coverage = ">=4.4" -pytest = ">=4.6" - -[package.extras] -testing = ["fields", "hunter", "process-tests (==2.0.2)", "pytest-xdist", "six", "virtualenv"] - -[[package]] -name = "python-dateutil" -version = "2.8.1" -description = "Extensions to the standard Python datetime module" -category = "main" -optional = false -python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,>=2.7" -files = [ - {file = "python-dateutil-2.8.1.tar.gz", hash = "sha256:73ebfe9dbf22e832286dafa60473e4cd239f8592f699aa5adaf10050e6e1823c"}, - {file = "python_dateutil-2.8.1-py2.py3-none-any.whl", hash = "sha256:75bb3f31ea686f1197762692a9ee6a7550b59fc6ca3a1f4b5d7e32fb98e2da2a"}, -] - -[package.dependencies] -six = ">=1.5" - -[[package]] -name = "python-editor" -version = "1.0.4" -description = "Programmatically open an editor, capture the result." -category = "main" -optional = false -python-versions = "*" -files = [ - {file = "python-editor-1.0.4.tar.gz", hash = "sha256:51fda6bcc5ddbbb7063b2af7509e43bd84bfc32a4ff71349ec7847713882327b"}, - {file = "python_editor-1.0.4-py2-none-any.whl", hash = "sha256:5f98b069316ea1c2ed3f67e7f5df6c0d8f10b689964a4a811ff64f0106819ec8"}, - {file = "python_editor-1.0.4-py3-none-any.whl", hash = "sha256:1bf6e860a8ad52a14c3ee1252d5dc25b2030618ed80c022598f00176adc8367d"}, -] - -[[package]] -name = "pyyaml" -version = "5.4.1" -description = "YAML parser and emitter for Python" -category = "dev" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*" -files = [ - {file = "PyYAML-5.4.1-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:3b2b1824fe7112845700f815ff6a489360226a5609b96ec2190a45e62a9fc922"}, - {file = "PyYAML-5.4.1-cp27-cp27m-win32.whl", hash = "sha256:129def1b7c1bf22faffd67b8f3724645203b79d8f4cc81f674654d9902cb4393"}, - {file = "PyYAML-5.4.1-cp27-cp27m-win_amd64.whl", hash = "sha256:4465124ef1b18d9ace298060f4eccc64b0850899ac4ac53294547536533800c8"}, - {file = "PyYAML-5.4.1-cp27-cp27mu-manylinux1_x86_64.whl", hash = "sha256:bb4191dfc9306777bc594117aee052446b3fa88737cd13b7188d0e7aa8162185"}, - {file = "PyYAML-5.4.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:6c78645d400265a062508ae399b60b8c167bf003db364ecb26dcab2bda048253"}, - {file = "PyYAML-5.4.1-cp36-cp36m-manylinux1_x86_64.whl", hash = "sha256:4e0583d24c881e14342eaf4ec5fbc97f934b999a6828693a99157fde912540cc"}, - {file = "PyYAML-5.4.1-cp36-cp36m-manylinux2014_aarch64.whl", hash = "sha256:72a01f726a9c7851ca9bfad6fd09ca4e090a023c00945ea05ba1638c09dc3347"}, - {file = "PyYAML-5.4.1-cp36-cp36m-manylinux2014_s390x.whl", hash = "sha256:895f61ef02e8fed38159bb70f7e100e00f471eae2bc838cd0f4ebb21e28f8541"}, - {file = "PyYAML-5.4.1-cp36-cp36m-win32.whl", hash = "sha256:3bd0e463264cf257d1ffd2e40223b197271046d09dadf73a0fe82b9c1fc385a5"}, - {file = "PyYAML-5.4.1-cp36-cp36m-win_amd64.whl", hash = "sha256:e4fac90784481d221a8e4b1162afa7c47ed953be40d31ab4629ae917510051df"}, - {file = "PyYAML-5.4.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:5accb17103e43963b80e6f837831f38d314a0495500067cb25afab2e8d7a4018"}, - {file = "PyYAML-5.4.1-cp37-cp37m-manylinux1_x86_64.whl", hash = "sha256:e1d4970ea66be07ae37a3c2e48b5ec63f7ba6804bdddfdbd3cfd954d25a82e63"}, - {file = "PyYAML-5.4.1-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:cb333c16912324fd5f769fff6bc5de372e9e7a202247b48870bc251ed40239aa"}, - {file = "PyYAML-5.4.1-cp37-cp37m-manylinux2014_s390x.whl", hash = "sha256:fe69978f3f768926cfa37b867e3843918e012cf83f680806599ddce33c2c68b0"}, - {file = "PyYAML-5.4.1-cp37-cp37m-win32.whl", hash = "sha256:dd5de0646207f053eb0d6c74ae45ba98c3395a571a2891858e87df7c9b9bd51b"}, - {file = "PyYAML-5.4.1-cp37-cp37m-win_amd64.whl", hash = "sha256:08682f6b72c722394747bddaf0aa62277e02557c0fd1c42cb853016a38f8dedf"}, - {file = "PyYAML-5.4.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:d2d9808ea7b4af864f35ea216be506ecec180628aced0704e34aca0b040ffe46"}, - {file = "PyYAML-5.4.1-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:8c1be557ee92a20f184922c7b6424e8ab6691788e6d86137c5d93c1a6ec1b8fb"}, - {file = "PyYAML-5.4.1-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:fd7f6999a8070df521b6384004ef42833b9bd62cfee11a09bda1079b4b704247"}, - {file = "PyYAML-5.4.1-cp38-cp38-manylinux2014_s390x.whl", hash = "sha256:bfb51918d4ff3d77c1c856a9699f8492c612cde32fd3bcd344af9be34999bfdc"}, - {file = "PyYAML-5.4.1-cp38-cp38-win32.whl", hash = "sha256:fa5ae20527d8e831e8230cbffd9f8fe952815b2b7dae6ffec25318803a7528fc"}, - {file = "PyYAML-5.4.1-cp38-cp38-win_amd64.whl", hash = "sha256:0f5f5786c0e09baddcd8b4b45f20a7b5d61a7e7e99846e3c799b05c7c53fa696"}, - {file = "PyYAML-5.4.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:294db365efa064d00b8d1ef65d8ea2c3426ac366c0c4368d930bf1c5fb497f77"}, - {file = "PyYAML-5.4.1-cp39-cp39-manylinux1_x86_64.whl", hash = "sha256:74c1485f7707cf707a7aef42ef6322b8f97921bd89be2ab6317fd782c2d53183"}, - {file = "PyYAML-5.4.1-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:d483ad4e639292c90170eb6f7783ad19490e7a8defb3e46f97dfe4bacae89122"}, - {file = "PyYAML-5.4.1-cp39-cp39-manylinux2014_s390x.whl", hash = "sha256:fdc842473cd33f45ff6bce46aea678a54e3d21f1b61a7750ce3c498eedfe25d6"}, - {file = "PyYAML-5.4.1-cp39-cp39-win32.whl", hash = "sha256:49d4cdd9065b9b6e206d0595fee27a96b5dd22618e7520c33204a4a3239d5b10"}, - {file = "PyYAML-5.4.1-cp39-cp39-win_amd64.whl", hash = "sha256:c20cfa2d49991c8b4147af39859b167664f2ad4561704ee74c1de03318e898db"}, - {file = "PyYAML-5.4.1.tar.gz", hash = "sha256:607774cbba28732bfa802b54baa7484215f530991055bb562efbed5b2f20a45e"}, -] - -[[package]] -name = "regex" -version = "2020.11.13" -description = "Alternative regular expression module, to replace re." -category = "dev" -optional = false -python-versions = "*" -files = [ - {file = "regex-2020.11.13-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:8b882a78c320478b12ff024e81dc7d43c1462aa4a3341c754ee65d857a521f85"}, - {file = "regex-2020.11.13-cp36-cp36m-manylinux1_i686.whl", hash = "sha256:a63f1a07932c9686d2d416fb295ec2c01ab246e89b4d58e5fa468089cab44b70"}, - {file = "regex-2020.11.13-cp36-cp36m-manylinux1_x86_64.whl", hash = "sha256:6e4b08c6f8daca7d8f07c8d24e4331ae7953333dbd09c648ed6ebd24db5a10ee"}, - {file = "regex-2020.11.13-cp36-cp36m-manylinux2010_i686.whl", hash = "sha256:bba349276b126947b014e50ab3316c027cac1495992f10e5682dc677b3dfa0c5"}, - {file = "regex-2020.11.13-cp36-cp36m-manylinux2010_x86_64.whl", hash = "sha256:56e01daca75eae420bce184edd8bb341c8eebb19dd3bce7266332258f9fb9dd7"}, - {file = "regex-2020.11.13-cp36-cp36m-manylinux2014_aarch64.whl", hash = "sha256:6a8ce43923c518c24a2579fda49f093f1397dad5d18346211e46f134fc624e31"}, - {file = "regex-2020.11.13-cp36-cp36m-manylinux2014_i686.whl", hash = "sha256:1ab79fcb02b930de09c76d024d279686ec5d532eb814fd0ed1e0051eb8bd2daa"}, - {file = "regex-2020.11.13-cp36-cp36m-manylinux2014_x86_64.whl", hash = "sha256:9801c4c1d9ae6a70aeb2128e5b4b68c45d4f0af0d1535500884d644fa9b768c6"}, - {file = "regex-2020.11.13-cp36-cp36m-win32.whl", hash = "sha256:49cae022fa13f09be91b2c880e58e14b6da5d10639ed45ca69b85faf039f7a4e"}, - {file = "regex-2020.11.13-cp36-cp36m-win_amd64.whl", hash = "sha256:749078d1eb89484db5f34b4012092ad14b327944ee7f1c4f74d6279a6e4d1884"}, - {file = "regex-2020.11.13-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:b2f4007bff007c96a173e24dcda236e5e83bde4358a557f9ccf5e014439eae4b"}, - {file = "regex-2020.11.13-cp37-cp37m-manylinux1_i686.whl", hash = "sha256:38c8fd190db64f513fe4e1baa59fed086ae71fa45083b6936b52d34df8f86a88"}, - {file = "regex-2020.11.13-cp37-cp37m-manylinux1_x86_64.whl", hash = "sha256:5862975b45d451b6db51c2e654990c1820523a5b07100fc6903e9c86575202a0"}, - {file = "regex-2020.11.13-cp37-cp37m-manylinux2010_i686.whl", hash = "sha256:262c6825b309e6485ec2493ffc7e62a13cf13fb2a8b6d212f72bd53ad34118f1"}, - {file = "regex-2020.11.13-cp37-cp37m-manylinux2010_x86_64.whl", hash = "sha256:bafb01b4688833e099d79e7efd23f99172f501a15c44f21ea2118681473fdba0"}, - {file = "regex-2020.11.13-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:e32f5f3d1b1c663af7f9c4c1e72e6ffe9a78c03a31e149259f531e0fed826512"}, - {file = "regex-2020.11.13-cp37-cp37m-manylinux2014_i686.whl", hash = "sha256:3bddc701bdd1efa0d5264d2649588cbfda549b2899dc8d50417e47a82e1387ba"}, - {file = "regex-2020.11.13-cp37-cp37m-manylinux2014_x86_64.whl", hash = "sha256:02951b7dacb123d8ea6da44fe45ddd084aa6777d4b2454fa0da61d569c6fa538"}, - {file = "regex-2020.11.13-cp37-cp37m-win32.whl", hash = "sha256:0d08e71e70c0237883d0bef12cad5145b84c3705e9c6a588b2a9c7080e5af2a4"}, - {file = "regex-2020.11.13-cp37-cp37m-win_amd64.whl", hash = "sha256:1fa7ee9c2a0e30405e21031d07d7ba8617bc590d391adfc2b7f1e8b99f46f444"}, - {file = "regex-2020.11.13-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:baf378ba6151f6e272824b86a774326f692bc2ef4cc5ce8d5bc76e38c813a55f"}, - {file = "regex-2020.11.13-cp38-cp38-manylinux1_i686.whl", hash = "sha256:e3faaf10a0d1e8e23a9b51d1900b72e1635c2d5b0e1bea1c18022486a8e2e52d"}, - {file = "regex-2020.11.13-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:2a11a3e90bd9901d70a5b31d7dd85114755a581a5da3fc996abfefa48aee78af"}, - {file = "regex-2020.11.13-cp38-cp38-manylinux2010_i686.whl", hash = "sha256:d1ebb090a426db66dd80df8ca85adc4abfcbad8a7c2e9a5ec7513ede522e0a8f"}, - {file = "regex-2020.11.13-cp38-cp38-manylinux2010_x86_64.whl", hash = "sha256:b2b1a5ddae3677d89b686e5c625fc5547c6e492bd755b520de5332773a8af06b"}, - {file = "regex-2020.11.13-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:2c99e97d388cd0a8d30f7c514d67887d8021541b875baf09791a3baad48bb4f8"}, - {file = "regex-2020.11.13-cp38-cp38-manylinux2014_i686.whl", hash = "sha256:c084582d4215593f2f1d28b65d2a2f3aceff8342aa85afd7be23a9cad74a0de5"}, - {file = "regex-2020.11.13-cp38-cp38-manylinux2014_x86_64.whl", hash = "sha256:a3d748383762e56337c39ab35c6ed4deb88df5326f97a38946ddd19028ecce6b"}, - {file = "regex-2020.11.13-cp38-cp38-win32.whl", hash = "sha256:7913bd25f4ab274ba37bc97ad0e21c31004224ccb02765ad984eef43e04acc6c"}, - {file = "regex-2020.11.13-cp38-cp38-win_amd64.whl", hash = "sha256:6c54ce4b5d61a7129bad5c5dc279e222afd00e721bf92f9ef09e4fae28755683"}, - {file = "regex-2020.11.13-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:1862a9d9194fae76a7aaf0150d5f2a8ec1da89e8b55890b1786b8f88a0f619dc"}, - {file = "regex-2020.11.13-cp39-cp39-manylinux1_i686.whl", hash = "sha256:4902e6aa086cbb224241adbc2f06235927d5cdacffb2425c73e6570e8d862364"}, - {file = "regex-2020.11.13-cp39-cp39-manylinux1_x86_64.whl", hash = "sha256:7a25fcbeae08f96a754b45bdc050e1fb94b95cab046bf56b016c25e9ab127b3e"}, - {file = "regex-2020.11.13-cp39-cp39-manylinux2010_i686.whl", hash = "sha256:d2d8ce12b7c12c87e41123997ebaf1a5767a5be3ec545f64675388970f415e2e"}, - {file = "regex-2020.11.13-cp39-cp39-manylinux2010_x86_64.whl", hash = "sha256:f7d29a6fc4760300f86ae329e3b6ca28ea9c20823df123a2ea8693e967b29917"}, - {file = "regex-2020.11.13-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:717881211f46de3ab130b58ec0908267961fadc06e44f974466d1887f865bd5b"}, - {file = "regex-2020.11.13-cp39-cp39-manylinux2014_i686.whl", hash = "sha256:3128e30d83f2e70b0bed9b2a34e92707d0877e460b402faca908c6667092ada9"}, - {file = "regex-2020.11.13-cp39-cp39-manylinux2014_x86_64.whl", hash = "sha256:8f6a2229e8ad946e36815f2a03386bb8353d4bde368fdf8ca5f0cb97264d3b5c"}, - {file = "regex-2020.11.13-cp39-cp39-win32.whl", hash = "sha256:f8f295db00ef5f8bae530fc39af0b40486ca6068733fb860b42115052206466f"}, - {file = "regex-2020.11.13-cp39-cp39-win_amd64.whl", hash = "sha256:a15f64ae3a027b64496a71ab1f722355e570c3fac5ba2801cafce846bf5af01d"}, - {file = "regex-2020.11.13.tar.gz", hash = "sha256:83d6b356e116ca119db8e7c6fc2983289d87b27b3fac238cfe5dca529d884562"}, -] - -[[package]] -name = "requests" -version = "2.25.0" -description = "Python HTTP for Humans." -category = "main" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" -files = [ - {file = "requests-2.25.0-py2.py3-none-any.whl", hash = "sha256:e786fa28d8c9154e6a4de5d46a1d921b8749f8b74e28bde23768e5e16eece998"}, - {file = "requests-2.25.0.tar.gz", hash = "sha256:7f1a0b932f4a60a1a65caa4263921bb7d9ee911957e0ae4a23a6dd08185ad5f8"}, -] - -[package.dependencies] -certifi = ">=2017.4.17" -chardet = ">=3.0.2,<4" -idna = ">=2.5,<3" -urllib3 = ">=1.21.1,<1.27" - -[package.extras] -security = ["cryptography (>=1.3.4)", "pyOpenSSL (>=0.14)"] -socks = ["PySocks (>=1.5.6,!=1.5.7)", "win-inet-pton"] - -[[package]] -name = "rope" -version = "0.16.0" -description = "a python refactoring library..." -category = "dev" -optional = false -python-versions = "*" -files = [ - {file = "rope-0.16.0-py2-none-any.whl", hash = "sha256:ae1fa2fd56f64f4cc9be46493ce54bed0dd12dee03980c61a4393d89d84029ad"}, - {file = "rope-0.16.0-py3-none-any.whl", hash = "sha256:52423a7eebb5306a6d63bdc91a7c657db51ac9babfb8341c9a1440831ecf3203"}, - {file = "rope-0.16.0.tar.gz", hash = "sha256:d2830142c2e046f5fc26a022fe680675b6f48f81c7fc1f03a950706e746e9dfe"}, -] - -[package.extras] -dev = ["pytest"] - -[[package]] -name = "setuptools" -version = "65.6.3" -description = "Easily download, build, install, upgrade, and uninstall Python packages" -category = "dev" -optional = false -python-versions = ">=3.7" -files = [ - {file = "setuptools-65.6.3-py3-none-any.whl", hash = "sha256:57f6f22bde4e042978bcd50176fdb381d7c21a9efa4041202288d3737a0c6a54"}, - {file = "setuptools-65.6.3.tar.gz", hash = "sha256:a7620757bf984b58deaf32fc8a4577a9bbc0850cf92c20e1ce41c38c19e5fb75"}, -] - -[package.extras] -docs = ["furo", "jaraco.packaging (>=9)", "jaraco.tidelift (>=1.4)", "pygments-github-lexers (==0.0.5)", "rst.linker (>=1.9)", "sphinx (>=3.5)", "sphinx-favicon", "sphinx-hoverxref (<2)", "sphinx-inline-tabs", "sphinx-notfound-page (==0.8.3)", "sphinx-reredirects", "sphinxcontrib-towncrier"] -testing = ["build[virtualenv]", "filelock (>=3.4.0)", "flake8 (<5)", "flake8-2020", "ini2toml[lite] (>=0.9)", "jaraco.envs (>=2.2)", "jaraco.path (>=3.2.0)", "pip (>=19.1)", "pip-run (>=8.8)", "pytest (>=6)", "pytest-black (>=0.3.7)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=1.3)", "pytest-flake8", "pytest-mypy (>=0.9.1)", "pytest-perf", "pytest-timeout", "pytest-xdist", "tomli-w (>=1.0.0)", "virtualenv (>=13.0.0)", "wheel"] -testing-integration = ["build[virtualenv]", "filelock (>=3.4.0)", "jaraco.envs (>=2.2)", "jaraco.path (>=3.2.0)", "pytest", "pytest-enabler", "pytest-xdist", "tomli", "virtualenv (>=13.0.0)", "wheel"] - -[[package]] -name = "six" -version = "1.15.0" -description = "Python 2 and 3 compatibility utilities" -category = "main" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*" -files = [ - {file = "six-1.15.0-py2.py3-none-any.whl", hash = "sha256:8b74bedcbbbaca38ff6d7491d76f2b06b3592611af620f8426e82dddb04a5ced"}, - {file = "six-1.15.0.tar.gz", hash = "sha256:30639c035cdb23534cd4aa2dd52c3bf48f06e5f4a941509c8bafd8ce11080259"}, -] - -[[package]] -name = "sqlalchemy" -version = "1.3.20" -description = "Database Abstraction Library" -category = "main" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" -files = [ - {file = "SQLAlchemy-1.3.20-cp27-cp27m-macosx_10_14_x86_64.whl", hash = "sha256:bad73f9888d30f9e1d57ac8829f8a12091bdee4949b91db279569774a866a18e"}, - {file = "SQLAlchemy-1.3.20-cp27-cp27m-manylinux1_x86_64.whl", hash = "sha256:e32e3455db14602b6117f0f422f46bc297a3853ae2c322ecd1e2c4c04daf6ed5"}, - {file = "SQLAlchemy-1.3.20-cp27-cp27m-manylinux2010_x86_64.whl", hash = "sha256:5cdfe54c1e37279dc70d92815464b77cd8ee30725adc9350f06074f91dbfeed2"}, - {file = "SQLAlchemy-1.3.20-cp27-cp27m-win32.whl", hash = "sha256:2e9bd5b23bba8ae8ce4219c9333974ff5e103c857d9ff0e4b73dc4cb244c7d86"}, - {file = "SQLAlchemy-1.3.20-cp27-cp27m-win_amd64.whl", hash = "sha256:5d92c18458a4aa27497a986038d5d797b5279268a2de303cd00910658e8d149c"}, - {file = "SQLAlchemy-1.3.20-cp27-cp27mu-manylinux1_x86_64.whl", hash = "sha256:53fd857c6c8ffc0aa6a5a3a2619f6a74247e42ec9e46b836a8ffa4abe7aab327"}, - {file = "SQLAlchemy-1.3.20-cp27-cp27mu-manylinux2010_x86_64.whl", hash = "sha256:0a92745bb1ebbcb3985ed7bda379b94627f0edbc6c82e9e4bac4fb5647ae609a"}, - {file = "SQLAlchemy-1.3.20-cp35-cp35m-macosx_10_14_x86_64.whl", hash = "sha256:b6f036ecc017ec2e2cc2a40615b41850dc7aaaea6a932628c0afc73ab98ba3fb"}, - {file = "SQLAlchemy-1.3.20-cp35-cp35m-manylinux1_x86_64.whl", hash = "sha256:3aa6d45e149a16aa1f0c46816397e12313d5e37f22205c26e06975e150ffcf2a"}, - {file = "SQLAlchemy-1.3.20-cp35-cp35m-manylinux2010_x86_64.whl", hash = "sha256:ed53209b5f0f383acb49a927179fa51a6e2259878e164273ebc6815f3a752465"}, - {file = "SQLAlchemy-1.3.20-cp35-cp35m-manylinux2014_aarch64.whl", hash = "sha256:d3b709d64b5cf064972b3763b47139e4a0dc4ae28a36437757f7663f67b99710"}, - {file = "SQLAlchemy-1.3.20-cp35-cp35m-win32.whl", hash = "sha256:950f0e17ffba7a7ceb0dd056567bc5ade22a11a75920b0e8298865dc28c0eff6"}, - {file = "SQLAlchemy-1.3.20-cp35-cp35m-win_amd64.whl", hash = "sha256:8dcbf377529a9af167cbfc5b8acec0fadd7c2357fc282a1494c222d3abfc9629"}, - {file = "SQLAlchemy-1.3.20-cp36-cp36m-macosx_10_14_x86_64.whl", hash = "sha256:0157c269701d88f5faf1fa0e4560e4d814f210c01a5b55df3cab95e9346a8bcc"}, - {file = "SQLAlchemy-1.3.20-cp36-cp36m-manylinux1_x86_64.whl", hash = "sha256:7cd40cb4bc50d9e87b3540b23df6e6b24821ba7e1f305c1492b0806c33dbdbec"}, - {file = "SQLAlchemy-1.3.20-cp36-cp36m-manylinux2010_x86_64.whl", hash = "sha256:c092fe282de83d48e64d306b4bce03114859cdbfe19bf8a978a78a0d44ddadb1"}, - {file = "SQLAlchemy-1.3.20-cp36-cp36m-manylinux2014_aarch64.whl", hash = "sha256:166917a729b9226decff29416f212c516227c2eb8a9c9f920d69ced24e30109f"}, - {file = "SQLAlchemy-1.3.20-cp36-cp36m-win32.whl", hash = "sha256:632b32183c0cb0053194a4085c304bc2320e5299f77e3024556fa2aa395c2a8b"}, - {file = "SQLAlchemy-1.3.20-cp36-cp36m-win_amd64.whl", hash = "sha256:bbc58fca72ce45a64bb02b87f73df58e29848b693869e58bd890b2ddbb42d83b"}, - {file = "SQLAlchemy-1.3.20-cp37-cp37m-macosx_10_14_x86_64.whl", hash = "sha256:b15002b9788ffe84e42baffc334739d3b68008a973d65fad0a410ca5d0531980"}, - {file = "SQLAlchemy-1.3.20-cp37-cp37m-manylinux1_x86_64.whl", hash = "sha256:9e379674728f43a0cd95c423ac0e95262500f9bfd81d33b999daa8ea1756d162"}, - {file = "SQLAlchemy-1.3.20-cp37-cp37m-manylinux2010_x86_64.whl", hash = "sha256:2b5dafed97f778e9901b79cc01b88d39c605e0545b4541f2551a2fd785adc15b"}, - {file = "SQLAlchemy-1.3.20-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:fcdb3755a7c355bc29df1b5e6fb8226d5c8b90551d202d69d0076a8a5649d68b"}, - {file = "SQLAlchemy-1.3.20-cp37-cp37m-win32.whl", hash = "sha256:bca4d367a725694dae3dfdc86cf1d1622b9f414e70bd19651f5ac4fb3aa96d61"}, - {file = "SQLAlchemy-1.3.20-cp37-cp37m-win_amd64.whl", hash = "sha256:f605f348f4e6a2ba00acb3399c71d213b92f27f2383fc4abebf7a37368c12142"}, - {file = "SQLAlchemy-1.3.20-cp38-cp38-macosx_10_14_x86_64.whl", hash = "sha256:84f0ac4a09971536b38cc5d515d6add7926a7e13baa25135a1dbb6afa351a376"}, - {file = "SQLAlchemy-1.3.20-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:2909dffe5c9a615b7e6c92d1ac2d31e3026dc436440a4f750f4749d114d88ceb"}, - {file = "SQLAlchemy-1.3.20-cp38-cp38-manylinux2010_x86_64.whl", hash = "sha256:c3ab23ee9674336654bf9cac30eb75ac6acb9150dc4b1391bec533a7a4126471"}, - {file = "SQLAlchemy-1.3.20-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:009e8388d4d551a2107632921320886650b46332f61dc935e70c8bcf37d8e0d6"}, - {file = "SQLAlchemy-1.3.20-cp38-cp38-win32.whl", hash = "sha256:bf53d8dddfc3e53a5bda65f7f4aa40fae306843641e3e8e701c18a5609471edf"}, - {file = "SQLAlchemy-1.3.20-cp38-cp38-win_amd64.whl", hash = "sha256:7c735c7a6db8ee9554a3935e741cf288f7dcbe8706320251eb38c412e6a4281d"}, - {file = "SQLAlchemy-1.3.20-cp39-cp39-macosx_10_14_x86_64.whl", hash = "sha256:4bdbdb8ca577c6c366d15791747c1de6ab14529115a2eb52774240c412a7b403"}, - {file = "SQLAlchemy-1.3.20-cp39-cp39-manylinux1_x86_64.whl", hash = "sha256:ce64a44c867d128ab8e675f587aae7f61bd2db836a3c4ba522d884cd7c298a77"}, - {file = "SQLAlchemy-1.3.20-cp39-cp39-manylinux2010_x86_64.whl", hash = "sha256:be41d5de7a8e241864189b7530ca4aaf56a5204332caa70555c2d96379e18079"}, - {file = "SQLAlchemy-1.3.20-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:1f5f369202912be72fdf9a8f25067a5ece31a2b38507bb869306f173336348da"}, - {file = "SQLAlchemy-1.3.20-cp39-cp39-win32.whl", hash = "sha256:0cca1844ba870e81c03633a99aa3dc62256fb96323431a5dec7d4e503c26372d"}, - {file = "SQLAlchemy-1.3.20-cp39-cp39-win_amd64.whl", hash = "sha256:d05cef4a164b44ffda58200efcb22355350979e000828479971ebca49b82ddb1"}, - {file = "SQLAlchemy-1.3.20.tar.gz", hash = "sha256:d2f25c7f410338d31666d7ddedfa67570900e248b940d186b48461bd4e5569a1"}, -] - -[package.extras] -mssql = ["pyodbc"] -mssql-pymssql = ["pymssql"] -mssql-pyodbc = ["pyodbc"] -mysql = ["mysqlclient"] -oracle = ["cx-oracle"] -postgresql = ["psycopg2"] -postgresql-pg8000 = ["pg8000"] -postgresql-psycopg2binary = ["psycopg2-binary"] -postgresql-psycopg2cffi = ["psycopg2cffi"] -pymysql = ["pymysql"] - -[[package]] -name = "structlog" -version = "20.1.0" -description = "Structured Logging for Python" -category = "main" -optional = false -python-versions = "*" -files = [ - {file = "structlog-20.1.0-py2.py3-none-any.whl", hash = "sha256:8a672be150547a93d90a7d74229a29e765be05bd156a35cdcc527ebf68e9af92"}, - {file = "structlog-20.1.0.tar.gz", hash = "sha256:7a48375db6274ed1d0ae6123c486472aa1d0890b08d314d2b016f3aa7f35990b"}, -] - -[package.dependencies] -six = "*" - -[package.extras] -azure-pipelines = ["coverage[toml]", "freezegun (>=0.2.8)", "pretend", "pytest (>=3.3.0)", "pytest-asyncio", "pytest-azurepipelines", "python-rapidjson", "simplejson"] -dev = ["coverage[toml]", "freezegun (>=0.2.8)", "pre-commit", "pretend", "pytest (>=3.3.0)", "pytest-asyncio", "python-rapidjson", "simplejson", "sphinx", "twisted"] -docs = ["sphinx", "twisted"] -tests = ["coverage[toml]", "freezegun (>=0.2.8)", "pretend", "pytest (>=3.3.0)", "pytest-asyncio", "python-rapidjson", "simplejson"] - -[[package]] -name = "toml" -version = "0.10.2" -description = "Python Library for Tom's Obvious, Minimal Language" -category = "dev" -optional = false -python-versions = ">=2.6, !=3.0.*, !=3.1.*, !=3.2.*" -files = [ - {file = "toml-0.10.2-py2.py3-none-any.whl", hash = "sha256:806143ae5bfb6a3c6e736a764057db0e6a0e05e338b5630894a5f779cabb4f9b"}, - {file = "toml-0.10.2.tar.gz", hash = "sha256:b3bda1d108d5dd99f4a20d24d9c348e91c4db7ab1b749200bded2f839ccbe68f"}, -] - -[[package]] -name = "traitlets" -version = "5.0.5" -description = "Traitlets Python configuration system" -category = "dev" -optional = false -python-versions = ">=3.7" -files = [ - {file = "traitlets-5.0.5-py3-none-any.whl", hash = "sha256:69ff3f9d5351f31a7ad80443c2674b7099df13cc41fc5fa6e2f6d3b0330b0426"}, - {file = "traitlets-5.0.5.tar.gz", hash = "sha256:178f4ce988f69189f7e523337a3e11d91c786ded9360174a3d9ca83e79bc5396"}, -] - -[package.dependencies] -ipython-genutils = "*" - -[package.extras] -test = ["pytest"] - -[[package]] -name = "typed-ast" -version = "1.4.1" -description = "a fork of Python 2 and 3 ast modules with type comment support" -category = "dev" -optional = false -python-versions = "*" -files = [ - {file = "typed_ast-1.4.1-cp35-cp35m-manylinux1_i686.whl", hash = "sha256:73d785a950fc82dd2a25897d525d003f6378d1cb23ab305578394694202a58c3"}, - {file = "typed_ast-1.4.1-cp35-cp35m-manylinux1_x86_64.whl", hash = "sha256:aaee9905aee35ba5905cfb3c62f3e83b3bec7b39413f0a7f19be4e547ea01ebb"}, - {file = "typed_ast-1.4.1-cp35-cp35m-win32.whl", hash = "sha256:0c2c07682d61a629b68433afb159376e24e5b2fd4641d35424e462169c0a7919"}, - {file = "typed_ast-1.4.1-cp35-cp35m-win_amd64.whl", hash = "sha256:4083861b0aa07990b619bd7ddc365eb7fa4b817e99cf5f8d9cf21a42780f6e01"}, - {file = "typed_ast-1.4.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:269151951236b0f9a6f04015a9004084a5ab0d5f19b57de779f908621e7d8b75"}, - {file = "typed_ast-1.4.1-cp36-cp36m-manylinux1_i686.whl", hash = "sha256:24995c843eb0ad11a4527b026b4dde3da70e1f2d8806c99b7b4a7cf491612652"}, - {file = "typed_ast-1.4.1-cp36-cp36m-manylinux1_x86_64.whl", hash = "sha256:fe460b922ec15dd205595c9b5b99e2f056fd98ae8f9f56b888e7a17dc2b757e7"}, - {file = "typed_ast-1.4.1-cp36-cp36m-manylinux2014_aarch64.whl", hash = "sha256:fcf135e17cc74dbfbc05894ebca928ffeb23d9790b3167a674921db19082401f"}, - {file = "typed_ast-1.4.1-cp36-cp36m-win32.whl", hash = "sha256:4e3e5da80ccbebfff202a67bf900d081906c358ccc3d5e3c8aea42fdfdfd51c1"}, - {file = "typed_ast-1.4.1-cp36-cp36m-win_amd64.whl", hash = "sha256:249862707802d40f7f29f6e1aad8d84b5aa9e44552d2cc17384b209f091276aa"}, - {file = "typed_ast-1.4.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:8ce678dbaf790dbdb3eba24056d5364fb45944f33553dd5869b7580cdbb83614"}, - {file = "typed_ast-1.4.1-cp37-cp37m-manylinux1_i686.whl", hash = "sha256:c9e348e02e4d2b4a8b2eedb48210430658df6951fa484e59de33ff773fbd4b41"}, - {file = "typed_ast-1.4.1-cp37-cp37m-manylinux1_x86_64.whl", hash = "sha256:bcd3b13b56ea479b3650b82cabd6b5343a625b0ced5429e4ccad28a8973f301b"}, - {file = "typed_ast-1.4.1-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:f208eb7aff048f6bea9586e61af041ddf7f9ade7caed625742af423f6bae3298"}, - {file = "typed_ast-1.4.1-cp37-cp37m-win32.whl", hash = "sha256:d5d33e9e7af3b34a40dc05f498939f0ebf187f07c385fd58d591c533ad8562fe"}, - {file = "typed_ast-1.4.1-cp37-cp37m-win_amd64.whl", hash = "sha256:0666aa36131496aed8f7be0410ff974562ab7eeac11ef351def9ea6fa28f6355"}, - {file = "typed_ast-1.4.1-cp38-cp38-macosx_10_15_x86_64.whl", hash = "sha256:d205b1b46085271b4e15f670058ce182bd1199e56b317bf2ec004b6a44f911f6"}, - {file = "typed_ast-1.4.1-cp38-cp38-manylinux1_i686.whl", hash = "sha256:6daac9731f172c2a22ade6ed0c00197ee7cc1221aa84cfdf9c31defeb059a907"}, - {file = "typed_ast-1.4.1-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:498b0f36cc7054c1fead3d7fc59d2150f4d5c6c56ba7fb150c013fbc683a8d2d"}, - {file = "typed_ast-1.4.1-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:7e4c9d7658aaa1fc80018593abdf8598bf91325af6af5cce4ce7c73bc45ea53d"}, - {file = "typed_ast-1.4.1-cp38-cp38-win32.whl", hash = "sha256:715ff2f2df46121071622063fc7543d9b1fd19ebfc4f5c8895af64a77a8c852c"}, - {file = "typed_ast-1.4.1-cp38-cp38-win_amd64.whl", hash = "sha256:fc0fea399acb12edbf8a628ba8d2312f583bdbdb3335635db062fa98cf71fca4"}, - {file = "typed_ast-1.4.1-cp39-cp39-macosx_10_15_x86_64.whl", hash = "sha256:d43943ef777f9a1c42bf4e552ba23ac77a6351de620aa9acf64ad54933ad4d34"}, - {file = "typed_ast-1.4.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:92c325624e304ebf0e025d1224b77dd4e6393f18aab8d829b5b7e04afe9b7a2c"}, - {file = "typed_ast-1.4.1-cp39-cp39-manylinux1_i686.whl", hash = "sha256:d648b8e3bf2fe648745c8ffcee3db3ff903d0817a01a12dd6a6ea7a8f4889072"}, - {file = "typed_ast-1.4.1-cp39-cp39-manylinux1_x86_64.whl", hash = "sha256:fac11badff8313e23717f3dada86a15389d0708275bddf766cca67a84ead3e91"}, - {file = "typed_ast-1.4.1-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:0d8110d78a5736e16e26213114a38ca35cb15b6515d535413b090bd50951556d"}, - {file = "typed_ast-1.4.1-cp39-cp39-win32.whl", hash = "sha256:b52ccf7cfe4ce2a1064b18594381bccf4179c2ecf7f513134ec2f993dd4ab395"}, - {file = "typed_ast-1.4.1-cp39-cp39-win_amd64.whl", hash = "sha256:3742b32cf1c6ef124d57f95be609c473d7ec4c14d0090e5a5e05a15269fb4d0c"}, - {file = "typed_ast-1.4.1.tar.gz", hash = "sha256:8c8aaad94455178e3187ab22c8b01a3837f8ee50e09cf31f1ba129eb293ec30b"}, -] - -[[package]] -name = "urllib3" -version = "1.26.2" -description = "HTTP library with thread-safe connection pooling, file post, and more." -category = "main" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, <4" -files = [ - {file = "urllib3-1.26.2-py2.py3-none-any.whl", hash = "sha256:d8ff90d979214d7b4f8ce956e80f4028fc6860e4431f731ea4a8c08f23f99473"}, - {file = "urllib3-1.26.2.tar.gz", hash = "sha256:19188f96923873c92ccb987120ec4acaa12f0461fa9ce5d3d0772bc965a39e08"}, -] - -[package.extras] -brotli = ["brotlipy (>=0.6.0)"] -secure = ["certifi", "cryptography (>=1.3.4)", "idna (>=2.0.0)", "ipaddress", "pyOpenSSL (>=0.14)"] -socks = ["PySocks (>=1.5.6,!=1.5.7,<2.0)"] - -[[package]] -name = "virtualenv" -version = "20.4.2" -description = "Virtual Python Environment builder" -category = "dev" -optional = false -python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,>=2.7" -files = [ - {file = "virtualenv-20.4.2-py2.py3-none-any.whl", hash = "sha256:2be72df684b74df0ea47679a7df93fd0e04e72520022c57b479d8f881485dbe3"}, - {file = "virtualenv-20.4.2.tar.gz", hash = "sha256:147b43894e51dd6bba882cf9c282447f780e2251cd35172403745fc381a0a80d"}, -] - -[package.dependencies] -appdirs = ">=1.4.3,<2" -distlib = ">=0.3.1,<1" -filelock = ">=3.0.0,<4" -importlib-metadata = {version = ">=0.12", markers = "python_version < \"3.8\""} -six = ">=1.9.0,<2" - -[package.extras] -docs = ["proselint (>=0.10.2)", "sphinx (>=3)", "sphinx-argparse (>=0.2.5)", "sphinx-rtd-theme (>=0.4.3)", "towncrier (>=19.9.0rc1)"] -testing = ["coverage (>=4)", "coverage-enable-subprocess (>=1)", "flaky (>=3)", "packaging (>=20.0)", "pytest (>=4)", "pytest-env (>=0.6.2)", "pytest-freezegun (>=0.4.1)", "pytest-mock (>=2)", "pytest-randomly (>=1)", "pytest-timeout (>=1)", "xonsh (>=0.9.16)"] - -[[package]] -name = "waitress" -version = "1.4.4" -description = "Waitress WSGI server" -category = "main" -optional = false -python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,>=2.7" -files = [ - {file = "waitress-1.4.4-py2.py3-none-any.whl", hash = "sha256:3d633e78149eb83b60a07dfabb35579c29aac2d24bb803c18b26fb2ab1a584db"}, - {file = "waitress-1.4.4.tar.gz", hash = "sha256:1bb436508a7487ac6cb097ae7a7fe5413aefca610550baf58f0940e51ecfb261"}, -] - -[package.extras] -docs = ["Sphinx (>=1.8.1)", "docutils", "pylons-sphinx-themes (>=1.0.9)"] -testing = ["coverage (>=5.0)", "pytest", "pytest-cover"] - -[[package]] -name = "wcwidth" -version = "0.2.5" -description = "Measures the displayed width of unicode strings in a terminal" -category = "dev" -optional = false -python-versions = "*" -files = [ - {file = "wcwidth-0.2.5-py2.py3-none-any.whl", hash = "sha256:beb4802a9cebb9144e99086eff703a642a13d6a0052920003a230f3294bbe784"}, - {file = "wcwidth-0.2.5.tar.gz", hash = "sha256:c4d647b99872929fdb7bdcaa4fbe7f01413ed3d98077df798530e5b04f116c83"}, -] - -[[package]] -name = "werkzeug" -version = "2.2.3" -description = "The comprehensive WSGI web application library." -category = "main" -optional = false -python-versions = ">=3.7" -files = [ - {file = "Werkzeug-2.2.3-py3-none-any.whl", hash = "sha256:56433961bc1f12533306c624f3be5e744389ac61d722175d543e1751285da612"}, - {file = "Werkzeug-2.2.3.tar.gz", hash = "sha256:2e1ccc9417d4da358b9de6f174e3ac094391ea1d4fbef2d667865d819dfd0afe"}, -] - -[package.dependencies] -MarkupSafe = ">=2.1.1" - -[package.extras] -watchdog = ["watchdog"] - -[[package]] -name = "zipp" -version = "3.4.0" -description = "Backport of pathlib-compatible object wrapper for zip files" -category = "dev" -optional = false -python-versions = ">=3.6" -files = [ - {file = "zipp-3.4.0-py3-none-any.whl", hash = "sha256:102c24ef8f171fd729d46599845e95c7ab894a4cf45f5de11a44cc7444fb1108"}, - {file = "zipp-3.4.0.tar.gz", hash = "sha256:ed5eee1974372595f9e416cc7bbeeb12335201d8081ca8a0743c954d4446e5cb"}, -] - -[package.extras] -docs = ["jaraco.packaging (>=3.2)", "rst.linker (>=1.9)", "sphinx"] -testing = ["func-timeout", "jaraco.itertools", "jaraco.test (>=3.2.0)", "pytest (>=3.5,!=3.7.3)", "pytest-black (>=0.3.7)", "pytest-checkdocs (>=1.2.3)", "pytest-cov", "pytest-flake8", "pytest-mypy"] - -[metadata] -lock-version = "2.0" -python-versions = "^3.7" -content-hash = "e4014ee68179696ae11e98413b379d11d25c4169a7373a36218c2b085c95cc8f" diff --git a/pyproject.toml b/pyproject.toml deleted file mode 100644 index 1e485cd..0000000 --- a/pyproject.toml +++ /dev/null @@ -1,43 +0,0 @@ -[tool.poetry] -name = "butterrobot" -version = "0.0.3" -description = "What is my purpose?" -authors = ["Felipe Martin "] -license = "GPL-2.0" -packages = [ - { include = "butterrobot" }, - { include = "butterrobot_plugins_contrib" }, -] -include = ["README.md"] -readme = "README.md" - -[tool.poetry.dependencies] -python = "^3.7" -structlog = "^20.1.0" -colorama = "^0.4.3" -dice = "^3.1.0" -flask = "^1.1.2" -requests = "^2.24.0" -waitress = "^1.4.4" -dataset = "^1.3.2" - -[tool.poetry.dev-dependencies] -black = "^19.10b0" -flake8 = "^3.7.9" -rope = "^0.16.0" -isort = "^4.3.21" -ipdb = "^0.13.2" -pytest = "^6.1.2" -pytest-cov = "^2.10.1" -pre-commit = "^2.10.0" - -[tool.poetry.plugins] -[tool.poetry.plugins."butterrobot.plugins"] -"fun.loquito" = "butterrobot_plugins_contrib.fun:LoquitoPlugin" -"fun.dice" = "butterrobot_plugins_contrib.fun:DicePlugin" -"fun.coin" = "butterrobot_plugins_contrib.fun:CoinPlugin" -"dev.ping" = "butterrobot_plugins_contrib.dev:PingPlugin" - -[build-system] -requires = ["poetry>=0.12"] -build-backend = "poetry.masonry.api" diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index 08f065e..0000000 --- a/setup.cfg +++ /dev/null @@ -1,16 +0,0 @@ -[flake8] -ignore = E203, E266, E501, W503, F403 -max-line-length = 88 -max-complexity = 18 -select = B,C,E,F,W,T4,B9 - -[isort] -use_parentheses = True -multi_line_output = 3 -include_trailing_comma = True -length_sort = 1 -lines_between_types = 0 -line_length = 88 -known_third_party = dataset,dice,flask,pkg_resources,pytest,requests,structlog -sections = FUTURE, STDLIB, DJANGO, THIRDPARTY, FIRSTPARTY, LOCALFOLDER -no_lines_before = LOCALFOLDER diff --git a/tests/test_db.py b/tests/test_db.py deleted file mode 100644 index 38c9e2e..0000000 --- a/tests/test_db.py +++ /dev/null @@ -1,109 +0,0 @@ -import os.path -import tempfile -from dataclasses import dataclass -from unittest import mock - -import dataset -import pytest - -from butterrobot import db - - -@dataclass -class DummyItem: - id: int - foo: str - - -class DummyQuery(db.Query): - tablename = "dummy" - obj = DummyItem - - -class MockDatabase: - def __init__(self): - self.temp_dir = tempfile.TemporaryDirectory() - - def __enter__(self): - db_path = os.path.join(self.temp_dir.name, "db.sqlite") - db.db = dataset.connect(f"sqlite:///{db_path}") - - def __exit__(self, exc_type, exc_val, exc_tb): - self.temp_dir.cleanup() - - -def test_query_create_ok(): - with MockDatabase(): - assert DummyQuery.create(foo="bar") - - -def test_query_delete_ok(): - with MockDatabase(): - item_id = DummyQuery.create(foo="bar") - assert DummyQuery.delete(item_id) - - -def test_query_exists_by_id_ok(): - with MockDatabase(): - assert not DummyQuery.exists(id=1) - item_id = DummyQuery.create(foo="bar") - assert DummyQuery.exists(id=item_id) - - -def test_query_exists_by_attribute_ok(): - with MockDatabase(): - assert not DummyQuery.exists(id=1) - item_id = DummyQuery.create(foo="bar") - assert DummyQuery.exists(foo="bar") - - -def test_query_get_ok(): - with MockDatabase(): - item_id = DummyQuery.create(foo="bar") - item = DummyQuery.get(id=item_id) - assert item.id - - -def test_query_all_ok(): - with MockDatabase(): - assert len(list(DummyQuery.all())) == 0 - [DummyQuery.create(foo="bar") for i in range(0, 3)] - assert len(list(DummyQuery.all())) == 3 - - -def test_update_ok(): - with MockDatabase(): - expected = "bar2" - item_id = DummyQuery.create(foo="bar") - assert DummyQuery.update(item_id, foo=expected) - item = DummyQuery.get(id=item_id) - assert item.foo == expected - - -def test_create_user_sets_password_ok(): - password = "password" - with MockDatabase(): - user_id = db.UserQuery.create(username="foo", password=password) - user = db.UserQuery.get(id=user_id) - assert user.password == db.UserQuery._hash_password(password) - - -def test_user_check_credentials_ok(): - with MockDatabase(): - username = "foo" - password = "bar" - user_id = db.UserQuery.create(username=username, password=password) - user = db.UserQuery.get(id=user_id) - user = db.UserQuery.check_credentials(username, password) - assert isinstance(user, db.UserQuery.obj) - - -def test_user_check_credentials_ko(): - with MockDatabase(): - username = "foo" - password = "bar" - user_id = db.UserQuery.create(username=username, password=password) - user = db.UserQuery.get(id=user_id) - assert not db.UserQuery.check_credentials(username, "error") - assert not db.UserQuery.check_credentials("error", password) - assert not db.UserQuery.check_credentials("error", "error") diff --git a/tests/test_objects.py b/tests/test_objects.py deleted file mode 100644 index ffab485..0000000 --- a/tests/test_objects.py +++ /dev/null @@ -1,18 +0,0 @@ -from butterrobot.objects import Channel, ChannelPlugin - - -def test_channel_has_enabled_plugin_ok(): - channel = Channel( - platform="debug", - platform_channel_id="debug", - channel_raw={}, - plugins={ - "enabled": ChannelPlugin( - id=1, channel_id="test", plugin_id="enabled", enabled=True - ), - "existant": ChannelPlugin(id=2, channel_id="test", plugin_id="existant"), - }, - ) - assert not channel.has_enabled_plugin("non.existant") - assert not channel.has_enabled_plugin("existant") - assert channel.has_enabled_plugin("enabled")