1
0
mirror of synced 2025-01-30 20:01:42 +03:00

Merge pull request #51 from gwinn/release

Handle 402 http status, add sentry tags
This commit is contained in:
Alex Lushpai 2018-10-24 17:29:08 +03:00 committed by GitHub
commit 7c1dc4534c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 78 additions and 27 deletions

2
go.mod
View File

@ -44,7 +44,7 @@ require (
github.com/op/go-logging v0.0.0-20160315200505-970db520ece7
github.com/pkg/errors v0.8.0
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/retailcrm/api-client-go v1.0.7
github.com/retailcrm/api-client-go v1.1.0
github.com/retailcrm/mg-transport-api-client-go v1.1.11
github.com/smartystreets/assertions v0.0.0-20180820201707-7c9eb446e3cf // indirect
github.com/smartystreets/goconvey v0.0.0-20180222194500-ef6db91d284a // indirect

4
go.sum
View File

@ -93,8 +93,8 @@ github.com/pkg/errors v0.8.0 h1:WdK/asTD0HN+q6hsWO3/vpuAkAr+tw6aNJNDFFf0+qw=
github.com/pkg/errors v0.8.0/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/retailcrm/api-client-go v1.0.7 h1:j4C2PvPUDP9nAuYWDvJPnYNpkj+LDBgn71kHvxJmSPg=
github.com/retailcrm/api-client-go v1.0.7/go.mod h1:QRoPE2SM6ST7i2g0yEdqm7Iw98y7cYuq3q14Ot+6N8c=
github.com/retailcrm/api-client-go v1.1.0 h1:APPO6ccJAeMV7Jz7BhrtDKSOm2r1j5Ft6fuEXNP2ij4=
github.com/retailcrm/api-client-go v1.1.0/go.mod h1:QRoPE2SM6ST7i2g0yEdqm7Iw98y7cYuq3q14Ot+6N8c=
github.com/retailcrm/mg-transport-api-client-go v1.1.11 h1:jAIOKqkjA2r0v/V6lTHYQsD8q0lFpfpqzAffHAJlhCQ=
github.com/retailcrm/mg-transport-api-client-go v1.1.11/go.mod h1:AWV6BueE28/6SCoyfKURTo4lF0oXYoOKmHTzehd5vAI=
github.com/smartystreets/assertions v0.0.0-20180820201707-7c9eb446e3cf h1:6V1qxN6Usn4jy8unvggSJz/NC790tefw8Zdy6OZS5co=

View File

@ -67,6 +67,30 @@ func ErrorCaptureHandler(client *raven.Client, errorsStacktrace bool) ErrorHandl
"endpoint": c.Request.RequestURI,
}
var (
ok bool
conn Connection
)
connection, ok := c.Get("connection")
if ok {
conn = connection.(Connection)
}
b, ok := c.Get("bot")
if ok {
tags["bot"] = b.(Bot).Token
conn = *getConnectionById(b.(Bot).ConnectionID)
}
if conn.APIURL != "" {
tags["crm"] = conn.APIURL
}
if conn.ClientID != "" {
tags["clientID"] = conn.ClientID
}
if recovery != nil {
stacktrace := raven.NewStacktrace(4, 3, nil)
recStr := fmt.Sprint(recovery)

View File

@ -187,6 +187,12 @@ func createHandler(c *gin.Context) {
return
}
if status == http.StatusPaymentRequired {
c.AbortWithStatusJSON(BadRequest("error_payment_mg"))
logger.Error(conn.APIURL, status, errr.ApiErr, data)
return
}
if status >= http.StatusBadRequest {
c.AbortWithStatusJSON(BadRequest("error_activity_mg"))
logger.Error(conn.APIURL, status, errr.ApiErr, data)
@ -406,17 +412,7 @@ func updateBots(conn *Connection, hashSettings string) {
}
func telegramWebhookHandler(c *gin.Context) {
token := c.Param("token")
b, err := getBotByToken(token)
if err != nil {
c.Error(err)
return
}
if b.ID == 0 {
c.AbortWithStatus(http.StatusOK)
return
}
b := c.MustGet("bot").(Bot)
conn := getConnectionById(b.ConnectionID)
if !conn.Active {
@ -559,17 +555,7 @@ func telegramWebhookHandler(c *gin.Context) {
}
func mgWebhookHandler(c *gin.Context) {
clientID := c.GetHeader("Clientid")
if clientID == "" {
c.AbortWithStatus(http.StatusBadRequest)
return
}
conn := getConnection(clientID)
if !conn.Active {
c.AbortWithStatus(http.StatusBadRequest)
return
}
conn := c.MustGet("connection").(Connection)
var msg v1.WebhookRequest
if err := c.ShouldBindJSON(&msg); err != nil {

View File

@ -1,6 +1,7 @@
package main
import (
"net/http"
"os"
"os/signal"
"syscall"
@ -92,8 +93,8 @@ func setup() *gin.Engine {
r.POST("/delete-bot/", checkBotForRequest(), deleteBotHandler)
r.POST("/set-lang/", checkBotForRequest(), setLangBotHandler)
r.POST("/actions/activity", activityHandler)
r.POST("/telegram/:token", telegramWebhookHandler)
r.POST("/webhook/", mgWebhookHandler)
r.POST("/telegram/:token", checkBotForWebhook(), telegramWebhookHandler)
r.POST("/webhook/", checkConnectionForWebhook(), mgWebhookHandler)
return r
}
@ -147,3 +148,40 @@ func checkConnectionForRequest() gin.HandlerFunc {
c.Set("connection", conn)
}
}
func checkConnectionForWebhook() gin.HandlerFunc {
return func(c *gin.Context) {
clientID := c.GetHeader("Clientid")
if clientID == "" {
c.AbortWithStatus(http.StatusBadRequest)
return
}
conn := getConnection(clientID)
if !conn.Active {
c.AbortWithStatus(http.StatusBadRequest)
return
}
c.Set("connection", *conn)
}
}
func checkBotForWebhook() gin.HandlerFunc {
return func(c *gin.Context) {
token := c.Param("token")
b, err := getBotByToken(token)
if err != nil {
c.Error(err)
return
}
if b.ID == 0 {
c.AbortWithStatus(http.StatusOK)
return
}
c.Set("bot", *b)
}
}

View File

@ -27,6 +27,7 @@ incorrect_token: Create the correct token
error_creating_webhook: Error when creating a webhook
error_adding_bot: Error when adding a bot
error_save: Error while saving, contact technical support
error_payment_mg: Your account has insufficient funds to activate integration module
missing_credentials: "Required methods: {{.Credentials}}"
error_activity_mg: Check if the integration with retailCRM Chat is enabled in retailCRM settings
info_bot: "If you have a problem with connecting a bot, please, refer to the <a target='_blank' href='//www.retailcrm.pro/docs/Users/Telegram'>documentation</a>"

View File

@ -28,6 +28,7 @@ incorrect_token: Crear el token correcto
error_creating_webhook: Error al crear el webhook
error_adding_bot: Error al añadir el bot
error_save: Error al guardar, contacte con el soporte técnico
error_payment_mg: Su cuenta no tiene fondos suficientes para activar el módulo de integración.
missing_credentials: "Métodos requeridos: {{.Credenciales}}"
error_activity_mg: Revisar si la integración con retailCRM Chat está habilitada en Ajustes de retailCRM
info_bot: "Si tiene dificultades para conectar el bot, por favor, consulte la <a target='_blank' href='//www.retailcrm.pro/docs/Users/Telegram'>documentación</a>"

View File

@ -27,6 +27,7 @@ incorrect_token: Установите корректный токен
error_creating_webhook: Ошибка при создании webhook
error_adding_bot: Ошибка при добавлении бота
error_save: Ошибка при сохранении, обратитесь в службу технической поддержки
error_payment_mg: На Вашем счете недостаточно средств для активации данного модуля
missing_credentials: "Необходимые методы: {{.Credentials}}"
error_activity_mg: Проверьте активность интеграции с retailCRM Chat в настройках retailCRM
info_bot: "Если у вас возникли трудности при подключении бота, изучите, пожалуйста, <a target='_blank' href='//www.retailcrm.ru/docs/Users/Telegram'>документацию</a>"