diff --git a/models.go b/models.go index 11f0ade..7388fcb 100644 --- a/models.go +++ b/models.go @@ -27,12 +27,5 @@ type Bot struct { Active bool `json:"active,omitempty"` } -// Mapping model -type Mapping struct { - ID int `gorm:"primary_key"` - SiteCode string `gorm:"site_code" json:"site_code,omitempty"` - BotID string `gorm:"bot_id" json:"bot_id,omitempty"` -} - //Bots list type Bots []Bot diff --git a/repository.go b/repository.go index 36f7dbb..5ac999c 100644 --- a/repository.go +++ b/repository.go @@ -1,28 +1,5 @@ package main -func createMapping(s []Mapping) error { - tx := orm.DB.Begin() - if tx.Error != nil { - return tx.Error - } - - defer func() { - if r := recover(); r != nil { - logger.Warning(r) - tx.Rollback() - } - }() - - for _, val := range s { - if err := tx.Create(&val).Error; err != nil { - tx.Rollback() - return err - } - } - - return tx.Commit().Error -} - func getConnection(uid string) (*Connection, error) { var connection Connection orm.DB.First(&connection, "client_id = ?", uid) diff --git a/routing.go b/routing.go index b189a5a..455a485 100644 --- a/routing.go +++ b/routing.go @@ -18,7 +18,7 @@ import ( ) var ( - templates = template.Must(template.ParseFiles("templates/header.html", "templates/form.html", "templates/home.html")) + templates = template.Must(template.ParseFiles("templates/layout.html", "templates/form.html", "templates/home.html")) validPath = regexp.MustCompile("^/(save|settings)/([a-zA-Z0-9]+)$") localizer *i18n.Localizer bundle = &i18n.Bundle{DefaultLanguage: language.English} @@ -91,6 +91,7 @@ func connectHandler(w http.ResponseWriter, r *http.Request) { &p, map[string]interface{}{ "ButConnect": localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "but_connect"}), + "ApiKey": localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "api_key"}), }, } renderTemplate(w, "home", &res) @@ -125,7 +126,7 @@ func addBotHandler(w http.ResponseWriter, r *http.Request) { bot, err := GetBotInfo(b.Token) if err != nil { logger.Error(b.Token, err.Error()) - http.Error(w, "set correct bot token", http.StatusInternalServerError) + http.Error(w, localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "incorrect_token"}), http.StatusInternalServerError) return } @@ -244,30 +245,6 @@ func activityBotHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } -func mappingHandler(w http.ResponseWriter, r *http.Request) { - body, err := ioutil.ReadAll(r.Body) - if err != nil { - raven.CaptureErrorAndWait(err, nil) - return - } - - var rec []Mapping - - err = json.Unmarshal(body, &rec) - if err != nil { - raven.CaptureErrorAndWait(err, nil) - return - } - - err = createMapping(rec) - if err != nil { - raven.CaptureErrorAndWait(err, nil) - return - } - - w.WriteHeader(http.StatusOK) -} - func settingsHandler(w http.ResponseWriter, r *http.Request, uid string) { setLocale(r.Header.Get("Accept-Language")) @@ -299,14 +276,12 @@ func settingsHandler(w http.ResponseWriter, r *http.Request, uid string) { sites.Sites, map[string]interface{}{ "ButConnect": localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "but_connect"}), + "ApiKey": localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "api_key"}), "TabSettings": localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "tab_settings"}), "TabBots": localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "tab_bots"}), - "TabMapping": localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "tab_mapping"}), "TableName": localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "table_name"}), "TableToken": localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "table_token"}), "TableActivity": localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "table_activity"}), - "MapSites": localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "map_sites"}), - "MapOption": localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "map_option"}), }, } @@ -348,13 +323,24 @@ func saveHandler(w http.ResponseWriter, r *http.Request) { func createHandler(w http.ResponseWriter, r *http.Request) { setLocale(r.Header.Get("Accept-Language")) - c := Connection{ - ClientID: GenerateToken(), - APIURL: string([]byte(r.FormValue("api_url"))), - APIKEY: string([]byte(r.FormValue("api_key"))), + + body, err := ioutil.ReadAll(r.Body) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return } - err := validate(c) + var c Connection + + err = json.Unmarshal(body, &c) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + c.ClientID = GenerateToken() + + err = validate(c) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) logger.Error(c.APIURL, err.Error()) @@ -388,9 +374,12 @@ func createHandler(w http.ResponseWriter, r *http.Request) { Active: true, Name: "MG Telegram", ClientID: c.ClientID, - BaseURL: config.HTTPServer.Host, + BaseURL: fmt.Sprintf( + "https://%s", + config.HTTPServer.Host, + ), AccountURL: fmt.Sprintf( - "%s/settings/%s", + "https://%s/settings/%s", config.HTTPServer.Host, c.ClientID, ), @@ -398,7 +387,7 @@ func createHandler(w http.ResponseWriter, r *http.Request) { Integrations: &v5.Integrations{ MgTransport: &v5.MgTransport{ WebhookUrl: fmt.Sprintf( - "%s/webhook", + "https://%s/webhook", config.HTTPServer.Host, ), }, diff --git a/telegram.go b/telegram.go index de11dd4..2a79e55 100644 --- a/telegram.go +++ b/telegram.go @@ -9,7 +9,6 @@ import ( func setTransportRoutes() { http.HandleFunc("/add-bot/", addBotHandler) http.HandleFunc("/activity-bot/", activityBotHandler) - http.HandleFunc("/map-bot/", mappingHandler) } // GetBotInfo function diff --git a/templates/form.html b/templates/form.html index e514fd2..d9a8e3d 100644 --- a/templates/form.html +++ b/templates/form.html @@ -1,219 +1,78 @@ {{template "header"}} -
-
- -
-

