From 0fad033ff38707e07011b7008d506cf4fcdaa7ec Mon Sep 17 00:00:00 2001 From: terminaldweller Date: Fri, 12 Nov 2021 11:57:17 +0330 Subject: restructured the repo-WIP --- .travis.yml | 18 -- Dockerfile | 18 -- docker-entrypoint.sh | 8 - go.mod | 12 - go.sum | 115 -------- hived.go | 675 ------------------------------------------- hived/Dockerfile | 18 ++ hived/docker-entrypoint.sh | 8 + hived/go.mod | 12 + hived/go.sum | 115 ++++++++ hived/hived.go | 675 +++++++++++++++++++++++++++++++++++++++++++ run.sh | 2 - runtravis.sh | 2 - telebot/Dockerfile | 18 ++ telebot/docker-entrypoint.sh | 8 + telebot/go.mod | 10 + telebot/go.sum | 35 +++ telebot/main.go | 92 ++++++ telebot/telebot | Bin 0 -> 7115842 bytes 19 files changed, 991 insertions(+), 850 deletions(-) delete mode 100644 .travis.yml delete mode 100644 Dockerfile delete mode 100755 docker-entrypoint.sh delete mode 100644 go.mod delete mode 100644 go.sum delete mode 100644 hived.go create mode 100644 hived/Dockerfile create mode 100755 hived/docker-entrypoint.sh create mode 100644 hived/go.mod create mode 100644 hived/go.sum create mode 100644 hived/hived.go delete mode 100755 run.sh delete mode 100755 runtravis.sh create mode 100644 telebot/Dockerfile create mode 100755 telebot/docker-entrypoint.sh create mode 100644 telebot/go.mod create mode 100644 telebot/go.sum create mode 100644 telebot/main.go create mode 100755 telebot/telebot diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index f0314d1..0000000 --- a/.travis.yml +++ /dev/null @@ -1,18 +0,0 @@ -language: go -go: - - 1.15 -env: - matrix: - - DOCKER_COMPOSE_VERSION=1.25.0 - global: - - secure: JW0y+F2BaxmKH00lv/jfiAo2ezMe383oqhA7PozarjYDrksU/cGKgdUay89STXZrN68p+oOIAaGnVM3SGWoKi0gCuDIZKYVVhhCitctnG13toQkvQda8+ceme8spv6ryicX0f2Kpfoe/2tp0cQo1aU16UZ7Zy6pX0Kok62h3wxm5m7ce0lBCyOJkNmHNNCAPgV9VqwpQLPnJyMh0tLuSQLDnKYV+LmNNL2IHVKpg6HRQh01fHvWWI2W+wGhrX4Yerdlm78rcdMJNISulhyyJxCgW5qWyJuIh+/LWX4fhGtIpLB3XZulIQWhjmBTnxHh2UGHYn4iMbMeZ3zdqewv5XBQv55lFuaERF3j7pVRnC+XFJIE9arVvHM0EMkd05O+CbxnPe2gTMIbxQTbVRPq3WzPzLf6o+MmJE+Gib3mz7beIAUbl+YGB6t+Kfgk16RUJrHINYHFXh/aksSbg7IjZT6gPDbtRxsggJPcqUaa5aaIK8wtJxMFxSs53IVUWk5i1kL/Z2J0ulqohZC+94C5HZJf7hZKJkXdX5OToCt+wRQPPuxS2HNKUtrWaxwae9Baxy4NSBbUoHabqUg+uE0cvY10t53RoyJyDZYEiGv3AyUDqUGUvRIy5iM9WDFFbMpbfMdiJE7oRUxfq+DnHAK4AWNfOlAvdijemK7XL42cm4ds= - - secure: CcatNUm2YY/aGXouNpPeMpnBneoTGLvDpZ7fttI22ZyGDVBShuxgcaHZ2T6Kh4bf+vNWUhVfFoHR7ODJwOARpr6L0GprEZoIqZb1DFdS1fTygvewlMzC4GeTHXRyCZRDtFpQahnNG1MA+ybFgtMI3osEb279+oNA4Mq1wBBECJ1ZT1aXb02wNLs0DygYjEaFzjPEpmMCFoiHwmT5caohHdMx4BNTDWVQtomyE56MGi0ymuHg8TNMUYTiZGLKhcIR8p0RDqs3qs/539DZtISvGsNQjGegk9YhaE13YyhF0wGRT6mzIH8ArGallr4RRMIazvIt3e9nPL67o+YBFlsvWJXqVWp1yScyerFjNk/KR7WDMYCHzyT3g4qTJAt9HPnvboorteLIMPK4yFWzEtLIMtMnWwnWv2qdqXwMRmxIJ3I/tZEX/WMVWRp07mMZJjjtyc5sM28tQze9BxRiKWMC8GFSoSvwr1BNUJMvJX1YCBSPbpRRG37uF6TkC3n4deM0jdQZen2ihM5IDSC2R5gJYEC8xI9pOsdMsj3OZbhZ2qe+4s8jZrz5kGgY3LQLeqXIDwmeMrJ3wJSsiDhG2YoUdGmro3g5ZEdxuPffAVtqaZB7r7qbn/W25Jptghabn1cH7lAnQ1CTwOlzOBc+8+MiZNVG/YRqDuc4u2vacn8Xhm8= - - secure: ZhSnKN3JLlAXfK9bTTnqTwYINp5j71ZqYlbPAhRKKl3VuUM1OhrC9iWRmxLj0t6r82u5dS9M7dYJWowwLhqkPSWlI/lYqy+4EYtmn+Qa2r7GrRkMsx/CkdC/C3okumJf9gpaYIpJMr7pkUeWbJd6zh/cGxD426NeAv2r2paiGd2rn+AlD67xDcOhJCqAczOHKjSMKLAVsRU6p7rB6Vie1dvY/FrL+enkjlJfWcaEyA5nWiky34Qz81IxqHKaz/4h9Kg3iVwu60Rh86WHu877AbPVykJS+/bZ+l/2FWI3zduifmpm5okf3YLV9XnYFZXmgD8efQi5b/cy5AdbjdnKtTJ/jiM0Ygbd3YfVc/bWb+unLWcr5/f6xaHUKEAlDSIXX8Mu4a2yrBkiUB99XZ+pqo7tC2Heqzytx0iqVxAeTLTx23Ce0e3gzRMGnSV5TW983W/xTlFmGSvgzAfzr/tZC+4DUcRRf6cSWH/CxxTRWrF8p4XeBfbZudD6629i16K1v8iM8sZvAWg1QnhU1qWIHOkVAkMbwPewLN6MVhc2JRMG0eFTn5EMIK5MpCPot2inY10VfcPnswHBSocVUEjhAQ+RtNQyBk9Oc3BhCckZUctR66IWH9bcXvO5MAqOVrEWxzNf2Kf837TZLLJBX36OKwzZCIhLz3Hx3Pd2/7AD+Qs= -services: -- docker -before_install: -- docker pull redis:6.2-alpine -install: -# - docker build -t hived ./ && docker-compose -f ./docker-compose-travis.yaml up -d -# - "./test/endpoints.sh" - - go build diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index 0a9e3e2..0000000 --- a/Dockerfile +++ /dev/null @@ -1,18 +0,0 @@ -FROM alpine:3.13 as builder -RUN apk update && apk upgrade -RUN apk add go git -COPY go.* /hived/ -RUN cd /hived && go mod download -COPY *.go /hived/ -RUN cd /hived && go build - -FROM node:lts-alpine3.13 AS certbuilder -RUN apk add openssl -WORKDIR /certs -RUN openssl req -nodes -new -x509 -subj="/C=US/ST=Denial/L=springfield/O=Dis/CN=localhost" -keyout server.key -out server.cert - -FROM gcr.io/distroless/static-debian10 -COPY --from=certbuilder /cert/ /cert/ -COPY --from=builder /hived/hived /hived/ -COPY ./docker-entrypoint.sh /hived/ -ENTRYPOINT ["/hived/docker-entrypoint.sh"] diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh deleted file mode 100755 index 932c9c9..0000000 --- a/docker-entrypoint.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env sh -set -ex - -export $(cat /run/secrets/tg_bot_token) -export $(cat /run/secrets/ch_api_key) -export $(cat /run/secrets/ch_api_secret) - -"/hived/hived" "$@" diff --git a/go.mod b/go.mod deleted file mode 100644 index 97de2d8..0000000 --- a/go.mod +++ /dev/null @@ -1,12 +0,0 @@ -module github.com/terminaldweller/hived - -go 1.15 - -require ( - github.com/Knetic/govaluate v3.0.0+incompatible - github.com/go-redis/redis/v8 v8.6.0 - github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible - github.com/gorilla/mux v1.8.0 - github.com/rs/zerolog v1.20.0 - github.com/technoweenie/multipartstreamer v1.0.1 // indirect -) diff --git a/go.sum b/go.sum deleted file mode 100644 index 07ad2bc..0000000 --- a/go.sum +++ /dev/null @@ -1,115 +0,0 @@ -github.com/Knetic/govaluate v3.0.0+incompatible h1:7o6+MAPhYTCF0+fdvoz1xDedhRb4f6s9Tn1Tt7/WTEg= -github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= -github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= -github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= -github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= -github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= -github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= -github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= -github.com/go-redis/redis/v8 v8.6.0 h1:swqbqOrxaPztsj2Hf1p94M3YAgl7hYEpcw21z299hh8= -github.com/go-redis/redis/v8 v8.6.0/go.mod h1:DQ9q4Rk2HtwkrwVrdgmphoOQDMfpvcd/nHEwRsicg8s= -github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible h1:2cauKuaELYAEARXRkq2LrJ0yDDv1rW7+wrTEdVL3uaU= -github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible/go.mod h1:qf9acutJ8cwBUhm1bqgz6Bei9/C/c93FPDljKWwsOgM= -github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= -github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= -github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= -github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= -github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= -github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0= -github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.4 h1:L8R9j+yAqZuZjsqh/z+F1NCffTKKLShY6zXTItVIZ8M= -github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= -github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= -github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= -github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78= -github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= -github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= -github.com/onsi/ginkgo v1.15.0 h1:1V1NfVQR87RtWAgp1lv9JZJ5Jap+XFGKPi00andXGi4= -github.com/onsi/ginkgo v1.15.0/go.mod h1:hF8qUzuuC8DJGygJH3726JnCZX4MYbRB8yFfISqnKUg= -github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= -github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= -github.com/onsi/gomega v1.10.5 h1:7n6FEkpFmfCoo2t+YYqXH0evK+a9ICQz0xcAy9dYcaQ= -github.com/onsi/gomega v1.10.5/go.mod h1:gza4q3jKQJijlu05nKWRCW/GavJumGt8aNRxWg7mt48= -github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ= -github.com/rs/zerolog v1.20.0 h1:38k9hgtUBdxFwE34yS8rTHmHBa4eN16E4DJlv177LNs= -github.com/rs/zerolog v1.20.0/go.mod h1:IzD0RJ65iWH0w97OQQebJEvTZYvsCUm9WVLWBQrJRjo= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/technoweenie/multipartstreamer v1.0.1 h1:XRztA5MXiR1TIRHxH2uNxXxaIkKQDeX7m2XsSOlQEnM= -github.com/technoweenie/multipartstreamer v1.0.1/go.mod h1:jNVxdtShOxzAsukZwTSw6MDx5eUJoiEBsSvzDU9uzog= -github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -go.opentelemetry.io/otel v0.17.0 h1:6MKOu8WY4hmfpQ4oQn34u6rYhnf2sWf1LXYO/UFm71U= -go.opentelemetry.io/otel v0.17.0/go.mod h1:Oqtdxmf7UtEvL037ohlgnaYa1h7GtMh0NcSd9eqkC9s= -go.opentelemetry.io/otel/metric v0.17.0 h1:t+5EioN8YFXQ2EH+1j6FHCKMUj+57zIDSnSGr/mWuug= -go.opentelemetry.io/otel/metric v0.17.0/go.mod h1:hUz9lH1rNXyEwWAhIWCMFWKhYtpASgSnObJFnU26dJ0= -go.opentelemetry.io/otel/oteltest v0.17.0 h1:TyAihUowTDLqb4+m5ePAsR71xPJaTBJl4KDArIdi9k4= -go.opentelemetry.io/otel/oteltest v0.17.0/go.mod h1:JT/LGFxPwpN+nlsTiinSYjdIx3hZIGqHCpChcIZmdoE= -go.opentelemetry.io/otel/trace v0.17.0 h1:SBOj64/GAOyWzs5F680yW1ITIfJkm6cJWL2YAvuL9xY= -go.opentelemetry.io/otel/trace v0.17.0/go.mod h1:bIujpqg6ZL6xUTubIUgziI1jSaUPthmabA/ygf/6Cfg= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb h1:eBmm0M9fYhWpKZLjQUUKka/LtIxf46G4fxeEz5KJr9U= -golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210112080510-489259a85091 h1:DMyOG0U+gKfu8JZzg2UQe9MeaC1X+xQWlAKcRnjxjCw= -golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190828213141-aed303cbaa74/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= -google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= -google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= -google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= -google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= -google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM= -google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= -gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= -gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= -gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= -gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/hived.go b/hived.go deleted file mode 100644 index 5345e70..0000000 --- a/hived.go +++ /dev/null @@ -1,675 +0,0 @@ -package main - -import ( - "bytes" - "context" - "crypto/hmac" - "crypto/sha512" - "crypto/tls" - "encoding/hex" - "encoding/json" - "errors" - "flag" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "os" - "os/signal" - "strconv" - "sync" - "time" - - "github.com/Knetic/govaluate" - "github.com/go-redis/redis/v8" - tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api" - "github.com/gorilla/mux" - "github.com/rs/zerolog" - "github.com/rs/zerolog/log" -) - -var ( - flagPort = flag.String("port", "8008", "determined the port the sercice runs on") - alertsCheckInterval = flag.Int64("alertinterval", 600., "in seconds, the amount of time between alert checks") - redisAddress = flag.String("redisaddress", "redis:6379", "determines the address of the redis instance") - redisPassword = flag.String("redispassword", "", "determines the password of the redis db") - redisDB = flag.Int64("redisdb", 0, "determines the db number") - botChannelID = flag.Int64("botchannelid", 146328407, "determines the channel id the telgram bot should send messages to") - rdb *redis.Client -) - -const ( - cryptocomparePriceURL = "https://min-api.cryptocompare.com/data/price?" - changellyURL = "https://api.changelly.com" - TELEGRAM_BOT_TOKEN_ENV_VAR = "TELEGRAM_BOT_TOKEN" - CHANGELLY_API_KEY_ENV_VAR = "CHANGELLY_API_KEY" - CHANGELLY_API_SECRET_ENV_VAR = "CHANGELLY_API_SECRET" - SERVER_DEPLOYMENT_TYPE = "SERVER_DEPLOYMENT_TYPE" -) - -func runTgBot() { - // bot := getTgBot() - token := os.Getenv(TELEGRAM_BOT_TOKEN_ENV_VAR) - bot, err := tgbotapi.NewBotAPI(token[1 : len(token)-1]) - if err != nil { - log.Error().Err(err) - } - log.Debug().Msg("authorized on account bot_bloodstalker") - - update := tgbotapi.NewUpdate(0) - update.Timeout = 60 - - updates, err := bot.GetUpdatesChan(update) - if err != nil { - log.Error().Err(err) - } - - for update := range updates { - if update.Message == nil { - continue - } - - log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text) - - msg := tgbotapi.NewMessage(update.Message.Chat.ID, update.Message.Text) - msg.ReplyToMessageID = update.Message.MessageID - - bot.Send(msg) - } -} - -type priceChanStruct struct { - name string - price float64 -} - -type errorChanStruct struct { - hasError bool - err error -} - -func sendGetToCryptoCompare( - name, unit string, - wg *sync.WaitGroup, - priceChan chan<- priceChanStruct, - errChan chan<- errorChanStruct) { - defer wg.Done() - - params := "fsym=" + url.QueryEscape(name) + "&" + - "tsyms=" + url.QueryEscape(unit) - path := cryptocomparePriceURL + params - resp, err := http.Get(path) - if err != nil { - priceChan <- priceChanStruct{name: name, price: 0.} - errChan <- errorChanStruct{hasError: true, err: err} - log.Error().Err(err) - } - defer resp.Body.Close() - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - priceChan <- priceChanStruct{name: name, price: 0.} - errChan <- errorChanStruct{hasError: true, err: err} - log.Error().Err(err) - } - - jsonBody := make(map[string]float64) - err = json.Unmarshal(body, &jsonBody) - if err != nil { - priceChan <- priceChanStruct{name: name, price: 0.} - errChan <- errorChanStruct{hasError: true, err: err} - log.Error().Err(err) - } - - log.Info().Msg(string(body)) - - priceChan <- priceChanStruct{name: name, price: jsonBody[unit]} - errChan <- errorChanStruct{hasError: false, err: nil} -} - -func priceHandler(w http.ResponseWriter, r *http.Request) { - w.Header().Add("Content-Type", "application/json") - if r.Method != "GET" { - http.Error(w, "Method is not supported.", http.StatusNotFound) - } - - var name string - var unit string - params := r.URL.Query() - for key, value := range params { - switch key { - case "name": - name = value[0] - case "unit": - unit = value[0] - default: - log.Error().Err(errors.New("bad parameters for the crypto endpoint.")) - } - } - - if name == "" || unit == "" { - json.NewEncoder(w).Encode(map[string]interface{}{ - "err": "query parameters must include name and unit", - "isSuccessful": false}) - log.Error().Err(errors.New("query parameters must include name and unit.")) - return - } - - var wg sync.WaitGroup - priceChan := make(chan priceChanStruct, 1) - errChan := make(chan errorChanStruct, 1) - defer close(errChan) - defer close(priceChan) - wg.Add(1) - go sendGetToCryptoCompare(name, unit, &wg, priceChan, errChan) - wg.Wait() - - select { - case err := <-errChan: - if err.hasError != false { - log.Error().Err(err.err) - } - default: - log.Error().Err(errors.New("this shouldn't have happened'")) - } - - var price priceChanStruct - select { - case priceCh := <-priceChan: - price = priceCh - default: - log.Fatal().Err(errors.New("this shouldnt have happened")) - } - - json.NewEncoder(w).Encode(map[string]interface{}{ - "name": price.name, - "price": price.price, - "unit": unit, - "err": "", - "isSuccessful": true}) -} - -func pairHandler(w http.ResponseWriter, r *http.Request) { - var err error - w.Header().Add("Content-Type", "application/json") - if r.Method != "GET" { - http.Error(w, "Method is not supported.", http.StatusNotFound) - } - - var one string - var two string - var multiplier float64 - params := r.URL.Query() - for key, value := range params { - switch key { - case "one": - one = value[0] - case "two": - two = value[0] - case "multiplier": - multiplier, err = strconv.ParseFloat(value[0], 64) - if err != nil { - log.Fatal().Err(err) - } - default: - log.Fatal().Err(errors.New("unknown parameters for the pair endpoint.")) - } - } - - if one == "" || two == "" || multiplier == 0. { - log.Error().Err(errors.New("the query must include one()),two and multiplier")) - } - - var wg sync.WaitGroup - priceChan := make(chan priceChanStruct, 2) - errChan := make(chan errorChanStruct, 2) - defer close(priceChan) - defer close(errChan) - - wg.Add(2) - go sendGetToCryptoCompare(one, "USD", &wg, priceChan, errChan) - go sendGetToCryptoCompare(two, "USD", &wg, priceChan, errChan) - wg.Wait() - - for i := 0; i < 2; i++ { - select { - case err := <-errChan: - if err.hasError != false { - log.Error().Err(err.err) - } - default: - log.Fatal().Err(errors.New("this shouldnt have happened")) - } - } - - var priceOne float64 - var priceTwo float64 - for i := 0; i < 2; i++ { - select { - case price := <-priceChan: - if price.name == one { - priceOne = price.price - } - if price.name == two { - priceTwo = price.price - } - default: - log.Fatal().Err(errors.New("this shouldnt have happened")) - } - } - - ratio := priceOne * multiplier / priceTwo - log.Info().Msg(fmt.Sprintf("%v", ratio)) - json.NewEncoder(w).Encode(map[string]interface{}{"ratio": ratio}) -} - -type alertType struct { - Name string `json:"name"` - Expr string `json:"expr"` -} - -type alertsType struct { - Alerts []alertType `json:"alerts"` -} - -func getAlerts() (alertsType, error) { - var alerts alertsType - ctx := context.Background() - keys := rdb.SMembersMap(ctx, "alertkeys") - alerts.Alerts = make([]alertType, len(keys.Val())) - vals := keys.Val() - - i := 0 - for key := range vals { - alert := rdb.Get(ctx, key[6:]) - expr, _ := alert.Result() - alerts.Alerts[i].Name = key - alerts.Alerts[i].Expr = expr - i++ - } - - return alerts, nil -} - -func alertManager() { - for { - alerts, err := getAlerts() - if err != nil { - log.Error().Err(err) - return - } - log.Info().Msg(fmt.Sprintf("%v", alerts)) - - for i := range alerts.Alerts { - expression, err := govaluate.NewEvaluableExpression(alerts.Alerts[i].Expr) - if err != nil { - log.Error().Err(err) - continue - } - - vars := expression.Vars() - parameters := make(map[string]interface{}, len(vars)) - - var wg sync.WaitGroup - priceChan := make(chan priceChanStruct, len(vars)) - errChan := make(chan errorChanStruct, len(vars)) - defer close(priceChan) - defer close(errChan) - wg.Add(len(vars)) - - for i := range vars { - go sendGetToCryptoCompare(vars[i], "USD", &wg, priceChan, errChan) - } - wg.Wait() - - for i := 0; i < len(vars); i++ { - select { - case err := <-errChan: - if err.hasError != false { - log.Printf(err.err.Error()) - } - default: - log.Error().Err(errors.New("this shouldnt have happened")) - } - } - - for i := 0; i < len(vars); i++ { - select { - case price := <-priceChan: - parameters[price.name] = price.price - default: - log.Error().Err(errors.New("this shouldnt have happened")) - } - } - - log.Info().Msg(fmt.Sprintf("parameters: %v", parameters)) - result, err := expression.Evaluate(parameters) - if err != nil { - log.Error().Err(err) - } - - var resultBool bool - log.Info().Msg(fmt.Sprintf("result: %v", result)) - resultBool = result.(bool) - if resultBool == true { - // bot := getTgBot() - token := os.Getenv(TELEGRAM_BOT_TOKEN_ENV_VAR) - bot, err := tgbotapi.NewBotAPI(token[1 : len(token)-1]) - if err != nil { - log.Error().Err(err) - } - msgText := "notification " + alerts.Alerts[i].Expr + " has been triggered" - msg := tgbotapi.NewMessage(*botChannelID, msgText) - bot.Send(msg) - } - } - - time.Sleep(time.Second * time.Duration(*alertsCheckInterval)) - } -} - -type addAlertJSONType struct { - Name string `json:"name"` - Expr string `json:"expr"` -} - -func handleAlertPost(w http.ResponseWriter, r *http.Request) { - w.Header().Add("Content-Type", "application/json") - bodyBytes, err := ioutil.ReadAll(r.Body) - if err != nil { - log.Printf(err.Error()) - } - - var bodyJSON addAlertJSONType - json.Unmarshal(bodyBytes, &bodyJSON) - - if bodyJSON.Name == "" || bodyJSON.Expr == "" { - json.NewEncoder(w).Encode(map[string]interface{}{ - "isSuccessful": false, - "error": "not all parameters are valid."}) - log.Fatal().Err(errors.New("not all parameters are valid.")) - return - } - - ctx := context.Background() - key := "alert:" + bodyJSON.Name - rdb.Set(ctx, bodyJSON.Name, bodyJSON.Expr, 0) - rdb.SAdd(ctx, "alertkeys", key) - json.NewEncoder(w).Encode(map[string]interface{}{ - "isSuccessful": true, - "error": ""}) -} - -func handleAlertDelete(w http.ResponseWriter, r *http.Request) { - var Id string - w.Header().Add("Content-Type", "application/json") - params := r.URL.Query() - for key, value := range params { - switch key { - case "key": - Id = value[0] - default: - log.Error().Err(errors.New("bad parameters for the crypto endpoint.")) - } - } - - if Id == "" { - json.NewEncoder(w).Encode(map[string]interface{}{ - "isSuccessful": false, - "error": "Id parameter is not valid."}) - log.Fatal().Err(errors.New("not all parameters are valid.")) - return - } - - ctx := context.Background() - - rdb.Del(ctx, Id) - setKey := "alert:" + Id - rdb.SRem(ctx, "alertkeys", setKey) - log.Printf(setKey) - - json.NewEncoder(w).Encode(struct { - IsSuccessful bool `json:"isSuccessful"` - Err string `json:"err"` - }{IsSuccessful: true, Err: ""}) -} - -func handleAlertGet(w http.ResponseWriter, r *http.Request) { - var Id string - w.Header().Add("Content-Type", "application/json") - params := r.URL.Query() - for key, value := range params { - switch key { - case "key": - Id = value[0] - default: - log.Error().Err(errors.New("bad parameters for the crypto endpoint.")) - } - } - - if Id == "" { - json.NewEncoder(w).Encode(map[string]interface{}{ - "isSuccessful": false, - "error": "Id parameter is not valid."}) - log.Fatal().Err(errors.New("not all parameters are valid.")) - return - } - - ctx := context.Background() - - redisResult := rdb.Get(ctx, Id) - redisResultString, err := redisResult.Result() - if err != nil { - log.Err(err) - } - - var ErrorString string - if err == nil { - ErrorString = "" - } else { - ErrorString = err.Error() - } - - w.Header().Add("Content-Type", "application/json") - - json.NewEncoder(w).Encode(struct { - IsSuccessful bool `json:"isSuccessful"` - Error string `json:"error"` - Key string `json:"key"` - Expr string `json:"expr"` - }{IsSuccessful: true, Error: ErrorString, Key: Id, Expr: redisResultString}) -} - -func alertHandler(w http.ResponseWriter, r *http.Request) { - if r.Method == "POST" || r.Method == "PUT" || r.Method == "PATCH" { - handleAlertPost(w, r) - } else if r.Method == "DELETE" { - handleAlertDelete(w, r) - } else if r.Method == "GET" { - handleAlertGet(w, r) - } else { - http.Error(w, "Method is not supported.", http.StatusNotFound) - } -} - -func exHandler(w http.ResponseWriter, r *http.Request) { - w.Header().Add("Content-Type", "application/json") - if r.Method != "GET" { - http.Error(w, "Method is not supported.", http.StatusNotFound) - } - - apiKey := os.Getenv(CHANGELLY_API_KEY_ENV_VAR) - apiSecret := os.Getenv(CHANGELLY_API_SECRET_ENV_VAR) - - body := struct { - Jsonrpc string `json:"jsonrpc"` - Id string `json:"id"` - Method string `json:"method"` - Params []string `json:"params"` - }{ - Jsonrpc: "2.0", - Id: "test", - Method: "getCurrencies", - Params: nil} - - bodyJSON, err := json.Marshal(body) - if err != nil { - log.Error().Err(err) - } - - secretBytes := []byte(apiSecret[1 : len(apiSecret)-1]) - mac := hmac.New(sha512.New, secretBytes) - mac.Write(bodyJSON) - - client := &http.Client{} - req, err := http.NewRequest("POST", changellyURL, bytes.NewReader(bodyJSON)) - if err != nil { - log.Error().Err(err) - } - - macDigest := hex.EncodeToString(mac.Sum(nil)) - req.Header.Add("Content-Type", "application/json") - req.Header.Add("api-key", apiKey[1:len(apiKey)-1]) - req.Header.Add("sign", macDigest) - - resp, err := client.Do(req) - if err != nil { - log.Error().Err(err) - } - defer resp.Body.Close() - - responseBody, err := ioutil.ReadAll(resp.Body) - log.Printf(string(responseBody)) - - responseUnmarshalled := struct { - Jsonrpc string `json:"jsonrpc"` - Id string `json:"id"` - Result []string `json:"result"` - }{} - - err = json.Unmarshal(responseBody, &responseUnmarshalled) - if err != nil { - log.Error().Err(err) - } - - json.NewEncoder(w).Encode(responseUnmarshalled) -} - -func healthHandler(w http.ResponseWriter, r *http.Request) { - var RedisError string - var HivedError string - IsHivedOk := true - var IsRedisOk bool - - w.Header().Add("Content-Type", "application/json") - if r.Method != "GET" { - http.Error(w, "Method is not supported.", http.StatusNotFound) - } - - pingCtx := context.Background() - pingResponse := rdb.Ping(pingCtx) - pingResponseResult, err := pingResponse.Result() - if err != nil { - log.Err(err) - IsRedisOk = false - RedisError = err.Error() - } else { - if pingResponseResult == "PONG" { - IsRedisOk = true - RedisError = "" - } else { - IsRedisOk = false - RedisError = "redis did not respond PONG to ping" - } - } - - w.WriteHeader(http.StatusOK) - - json.NewEncoder(w).Encode(struct { - IsHivedOk bool `json:"isHivedOk"` - HivedError string `json:"hivedError"` - IsRedisOk bool `json:"isRedisOk"` - RedisError string `json:"redisError"` - }{IsHivedOk: IsHivedOk, HivedError: HivedError, IsRedisOk: IsRedisOk, RedisError: RedisError}) -} - -func robotsHandler(w http.ResponseWriter, r *http.Request) { - w.Header().Add("Content-Type", "text/plain") - json.NewEncoder(w).Encode(struct { - UserAgents string `json:"User-Agents"` - Disallow string `json:"Disallow"` - }{"*", "/"}) -} - -func startServer(gracefulWait time.Duration) { - r := mux.NewRouter() - cfg := &tls.Config{ - MinVersion: tls.VersionTLS13, - // CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256}, - // PreferServerCipherSuites: true, - // CipherSuites: []uint16{ - // tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, - // tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, - // tls.TLS_RSA_WITH_AES_256_GCM_SHA384, - // tls.TLS_RSA_WITH_AES_256_CBC_SHA, - // }, - } - srv := &http.Server{ - Addr: "0.0.0.0:" + *flagPort, - WriteTimeout: time.Second * 15, - ReadTimeout: time.Second * 15, - Handler: r, - TLSConfig: cfg, - } - r.HandleFunc("/crypto/health", healthHandler) - r.HandleFunc("/crypto/price", priceHandler) - r.HandleFunc("/crypto/pair", pairHandler) - r.HandleFunc("/crypto/alert", alertHandler) - r.HandleFunc("/crypto/ex", exHandler) - r.HandleFunc("/crypto/robots.txt", robotsHandler) - - go func() { - var certPath, keyPath string - if os.Getenv(SERVER_DEPLOYMENT_TYPE) == "deployment" { - certPath = "/certs/fullchain1.pem" - keyPath = "/certs/privkey1.pem" - } else { - certPath = "/certs/server.cert" - keyPath = "/certs/server.key" - } - if err := srv.ListenAndServeTLS(certPath, keyPath); err != nil { - log.Fatal().Err(err) - } - }() - - c := make(chan os.Signal, 1) - - signal.Notify(c, os.Interrupt) - <-c - ctx, cancel := context.WithTimeout(context.Background(), gracefulWait) - defer cancel() - srv.Shutdown(ctx) - log.Info().Msg("gracefully shut down the server") -} - -func setupLogging() { - zerolog.TimeFieldFormat = zerolog.TimeFormatUnix -} - -func main() { - var gracefulWait time.Duration - flag.DurationVar(&gracefulWait, "gracefulwait", time.Second*15, "the duration to wait during the graceful shutdown") - flag.Parse() - - rdb = redis.NewClient(&redis.Options{ - Addr: *redisAddress, - Password: *redisPassword, - DB: int(*redisDB), - }) - defer rdb.Close() - - setupLogging() - // go runTgBot() - go alertManager() - startServer(gracefulWait) -} diff --git a/hived/Dockerfile b/hived/Dockerfile new file mode 100644 index 0000000..0a9e3e2 --- /dev/null +++ b/hived/Dockerfile @@ -0,0 +1,18 @@ +FROM alpine:3.13 as builder +RUN apk update && apk upgrade +RUN apk add go git +COPY go.* /hived/ +RUN cd /hived && go mod download +COPY *.go /hived/ +RUN cd /hived && go build + +FROM node:lts-alpine3.13 AS certbuilder +RUN apk add openssl +WORKDIR /certs +RUN openssl req -nodes -new -x509 -subj="/C=US/ST=Denial/L=springfield/O=Dis/CN=localhost" -keyout server.key -out server.cert + +FROM gcr.io/distroless/static-debian10 +COPY --from=certbuilder /cert/ /cert/ +COPY --from=builder /hived/hived /hived/ +COPY ./docker-entrypoint.sh /hived/ +ENTRYPOINT ["/hived/docker-entrypoint.sh"] diff --git a/hived/docker-entrypoint.sh b/hived/docker-entrypoint.sh new file mode 100755 index 0000000..932c9c9 --- /dev/null +++ b/hived/docker-entrypoint.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env sh +set -ex + +export $(cat /run/secrets/tg_bot_token) +export $(cat /run/secrets/ch_api_key) +export $(cat /run/secrets/ch_api_secret) + +"/hived/hived" "$@" diff --git a/hived/go.mod b/hived/go.mod new file mode 100644 index 0000000..9df31fa --- /dev/null +++ b/hived/go.mod @@ -0,0 +1,12 @@ +module github.com/terminaldweller/hived + +go 1.17 + +require ( + github.com/Knetic/govaluate v3.0.0+incompatible + github.com/go-redis/redis/v8 v8.6.0 + github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible + github.com/gorilla/mux v1.8.0 + github.com/rs/zerolog v1.20.0 + github.com/technoweenie/multipartstreamer v1.0.1 // indirect +) diff --git a/hived/go.sum b/hived/go.sum new file mode 100644 index 0000000..07ad2bc --- /dev/null +++ b/hived/go.sum @@ -0,0 +1,115 @@ +github.com/Knetic/govaluate v3.0.0+incompatible h1:7o6+MAPhYTCF0+fdvoz1xDedhRb4f6s9Tn1Tt7/WTEg= +github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= +github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= +github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/go-redis/redis/v8 v8.6.0 h1:swqbqOrxaPztsj2Hf1p94M3YAgl7hYEpcw21z299hh8= +github.com/go-redis/redis/v8 v8.6.0/go.mod h1:DQ9q4Rk2HtwkrwVrdgmphoOQDMfpvcd/nHEwRsicg8s= +github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible h1:2cauKuaELYAEARXRkq2LrJ0yDDv1rW7+wrTEdVL3uaU= +github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible/go.mod h1:qf9acutJ8cwBUhm1bqgz6Bei9/C/c93FPDljKWwsOgM= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.4 h1:L8R9j+yAqZuZjsqh/z+F1NCffTKKLShY6zXTItVIZ8M= +github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= +github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78= +github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= +github.com/onsi/ginkgo v1.15.0 h1:1V1NfVQR87RtWAgp1lv9JZJ5Jap+XFGKPi00andXGi4= +github.com/onsi/ginkgo v1.15.0/go.mod h1:hF8qUzuuC8DJGygJH3726JnCZX4MYbRB8yFfISqnKUg= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/onsi/gomega v1.10.5 h1:7n6FEkpFmfCoo2t+YYqXH0evK+a9ICQz0xcAy9dYcaQ= +github.com/onsi/gomega v1.10.5/go.mod h1:gza4q3jKQJijlu05nKWRCW/GavJumGt8aNRxWg7mt48= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ= +github.com/rs/zerolog v1.20.0 h1:38k9hgtUBdxFwE34yS8rTHmHBa4eN16E4DJlv177LNs= +github.com/rs/zerolog v1.20.0/go.mod h1:IzD0RJ65iWH0w97OQQebJEvTZYvsCUm9WVLWBQrJRjo= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/technoweenie/multipartstreamer v1.0.1 h1:XRztA5MXiR1TIRHxH2uNxXxaIkKQDeX7m2XsSOlQEnM= +github.com/technoweenie/multipartstreamer v1.0.1/go.mod h1:jNVxdtShOxzAsukZwTSw6MDx5eUJoiEBsSvzDU9uzog= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +go.opentelemetry.io/otel v0.17.0 h1:6MKOu8WY4hmfpQ4oQn34u6rYhnf2sWf1LXYO/UFm71U= +go.opentelemetry.io/otel v0.17.0/go.mod h1:Oqtdxmf7UtEvL037ohlgnaYa1h7GtMh0NcSd9eqkC9s= +go.opentelemetry.io/otel/metric v0.17.0 h1:t+5EioN8YFXQ2EH+1j6FHCKMUj+57zIDSnSGr/mWuug= +go.opentelemetry.io/otel/metric v0.17.0/go.mod h1:hUz9lH1rNXyEwWAhIWCMFWKhYtpASgSnObJFnU26dJ0= +go.opentelemetry.io/otel/oteltest v0.17.0 h1:TyAihUowTDLqb4+m5ePAsR71xPJaTBJl4KDArIdi9k4= +go.opentelemetry.io/otel/oteltest v0.17.0/go.mod h1:JT/LGFxPwpN+nlsTiinSYjdIx3hZIGqHCpChcIZmdoE= +go.opentelemetry.io/otel/trace v0.17.0 h1:SBOj64/GAOyWzs5F680yW1ITIfJkm6cJWL2YAvuL9xY= +go.opentelemetry.io/otel/trace v0.17.0/go.mod h1:bIujpqg6ZL6xUTubIUgziI1jSaUPthmabA/ygf/6Cfg= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb h1:eBmm0M9fYhWpKZLjQUUKka/LtIxf46G4fxeEz5KJr9U= +golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210112080510-489259a85091 h1:DMyOG0U+gKfu8JZzg2UQe9MeaC1X+xQWlAKcRnjxjCw= +golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190828213141-aed303cbaa74/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/hived/hived.go b/hived/hived.go new file mode 100644 index 0000000..5345e70 --- /dev/null +++ b/hived/hived.go @@ -0,0 +1,675 @@ +package main + +import ( + "bytes" + "context" + "crypto/hmac" + "crypto/sha512" + "crypto/tls" + "encoding/hex" + "encoding/json" + "errors" + "flag" + "fmt" + "io/ioutil" + "net/http" + "net/url" + "os" + "os/signal" + "strconv" + "sync" + "time" + + "github.com/Knetic/govaluate" + "github.com/go-redis/redis/v8" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api" + "github.com/gorilla/mux" + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" +) + +var ( + flagPort = flag.String("port", "8008", "determined the port the sercice runs on") + alertsCheckInterval = flag.Int64("alertinterval", 600., "in seconds, the amount of time between alert checks") + redisAddress = flag.String("redisaddress", "redis:6379", "determines the address of the redis instance") + redisPassword = flag.String("redispassword", "", "determines the password of the redis db") + redisDB = flag.Int64("redisdb", 0, "determines the db number") + botChannelID = flag.Int64("botchannelid", 146328407, "determines the channel id the telgram bot should send messages to") + rdb *redis.Client +) + +const ( + cryptocomparePriceURL = "https://min-api.cryptocompare.com/data/price?" + changellyURL = "https://api.changelly.com" + TELEGRAM_BOT_TOKEN_ENV_VAR = "TELEGRAM_BOT_TOKEN" + CHANGELLY_API_KEY_ENV_VAR = "CHANGELLY_API_KEY" + CHANGELLY_API_SECRET_ENV_VAR = "CHANGELLY_API_SECRET" + SERVER_DEPLOYMENT_TYPE = "SERVER_DEPLOYMENT_TYPE" +) + +func runTgBot() { + // bot := getTgBot() + token := os.Getenv(TELEGRAM_BOT_TOKEN_ENV_VAR) + bot, err := tgbotapi.NewBotAPI(token[1 : len(token)-1]) + if err != nil { + log.Error().Err(err) + } + log.Debug().Msg("authorized on account bot_bloodstalker") + + update := tgbotapi.NewUpdate(0) + update.Timeout = 60 + + updates, err := bot.GetUpdatesChan(update) + if err != nil { + log.Error().Err(err) + } + + for update := range updates { + if update.Message == nil { + continue + } + + log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text) + + msg := tgbotapi.NewMessage(update.Message.Chat.ID, update.Message.Text) + msg.ReplyToMessageID = update.Message.MessageID + + bot.Send(msg) + } +} + +type priceChanStruct struct { + name string + price float64 +} + +type errorChanStruct struct { + hasError bool + err error +} + +func sendGetToCryptoCompare( + name, unit string, + wg *sync.WaitGroup, + priceChan chan<- priceChanStruct, + errChan chan<- errorChanStruct) { + defer wg.Done() + + params := "fsym=" + url.QueryEscape(name) + "&" + + "tsyms=" + url.QueryEscape(unit) + path := cryptocomparePriceURL + params + resp, err := http.Get(path) + if err != nil { + priceChan <- priceChanStruct{name: name, price: 0.} + errChan <- errorChanStruct{hasError: true, err: err} + log.Error().Err(err) + } + defer resp.Body.Close() + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + priceChan <- priceChanStruct{name: name, price: 0.} + errChan <- errorChanStruct{hasError: true, err: err} + log.Error().Err(err) + } + + jsonBody := make(map[string]float64) + err = json.Unmarshal(body, &jsonBody) + if err != nil { + priceChan <- priceChanStruct{name: name, price: 0.} + errChan <- errorChanStruct{hasError: true, err: err} + log.Error().Err(err) + } + + log.Info().Msg(string(body)) + + priceChan <- priceChanStruct{name: name, price: jsonBody[unit]} + errChan <- errorChanStruct{hasError: false, err: nil} +} + +func priceHandler(w http.ResponseWriter, r *http.Request) { + w.Header().Add("Content-Type", "application/json") + if r.Method != "GET" { + http.Error(w, "Method is not supported.", http.StatusNotFound) + } + + var name string + var unit string + params := r.URL.Query() + for key, value := range params { + switch key { + case "name": + name = value[0] + case "unit": + unit = value[0] + default: + log.Error().Err(errors.New("bad parameters for the crypto endpoint.")) + } + } + + if name == "" || unit == "" { + json.NewEncoder(w).Encode(map[string]interface{}{ + "err": "query parameters must include name and unit", + "isSuccessful": false}) + log.Error().Err(errors.New("query parameters must include name and unit.")) + return + } + + var wg sync.WaitGroup + priceChan := make(chan priceChanStruct, 1) + errChan := make(chan errorChanStruct, 1) + defer close(errChan) + defer close(priceChan) + wg.Add(1) + go sendGetToCryptoCompare(name, unit, &wg, priceChan, errChan) + wg.Wait() + + select { + case err := <-errChan: + if err.hasError != false { + log.Error().Err(err.err) + } + default: + log.Error().Err(errors.New("this shouldn't have happened'")) + } + + var price priceChanStruct + select { + case priceCh := <-priceChan: + price = priceCh + default: + log.Fatal().Err(errors.New("this shouldnt have happened")) + } + + json.NewEncoder(w).Encode(map[string]interface{}{ + "name": price.name, + "price": price.price, + "unit": unit, + "err": "", + "isSuccessful": true}) +} + +func pairHandler(w http.ResponseWriter, r *http.Request) { + var err error + w.Header().Add("Content-Type", "application/json") + if r.Method != "GET" { + http.Error(w, "Method is not supported.", http.StatusNotFound) + } + + var one string + var two string + var multiplier float64 + params := r.URL.Query() + for key, value := range params { + switch key { + case "one": + one = value[0] + case "two": + two = value[0] + case "multiplier": + multiplier, err = strconv.ParseFloat(value[0], 64) + if err != nil { + log.Fatal().Err(err) + } + default: + log.Fatal().Err(errors.New("unknown parameters for the pair endpoint.")) + } + } + + if one == "" || two == "" || multiplier == 0. { + log.Error().Err(errors.New("the query must include one()),two and multiplier")) + } + + var wg sync.WaitGroup + priceChan := make(chan priceChanStruct, 2) + errChan := make(chan errorChanStruct, 2) + defer close(priceChan) + defer close(errChan) + + wg.Add(2) + go sendGetToCryptoCompare(one, "USD", &wg, priceChan, errChan) + go sendGetToCryptoCompare(two, "USD", &wg, priceChan, errChan) + wg.Wait() + + for i := 0; i < 2; i++ { + select { + case err := <-errChan: + if err.hasError != false { + log.Error().Err(err.err) + } + default: + log.Fatal().Err(errors.New("this shouldnt have happened")) + } + } + + var priceOne float64 + var priceTwo float64 + for i := 0; i < 2; i++ { + select { + case price := <-priceChan: + if price.name == one { + priceOne = price.price + } + if price.name == two { + priceTwo = price.price + } + default: + log.Fatal().Err(errors.New("this shouldnt have happened")) + } + } + + ratio := priceOne * multiplier / priceTwo + log.Info().Msg(fmt.Sprintf("%v", ratio)) + json.NewEncoder(w).Encode(map[string]interface{}{"ratio": ratio}) +} + +type alertType struct { + Name string `json:"name"` + Expr string `json:"expr"` +} + +type alertsType struct { + Alerts []alertType `json:"alerts"` +} + +func getAlerts() (alertsType, error) { + var alerts alertsType + ctx := context.Background() + keys := rdb.SMembersMap(ctx, "alertkeys") + alerts.Alerts = make([]alertType, len(keys.Val())) + vals := keys.Val() + + i := 0 + for key := range vals { + alert := rdb.Get(ctx, key[6:]) + expr, _ := alert.Result() + alerts.Alerts[i].Name = key + alerts.Alerts[i].Expr = expr + i++ + } + + return alerts, nil +} + +func alertManager() { + for { + alerts, err := getAlerts() + if err != nil { + log.Error().Err(err) + return + } + log.Info().Msg(fmt.Sprintf("%v", alerts)) + + for i := range alerts.Alerts { + expression, err := govaluate.NewEvaluableExpression(alerts.Alerts[i].Expr) + if err != nil { + log.Error().Err(err) + continue + } + + vars := expression.Vars() + parameters := make(map[string]interface{}, len(vars)) + + var wg sync.WaitGroup + priceChan := make(chan priceChanStruct, len(vars)) + errChan := make(chan errorChanStruct, len(vars)) + defer close(priceChan) + defer close(errChan) + wg.Add(len(vars)) + + for i := range vars { + go sendGetToCryptoCompare(vars[i], "USD", &wg, priceChan, errChan) + } + wg.Wait() + + for i := 0; i < len(vars); i++ { + select { + case err := <-errChan: + if err.hasError != false { + log.Printf(err.err.Error()) + } + default: + log.Error().Err(errors.New("this shouldnt have happened")) + } + } + + for i := 0; i < len(vars); i++ { + select { + case price := <-priceChan: + parameters[price.name] = price.price + default: + log.Error().Err(errors.New("this shouldnt have happened")) + } + } + + log.Info().Msg(fmt.Sprintf("parameters: %v", parameters)) + result, err := expression.Evaluate(parameters) + if err != nil { + log.Error().Err(err) + } + + var resultBool bool + log.Info().Msg(fmt.Sprintf("result: %v", result)) + resultBool = result.(bool) + if resultBool == true { + // bot := getTgBot() + token := os.Getenv(TELEGRAM_BOT_TOKEN_ENV_VAR) + bot, err := tgbotapi.NewBotAPI(token[1 : len(token)-1]) + if err != nil { + log.Error().Err(err) + } + msgText := "notification " + alerts.Alerts[i].Expr + " has been triggered" + msg := tgbotapi.NewMessage(*botChannelID, msgText) + bot.Send(msg) + } + } + + time.Sleep(time.Second * time.Duration(*alertsCheckInterval)) + } +} + +type addAlertJSONType struct { + Name string `json:"name"` + Expr string `json:"expr"` +} + +func handleAlertPost(w http.ResponseWriter, r *http.Request) { + w.Header().Add("Content-Type", "application/json") + bodyBytes, err := ioutil.ReadAll(r.Body) + if err != nil { + log.Printf(err.Error()) + } + + var bodyJSON addAlertJSONType + json.Unmarshal(bodyBytes, &bodyJSON) + + if bodyJSON.Name == "" || bodyJSON.Expr == "" { + json.NewEncoder(w).Encode(map[string]interface{}{ + "isSuccessful": false, + "error": "not all parameters are valid."}) + log.Fatal().Err(errors.New("not all parameters are valid.")) + return + } + + ctx := context.Background() + key := "alert:" + bodyJSON.Name + rdb.Set(ctx, bodyJSON.Name, bodyJSON.Expr, 0) + rdb.SAdd(ctx, "alertkeys", key) + json.NewEncoder(w).Encode(map[string]interface{}{ + "isSuccessful": true, + "error": ""}) +} + +func handleAlertDelete(w http.ResponseWriter, r *http.Request) { + var Id string + w.Header().Add("Content-Type", "application/json") + params := r.URL.Query() + for key, value := range params { + switch key { + case "key": + Id = value[0] + default: + log.Error().Err(errors.New("bad parameters for the crypto endpoint.")) + } + } + + if Id == "" { + json.NewEncoder(w).Encode(map[string]interface{}{ + "isSuccessful": false, + "error": "Id parameter is not valid."}) + log.Fatal().Err(errors.New("not all parameters are valid.")) + return + } + + ctx := context.Background() + + rdb.Del(ctx, Id) + setKey := "alert:" + Id + rdb.SRem(ctx, "alertkeys", setKey) + log.Printf(setKey) + + json.NewEncoder(w).Encode(struct { + IsSuccessful bool `json:"isSuccessful"` + Err string `json:"err"` + }{IsSuccessful: true, Err: ""}) +} + +func handleAlertGet(w http.ResponseWriter, r *http.Request) { + var Id string + w.Header().Add("Content-Type", "application/json") + params := r.URL.Query() + for key, value := range params { + switch key { + case "key": + Id = value[0] + default: + log.Error().Err(errors.New("bad parameters for the crypto endpoint.")) + } + } + + if Id == "" { + json.NewEncoder(w).Encode(map[string]interface{}{ + "isSuccessful": false, + "error": "Id parameter is not valid."}) + log.Fatal().Err(errors.New("not all parameters are valid.")) + return + } + + ctx := context.Background() + + redisResult := rdb.Get(ctx, Id) + redisResultString, err := redisResult.Result() + if err != nil { + log.Err(err) + } + + var ErrorString string + if err == nil { + ErrorString = "" + } else { + ErrorString = err.Error() + } + + w.Header().Add("Content-Type", "application/json") + + json.NewEncoder(w).Encode(struct { + IsSuccessful bool `json:"isSuccessful"` + Error string `json:"error"` + Key string `json:"key"` + Expr string `json:"expr"` + }{IsSuccessful: true, Error: ErrorString, Key: Id, Expr: redisResultString}) +} + +func alertHandler(w http.ResponseWriter, r *http.Request) { + if r.Method == "POST" || r.Method == "PUT" || r.Method == "PATCH" { + handleAlertPost(w, r) + } else if r.Method == "DELETE" { + handleAlertDelete(w, r) + } else if r.Method == "GET" { + handleAlertGet(w, r) + } else { + http.Error(w, "Method is not supported.", http.StatusNotFound) + } +} + +func exHandler(w http.ResponseWriter, r *http.Request) { + w.Header().Add("Content-Type", "application/json") + if r.Method != "GET" { + http.Error(w, "Method is not supported.", http.StatusNotFound) + } + + apiKey := os.Getenv(CHANGELLY_API_KEY_ENV_VAR) + apiSecret := os.Getenv(CHANGELLY_API_SECRET_ENV_VAR) + + body := struct { + Jsonrpc string `json:"jsonrpc"` + Id string `json:"id"` + Method string `json:"method"` + Params []string `json:"params"` + }{ + Jsonrpc: "2.0", + Id: "test", + Method: "getCurrencies", + Params: nil} + + bodyJSON, err := json.Marshal(body) + if err != nil { + log.Error().Err(err) + } + + secretBytes := []byte(apiSecret[1 : len(apiSecret)-1]) + mac := hmac.New(sha512.New, secretBytes) + mac.Write(bodyJSON) + + client := &http.Client{} + req, err := http.NewRequest("POST", changellyURL, bytes.NewReader(bodyJSON)) + if err != nil { + log.Error().Err(err) + } + + macDigest := hex.EncodeToString(mac.Sum(nil)) + req.Header.Add("Content-Type", "application/json") + req.Header.Add("api-key", apiKey[1:len(apiKey)-1]) + req.Header.Add("sign", macDigest) + + resp, err := client.Do(req) + if err != nil { + log.Error().Err(err) + } + defer resp.Body.Close() + + responseBody, err := ioutil.ReadAll(resp.Body) + log.Printf(string(responseBody)) + + responseUnmarshalled := struct { + Jsonrpc string `json:"jsonrpc"` + Id string `json:"id"` + Result []string `json:"result"` + }{} + + err = json.Unmarshal(responseBody, &responseUnmarshalled) + if err != nil { + log.Error().Err(err) + } + + json.NewEncoder(w).Encode(responseUnmarshalled) +} + +func healthHandler(w http.ResponseWriter, r *http.Request) { + var RedisError string + var HivedError string + IsHivedOk := true + var IsRedisOk bool + + w.Header().Add("Content-Type", "application/json") + if r.Method != "GET" { + http.Error(w, "Method is not supported.", http.StatusNotFound) + } + + pingCtx := context.Background() + pingResponse := rdb.Ping(pingCtx) + pingResponseResult, err := pingResponse.Result() + if err != nil { + log.Err(err) + IsRedisOk = false + RedisError = err.Error() + } else { + if pingResponseResult == "PONG" { + IsRedisOk = true + RedisError = "" + } else { + IsRedisOk = false + RedisError = "redis did not respond PONG to ping" + } + } + + w.WriteHeader(http.StatusOK) + + json.NewEncoder(w).Encode(struct { + IsHivedOk bool `json:"isHivedOk"` + HivedError string `json:"hivedError"` + IsRedisOk bool `json:"isRedisOk"` + RedisError string `json:"redisError"` + }{IsHivedOk: IsHivedOk, HivedError: HivedError, IsRedisOk: IsRedisOk, RedisError: RedisError}) +} + +func robotsHandler(w http.ResponseWriter, r *http.Request) { + w.Header().Add("Content-Type", "text/plain") + json.NewEncoder(w).Encode(struct { + UserAgents string `json:"User-Agents"` + Disallow string `json:"Disallow"` + }{"*", "/"}) +} + +func startServer(gracefulWait time.Duration) { + r := mux.NewRouter() + cfg := &tls.Config{ + MinVersion: tls.VersionTLS13, + // CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256}, + // PreferServerCipherSuites: true, + // CipherSuites: []uint16{ + // tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, + // tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, + // tls.TLS_RSA_WITH_AES_256_GCM_SHA384, + // tls.TLS_RSA_WITH_AES_256_CBC_SHA, + // }, + } + srv := &http.Server{ + Addr: "0.0.0.0:" + *flagPort, + WriteTimeout: time.Second * 15, + ReadTimeout: time.Second * 15, + Handler: r, + TLSConfig: cfg, + } + r.HandleFunc("/crypto/health", healthHandler) + r.HandleFunc("/crypto/price", priceHandler) + r.HandleFunc("/crypto/pair", pairHandler) + r.HandleFunc("/crypto/alert", alertHandler) + r.HandleFunc("/crypto/ex", exHandler) + r.HandleFunc("/crypto/robots.txt", robotsHandler) + + go func() { + var certPath, keyPath string + if os.Getenv(SERVER_DEPLOYMENT_TYPE) == "deployment" { + certPath = "/certs/fullchain1.pem" + keyPath = "/certs/privkey1.pem" + } else { + certPath = "/certs/server.cert" + keyPath = "/certs/server.key" + } + if err := srv.ListenAndServeTLS(certPath, keyPath); err != nil { + log.Fatal().Err(err) + } + }() + + c := make(chan os.Signal, 1) + + signal.Notify(c, os.Interrupt) + <-c + ctx, cancel := context.WithTimeout(context.Background(), gracefulWait) + defer cancel() + srv.Shutdown(ctx) + log.Info().Msg("gracefully shut down the server") +} + +func setupLogging() { + zerolog.TimeFieldFormat = zerolog.TimeFormatUnix +} + +func main() { + var gracefulWait time.Duration + flag.DurationVar(&gracefulWait, "gracefulwait", time.Second*15, "the duration to wait during the graceful shutdown") + flag.Parse() + + rdb = redis.NewClient(&redis.Options{ + Addr: *redisAddress, + Password: *redisPassword, + DB: int(*redisDB), + }) + defer rdb.Close() + + setupLogging() + // go runTgBot() + go alertManager() + startServer(gracefulWait) +} diff --git a/run.sh b/run.sh deleted file mode 100755 index 4031990..0000000 --- a/run.sh +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/env sh -docker build -t hived ./ && docker-compose up diff --git a/runtravis.sh b/runtravis.sh deleted file mode 100755 index 10ee492..0000000 --- a/runtravis.sh +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/env sh - diff --git a/telebot/Dockerfile b/telebot/Dockerfile new file mode 100644 index 0000000..0a9e3e2 --- /dev/null +++ b/telebot/Dockerfile @@ -0,0 +1,18 @@ +FROM alpine:3.13 as builder +RUN apk update && apk upgrade +RUN apk add go git +COPY go.* /hived/ +RUN cd /hived && go mod download +COPY *.go /hived/ +RUN cd /hived && go build + +FROM node:lts-alpine3.13 AS certbuilder +RUN apk add openssl +WORKDIR /certs +RUN openssl req -nodes -new -x509 -subj="/C=US/ST=Denial/L=springfield/O=Dis/CN=localhost" -keyout server.key -out server.cert + +FROM gcr.io/distroless/static-debian10 +COPY --from=certbuilder /cert/ /cert/ +COPY --from=builder /hived/hived /hived/ +COPY ./docker-entrypoint.sh /hived/ +ENTRYPOINT ["/hived/docker-entrypoint.sh"] diff --git a/telebot/docker-entrypoint.sh b/telebot/docker-entrypoint.sh new file mode 100755 index 0000000..932c9c9 --- /dev/null +++ b/telebot/docker-entrypoint.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env sh +set -ex + +export $(cat /run/secrets/tg_bot_token) +export $(cat /run/secrets/ch_api_key) +export $(cat /run/secrets/ch_api_secret) + +"/hived/hived" "$@" diff --git a/telebot/go.mod b/telebot/go.mod new file mode 100644 index 0000000..71766e5 --- /dev/null +++ b/telebot/go.mod @@ -0,0 +1,10 @@ +module telebot + +go 1.15 + +require ( + github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible + github.com/gorilla/mux v1.8.0 + github.com/rs/zerolog v1.26.0 + github.com/technoweenie/multipartstreamer v1.0.1 // indirect +) diff --git a/telebot/go.sum b/telebot/go.sum new file mode 100644 index 0000000..ca57a1e --- /dev/null +++ b/telebot/go.sum @@ -0,0 +1,35 @@ +github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible h1:2cauKuaELYAEARXRkq2LrJ0yDDv1rW7+wrTEdVL3uaU= +github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible/go.mod h1:qf9acutJ8cwBUhm1bqgz6Bei9/C/c93FPDljKWwsOgM= +github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= +github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/rs/xid v1.3.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= +github.com/rs/zerolog v1.26.0 h1:ORM4ibhEZeTeQlCojCK2kPz1ogAY4bGs4tD+SaAdGaE= +github.com/rs/zerolog v1.26.0/go.mod h1:yBiM87lvSqX8h0Ww4sdzNSkVYZ8dL2xjZJG1lAuGZEo= +github.com/technoweenie/multipartstreamer v1.0.1 h1:XRztA5MXiR1TIRHxH2uNxXxaIkKQDeX7m2XsSOlQEnM= +github.com/technoweenie/multipartstreamer v1.0.1/go.mod h1:jNVxdtShOxzAsukZwTSw6MDx5eUJoiEBsSvzDU9uzog= +github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/telebot/main.go b/telebot/main.go new file mode 100644 index 0000000..f6a3bf7 --- /dev/null +++ b/telebot/main.go @@ -0,0 +1,92 @@ +package main + +import ( + "context" + "encoding/json" + "flag" + "net/http" + "os" + "os/signal" + "time" + + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api" + "github.com/gorilla/mux" + "github.com/rs/zerolog/log" +) + +var flagPort = flag.String("port", "8000", "determined the port the sercice runs on") + +// FIXME-the client should provide the channel ID +var botChannelID = flag.Int64("botchannelid", 146328407, "determines the channel id the telgram bot should send messages to") + +const TELEGRAM_BOT_TOKEN_ENV_VAR = "TELEGRAM_BOT_TOKEN" + +func getTGBot() *tgbotapi.BotAPI { + token := os.Getenv(TELEGRAM_BOT_TOKEN_ENV_VAR) + bot, err := tgbotapi.NewBotAPI(token[1 : len(token)-1]) + if err != nil { + log.Error().Err(err) + } + return bot +} + +func sendMessage(bot *tgbotapi.BotAPI, msgText string) error { + msg := tgbotapi.NewMessage(*botChannelID, msgText) + bot.Send(msg) + return nil +} + +func healthHandler(w http.ResponseWriter, r *http.Request) { + var telebotError string + IsTelebotOk := true + + w.Header().Add("Content-Type", "application/json") + if r.Method != "GET" { + http.Error(w, "Method is not supported.", http.StatusNotFound) + } + + w.WriteHeader(http.StatusOK) + + json.NewEncoder(w).Encode(struct { + IsHivedOk bool `json:"isTelebotOK"` + TelebotError string `json:"telebotError"` + }{IsHivedOk: IsTelebotOk, TelebotError: telebotError}) +} + +func msgHandler(w http.ResponseWriter, r *http.Request) { + +} + +func startServer(gracefulWait time.Duration) { + r := mux.NewRouter() + srv := &http.Server{ + Addr: "0.0.0.0:" + *flagPort, + WriteTimeout: time.Second * 15, + ReadTimeout: time.Second * 15, + Handler: r, + } + r.HandleFunc("/health", healthHandler) + r.HandleFunc("/msg", msgHandler) + + go func() { + if err := srv.ListenAndServe(); err != nil { + log.Fatal().Err(err) + } + }() + + c := make(chan os.Signal, 1) + + signal.Notify(c, os.Interrupt) + <-c + ctx, cancel := context.WithTimeout(context.Background(), gracefulWait) + defer cancel() + srv.Shutdown(ctx) + log.Info().Msg("gracefully shut down the server") +} + +func main() { + var gracefulWait time.Duration + flag.DurationVar(&gracefulWait, "gracefulwait", time.Second*15, "the duration to wait during the graceful shutdown") + flag.Parse() + startServer(gracefulWait) +} diff --git a/telebot/telebot b/telebot/telebot new file mode 100755 index 0000000..21b84aa Binary files /dev/null and b/telebot/telebot differ -- cgit v1.2.3