diff --git a/go.mod b/go.mod index e6d2520..71cd701 100644 --- a/go.mod +++ b/go.mod @@ -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 diff --git a/go.sum b/go.sum index c459b47..64e8d2b 100644 --- a/go.sum +++ b/go.sum @@ -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= diff --git a/src/error_handler.go b/src/error_handler.go index 4f0b05e..56c0368 100644 --- a/src/error_handler.go +++ b/src/error_handler.go @@ -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) diff --git a/src/routing.go b/src/routing.go index 9024953..fcfc9e6 100644 --- a/src/routing.go +++ b/src/routing.go @@ -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 { diff --git a/src/run.go b/src/run.go index 74fd3db..a7b3c50 100644 --- a/src/run.go +++ b/src/run.go @@ -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) + } +} diff --git a/translate/translate.en.yml b/translate/translate.en.yml index e40bdb4..5deae0b 100644 --- a/translate/translate.en.yml +++ b/translate/translate.en.yml @@ -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 documentation" diff --git a/translate/translate.es.yml b/translate/translate.es.yml index e205ca0..13bcc87 100644 --- a/translate/translate.es.yml +++ b/translate/translate.es.yml @@ -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 documentación" diff --git a/translate/translate.ru.yml b/translate/translate.ru.yml index 5b14854..52d7a3e 100644 --- a/translate/translate.ru.yml +++ b/translate/translate.ru.yml @@ -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: "Если у вас возникли трудности при подключении бота, изучите, пожалуйста, документацию"