-
-
-
-
- -
-
- -
-
-
-
- -
-
-
-
- -
-
-
-
-
-
-
-
- -
-
- -
-
- -
-
-
- {{if .Bots}} - - - - - - - - - - {{range .Bots}} - - - - - - {{end}} - -
{{.Locale.TableName}}{{.Locale.TableToken}}{{.Locale.TableActivity}}
{{.Name}}{{.Token}} - -
- {{end}} -
-
-
-
- {{ $sites := .Sites }} - {{ $bots := .Bots }} - {{ $locale := .Locale }} - {{if and $sites $bots}} - - - - - - - - - {{range $site := $sites}} - - - - - {{end}} - -
{{.Locale.MapSites}}{{.Locale.TabBots}}
{{$site.Name}} - -
-
-
-
- -
-
- {{end}} -
-
-
- - +
+
+
- - - +
+
+
+
+
+
+ +
+
+ +
+
+
+
+ +
+
+
+
+ +
+
+
+
+
+
+
+
+ +
+
+ +
+
+ +
+
+
+ + + + + + + + + + {{range .Bots}} + + + + + + {{end}} + +
{{.Locale.TableName}}{{.Locale.TableToken}}{{.Locale.TableActivity}}
{{.Name}}{{.Token}} + +
+
+
+
+{{template "footer"}} diff --git a/templates/header.html b/templates/header.html deleted file mode 100644 index daade3f..0000000 --- a/templates/header.html +++ /dev/null @@ -1,13 +0,0 @@ -{{ define "header" }} - - - - - - - - - - - -{{ end }} \ No newline at end of file diff --git a/templates/home.html b/templates/home.html index d25d291..6f3d906 100644 --- a/templates/home.html +++ b/templates/home.html @@ -1,57 +1,28 @@ {{template "header"}} -
-
-
-

