~sgeisenh/streamnotify

8f231ebf02cb1cbd2457e4ad85c217bc013637e3 — Samuel Eisenhandler 1 year, 5 months ago
Initial commit
7 files changed, 179 insertions(+), 0 deletions(-)

A .dockerignore
A .gitignore
A LICENSE
A Procfile
A fly.toml
A requirements.txt
A server.py
A  => .dockerignore +1 -0
@@ 1,1 @@
fly.toml

A  => .gitignore +1 -0
@@ 1,1 @@
venv

A  => LICENSE +19 -0
@@ 1,19 @@
Copyright (c) 2023 Samuel Eisenhandler

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

A  => Procfile +2 -0
@@ 1,2 @@
# Modify this Procfile to fit your needs
web: gunicorn server:app

A  => fly.toml +41 -0
@@ 1,41 @@
# fly.toml file generated for stream-notify on 2023-02-07T11:50:21-05:00

app = "stream-notify"
kill_signal = "SIGINT"
kill_timeout = 5
processes = []

[build]
  builder = "paketobuildpacks/builder:base"

[env]
  PORT = "8080"

[experimental]
  auto_rollback = true

[[services]]
  http_checks = []
  internal_port = 8080
  processes = ["app"]
  protocol = "tcp"
  script_checks = []
  [services.concurrency]
    hard_limit = 25
    soft_limit = 20
    type = "connections"

  [[services.ports]]
    force_https = true
    handlers = ["http"]
    port = 80

  [[services.ports]]
    handlers = ["tls", "http"]
    port = 443

  [[services.tcp_checks]]
    grace_period = "1s"
    interval = "15s"
    restart_limit = 0
    timeout = "2s"

A  => requirements.txt +12 -0
@@ 1,12 @@
certifi==2022.12.7
charset-normalizer==3.0.1
click==8.1.3
Flask==2.2.2
gunicorn==20.1.0
idna==3.4
itsdangerous==2.1.2
Jinja2==3.1.2
MarkupSafe==2.1.2
requests==2.28.2
urllib3==1.26.14
Werkzeug==2.2.2

A  => server.py +103 -0
@@ 1,103 @@
import hmac
import os
from logging.config import dictConfig
from typing import Final

import requests
from flask import Flask, request, abort

dictConfig(
    {
        "version": 1,
        "formatters": {
            "default": {
                "format": "[%(asctime)s] %(levelname)s in %(module)s: %(message)s",
            }
        },
        "handlers": {
            "wsgi": {
                "class": "logging.StreamHandler",
                "stream": "ext://flask.logging.wsgi_errors_stream",
                "formatter": "default",
            }
        },
        "root": {"level": "DEBUG", "handlers": ["wsgi"]},
    }
)


app = Flask(__name__)


# Environment variables.
TWITCH_SECRET: Final[bytes] = os.environ["TWITCH_SECRET"].encode()
ZULIP_KEY: Final[str] = os.environ["ZULIP_KEY"]
ZULIP_EMAIL: Final[str] = os.environ["ZULIP_EMAIL"]
MESSAGES_URL = "https://recurse.zulipchat.com/api/v1/messages"
MEMBERS_URL = "https://recurse.zulipchat.com/api/v1/users"

TWITCH_MESSAGE_ID: Final[str] = "twitch-eventsub-message-id"
TWITCH_MESSAGE_TIMESTAMP: Final[str] = "twitch-eventsub-message-timestamp"
TWITCH_MESSAGE_SIGNATURE: Final[str] = "twitch-eventsub-message-signature"
TWITCH_MESSAGE_TYPE: Final[str] = "twitch-eventsub-message-type"

HMAC_PREFIX: Final[str] = "sha256="

STREAM: Final[str] = "livestream notifications"


def get_hmac_message(request):
    return (
        request.headers[TWITCH_MESSAGE_ID].encode()
        + request.headers[TWITCH_MESSAGE_TIMESTAMP].encode()
        + request.get_data()
    )


def get_hmac(message):
    return hmac.new(TWITCH_SECRET, message, "sha256").hexdigest()


@app.route("/")
def index():
    return "Hey there, how's it going?"


@app.route("/callback", methods=["POST"])
def callback():
    body = request.json
    assert body is not None
    message = get_hmac_message(request)
    truth = HMAC_PREFIX + get_hmac(message)

    if not hmac.compare_digest(truth, request.headers[TWITCH_MESSAGE_SIGNATURE]):
        app.logger.warning("Invalid digest")
        abort(403)

    app.logger.info("Valid digest!")

    match request.headers[TWITCH_MESSAGE_TYPE]:
        case "webhook_callback_verification":
            app.logger.info("Replying to challenge!")
            return body["challenge"]
        case "notification":
            # TODO: We should handle duplicate events gracefully
            # https://dev.twitch.tv/docs/eventsub/#handling-duplicate-events
            event = body["event"]
            app.logger.info(f"Received event: {event}")
            user_login = event["broadcaster_user_login"]
            subject = f"{user_login} stream online notifications"
            message = f"Channel [{user_login}](https://twitch.tv/{user_login}) has started a stream!"
            send_message_zulip(subject, message)
    return "", 204


def send_message_zulip(subject, content):
    data = {"type": "stream", "to": STREAM, "subject": subject, "content": content}
    try:
        app.logger.info("Sending message '%s' with data '%s'", content, data)
        response = requests.post(MESSAGES_URL, data=data, auth=(ZULIP_EMAIL, ZULIP_KEY))
        return response.status_code == 200
    except Exception as e:
        app.logger.exception(e)
        return False