-
-
- -
-
-
-
- -
-
-
-
- -
-
-
-
+
+
+
- - - - +
+
+
+
+ +
+
+
+
+ +
+
+
+
+ +
+
+
+
+{{template "footer"}} diff --git a/templates/layout.html b/templates/layout.html new file mode 100644 index 0000000..61ceade --- /dev/null +++ b/templates/layout.html @@ -0,0 +1,25 @@ +{{ define "header" }} + + + + + + + + + + +
+
+ +
+{{ end }} + +{{ define "footer" }} +
+ + + + + +{{ end }} diff --git a/translate/translate.en.yml b/translate/translate.en.yml index 5b866cb..a4f9573 100644 --- a/translate/translate.en.yml +++ b/translate/translate.en.yml @@ -1,12 +1,10 @@ but_connect: Save tab_settings: Connection settings tab_bots: Bots -tab_mapping: Mapping table_name: Bot name table_token: Bot token table_activity: Activity -map_sites: Sites -map_option: Choose your option +api_key: API Key no_bot_token: Enter the bot token incorrect_data: Incorrect data @@ -21,3 +19,4 @@ error_creating_connection: Error while creating connection connection_already_created: Connection already created missing_url_key: Missing crm url or apiKey incorrect_url: Enter the correct CRM url +incorrect_token: Set correct bot token diff --git a/translate/translate.ru.yml b/translate/translate.ru.yml index 4088591..7cb57d6 100644 --- a/translate/translate.ru.yml +++ b/translate/translate.ru.yml @@ -1,12 +1,11 @@ but_connect: Сохранить tab_settings: Настройки CRM tab_bots: Боты -tab_mapping: Cоответствие table_name: Имя table_token: Токен table_activity: Активность -map_sites: Сайты -map_option: Выберите бота +api_key: API Ключ + no_bot_token: Введите токен wrong_data: Неверные данные @@ -15,12 +14,10 @@ bot_already_created: Бот уже создан not_find_account: Не удалось найти учетную запись, обратитесь в службу технической поддержки error_activating_channel: Ошибка при активации канала error_deactivating_channel: Ошибка при отключении канала -correct_url_key: Введите правильный URL или apiKey +correct_url_key: Введите корректный URL или apiKey error_creating_integration: Ошибка при создании интеграции error_creating_connection: Ошибка при создании соединения connection_already_created: Соединение уже создано missing_url_key: Отсутствует URL или apiKey -incorrect_url: Введите правильный URL CRM - - - +incorrect_url: Введите корректный URL CRM +incorrect_token: Установите корректный токен \ No newline at end of file diff --git a/web/script.js b/web/script.js new file mode 100644 index 0000000..91cfc6a --- /dev/null +++ b/web/script.js @@ -0,0 +1,108 @@ +$('#save-crm').on("submit", function(e) { + e.preventDefault(); + send( + $(this).attr('action'), + formDataToObj($(this).serializeArray()), + function () { + return 0; + } + ) +}); + +$("#save").on("submit", function(e) { + e.preventDefault(); + send( + $(this).attr('action'), + formDataToObj($(this).serializeArray()), + function () { + return 0; + } + ) +}); + +$("#add-bot").on("submit", function(e) { + e.preventDefault(); + send( + $(this).attr('action'), + formDataToObj($(this).serializeArray()), + function (data) { + let bots = $("#bots"); + if (bots.hasClass("hide")) { + bots.removeClass("hide") + } + $("#bots tbody").append(getBotTemplate(data)); + } + ) +}); + +$(document).on("click", ".activity-bot", function(e) { + let but = $(this); + send("/activity-bot/", + { + token: but.attr("data-token"), + active: (but.attr("data-activity") === 'true'), + clientId: $('input[name=clientId]').val(), + }, + function () { + if (but.attr("data-activity") === 'true') { + but.find('i').replaceWith('play_arrow'); + but.attr("data-activity", "false") + } else { + but.find('i').replaceWith('stop'); + but.attr("data-activity", "true") + } + } + ) +}); + +function send(url, data, callback) { + $('#msg').empty(); + $.ajax({ + url: url, + data: JSON.stringify(data), + type: "POST", + success: callback, + error: function (res){ + if (res.status < 400) { + if (res.responseText) { + document.location.replace( + location.protocol.concat("//").concat(window.location.host) + res.responseText + ); + } + } else { + $('#msg').html(`

${res.responseText}

`); + } + } + }); +} + +function getBotTemplate(data) { + let bot = JSON.parse(data); + tmpl = + ` + ${bot.name} + ${bot.token} + + + + `; + return tmpl; +} + +function formDataToObj(formArray) { + let obj = {}; + for (let i = 0; i < formArray.length; i++){ + obj[formArray[i]['name']] = formArray[i]['value']; + } + return obj; +} + +$( document ).ready(function() { + M.Tabs.init(document.getElementById("tab")); + if ($("table tbody").children().length === 0) { + $("#bots").addClass("hide"); + } +}); diff --git a/web/style.css b/web/style.css new file mode 100644 index 0000000..366cf5e --- /dev/null +++ b/web/style.css @@ -0,0 +1,24 @@ +.indent-top { + margin-top: 2%; +} + +.text-left{ + text-align: right; +} + +#bots .activity-bot{ + float: right; +} +#msg{ + height: 23px; +} + +.err-msg{ + color: red; + margin: 0; +} + +#logo{ + height: 80px; + border-bottom: 1px solid red; +} \ No newline at end of file diff --git a/web/telegram_logo.svg b/web/telegram_logo.svg new file mode 100644 index 0000000..49a8638 --- /dev/null +++ b/web/telegram_logo.svg @@ -0,0 +1,58 @@ + + + + + + + + + + image/svg+xml + + + + + + + + +