From f74945f5d84631e5ecf8fce247e63465a8da21cb Mon Sep 17 00:00:00 2001 From: Nilo Roberto C Paim Date: Fri, 5 Dec 2025 22:42:50 -0300 Subject: [PATCH] version 3 for the new User Area --- config.json | 6 +- controllers/transmissionController.go | 14 +- controllers/userController.go | 96 ++++++------ controllers/webhookController.go | 203 +++++++++++-------------- controllers/websocketController.go.old | 156 ------------------- models/models.go | 173 ++++++++++----------- routes/routes.go | 6 +- services/channelservices.go | 47 +++--- services/transmlogservices.go | 27 ++-- services/userservices.go | 48 +++--- 10 files changed, 291 insertions(+), 485 deletions(-) delete mode 100644 controllers/websocketController.go.old diff --git a/config.json b/config.json index 42bb1ee..3e778cd 100644 --- a/config.json +++ b/config.json @@ -1,5 +1,5 @@ { - "version": "2.1.1", + "version": "3.0.0", "apisecret": "pcast", "release": [ { @@ -10,7 +10,7 @@ "DB_DRIVER": "postgres", "DB_USER": "postgres", "DB_PASSWORD": "@407Smc837", - "DB_NAME": "pcast", + "DB_NAME": "area", "DB_PORT": 5432 } }, @@ -22,7 +22,7 @@ "DB_DRIVER": "postgres", "DB_USER": "postgres", "DB_PASSWORD": "@407Smc837", - "DB_NAME": "pcast", + "DB_NAME": "area", "DB_PORT": 5432 } } diff --git a/controllers/transmissionController.go b/controllers/transmissionController.go index f0536fa..8a84b6a 100644 --- a/controllers/transmissionController.go +++ b/controllers/transmissionController.go @@ -36,7 +36,7 @@ func WatchersCount(c *fiber.Ctx) error { } if transmission, exists := globals.Transmissions[channel]; exists { - return c.JSON(transmission.Watchers) + return c.JSON(transmission.Assistentes) } return c.SendStatus(fiber.StatusNotFound) @@ -55,14 +55,14 @@ func Watch(c *fiber.Ctx) error { log.Printf("User started watching channel on %s: %s", platform, channel) if transmission, exists := globals.Transmissions[channel]; exists { - transmission.Watchers = transmission.Watchers + 1 + transmission.Assistentes = transmission.Assistentes + 1 switch platform { case "desktop": transmission.Desktop = transmission.Desktop + 1 case "mobile": transmission.Mobile = transmission.Mobile + 1 } - return c.JSON(transmission.Watchers) + return c.JSON(transmission.Assistentes) } return c.SendStatus(fiber.StatusNotFound) @@ -81,9 +81,9 @@ func Leave(c *fiber.Ctx) error { log.Printf("User stopped watching channel: %s", channel) if transmission, exists := globals.Transmissions[channel]; exists { - transmission.Watchers = transmission.Watchers - 1 - if transmission.Watchers < 0 { - transmission.Watchers = 0 + transmission.Assistentes = transmission.Assistentes - 1 + if transmission.Assistentes < 0 { + transmission.Assistentes = 0 } switch platform { case "desktop": @@ -91,7 +91,7 @@ func Leave(c *fiber.Ctx) error { case "mobile": transmission.Mobile = transmission.Mobile - 1 } - return c.JSON(transmission.Watchers) + return c.JSON(transmission.Assistentes) } return c.SendStatus(fiber.StatusNotFound) diff --git a/controllers/userController.go b/controllers/userController.go index 7e54b54..259cc71 100644 --- a/controllers/userController.go +++ b/controllers/userController.go @@ -3,8 +3,6 @@ package controllers import ( "api/globals" "api/models" - "api/services" - "fmt" "github.com/gofiber/fiber/v2" ) @@ -25,66 +23,66 @@ func GetGroups(c *fiber.Ctx) error { return c.JSON(groups) } -func CreateUser(c *fiber.Ctx) error { - var body map[string]interface{} +// func CreateUser(c *fiber.Ctx) error { +// var body map[string]interface{} - if err := c.BodyParser(&body); err != nil { - return fiber.ErrBadRequest - } +// if err := c.BodyParser(&body); err != nil { +// return fiber.ErrBadRequest +// } - email := body["email"].(string) +// email := body["email"].(string) - user := services.GetUserByEmail(email) +// user := services.GetUserByEmail(email) - if user.ID == 0 { - fmt.Println("inexistent user") - } +// if user.ID == 0 { +// fmt.Println("inexistent user") +// } - return c.JSON(user) -} +// return c.JSON(user) +// } -func Login(c *fiber.Ctx) error { - var body map[string]interface{} +// func Login(c *fiber.Ctx) error { +// var body map[string]interface{} - var channel models.Channel - var channels []models.Channel +// var channel models.Channel +// var channels []models.Channel - if err := c.BodyParser(&body); err != nil { - return fiber.ErrBadRequest - } +// if err := c.BodyParser(&body); err != nil { +// return fiber.ErrBadRequest +// } - channelname := body["channel"].(string) - password := body["password"].(string) +// channelname := body["channel"].(string) +// password := body["password"].(string) - result := globals.DB.Where("name LIKE ?", channelname+"%").Find(&channels) - if result.RowsAffected == 0 { - return fiber.ErrNotFound - } +// result := globals.DB.Where("name LIKE ?", channelname+"%").Find(&channels) +// if result.RowsAffected == 0 { +// return fiber.ErrNotFound +// } - matchFound := false - for _, ch := range channels { - if ch.TransmissionKey == password { - channel = ch - matchFound = true - break - } - } +// matchFound := false +// for _, ch := range channels { +// if ch.TransmissionKey == password { +// channel = ch +// matchFound = true +// break +// } +// } - if !matchFound { - return fiber.ErrUnauthorized - } +// if !matchFound { +// return fiber.ErrUnauthorized +// } - customer := models.Customer{} - globals.DB.First(&customer, channel.CustomerID) +// customer := models.Cliente{} +// globals.DB.First(&customer, channel.CustomerID) - token, err := services.GenerateJWT(channel) +// token, err := services.GenerateJWT(channel) - if err != nil { - return fiber.ErrInternalServerError - } +// if err != nil { +// return fiber.ErrInternalServerError +// } - return c.JSON(fiber.Map{ - "token": token, - "customer": customer, - }) -} +// return c.JSON(fiber.Map{ +// "token": token, +// "cliente": customer, +// }) +// } diff --git a/controllers/webhookController.go b/controllers/webhookController.go index c263fca..ca165df 100644 --- a/controllers/webhookController.go +++ b/controllers/webhookController.go @@ -5,9 +5,7 @@ import ( "api/models" "api/services" "api/utils" - "fmt" "log" - "strings" "time" "github.com/gofiber/fiber/v2" @@ -40,25 +38,6 @@ func ServerStart(c *fiber.Ctx) error { return c.SendString("Server started: " + string(c.Body())) } -// func OnUpdate(c *fiber.Ctx) error { -// p := new(models.Update) -// if err := c.BodyParser(p); err != nil { -// log.Printf("Error Update: %s\n", err) -// return err -// } - -// log.Printf("======================== Update") -// utils.PrettyPrintJson(p) - -// if len(p.Groups) > 0 { -// for _, g := range p.Groups { -// log.Printf("======================== Update %s %s [(%dx%d) %d]\n", g.Channel, g.UpdPub.StartTime, g.VideoWidth, g.VideoHeight, g.UpdPub.ReadBytesSum) -// } -// } - -// return c.SendString("On_Update: " + string(c.Body())) -// } - func OnSubStart(c *fiber.Ctx) error { return nil } @@ -113,7 +92,7 @@ func OnPubStop(c *fiber.Ctx) error { } now := time.Now() - duration := now.Sub(transm.StartTime) + duration := now.Sub(transm.Inicio) minutes := int(duration.Minutes()) @@ -135,123 +114,123 @@ func OnPubStop(c *fiber.Ctx) error { // services.AddTransmissionlog(p.StreamName, msg) // Saves the transmission on the database - transm.Duration = minutes + transm.Duracao = minutes globals.DB.Debug().Create(&transm) delete(globals.Transmissions, p.StreamName) return c.SendString("On_Pub_Stop: " + string(c.Body())) } -func WixTest(c *fiber.Ctx) error { +// func WixTestX(c *fiber.Ctx) error { - // Get the data from the callback - var r ResponseTest - if err := c.BodyParser(&r); err != nil { - return err - } +// // Get the data from the callback +// var r ResponseTest +// if err := c.BodyParser(&r); err != nil { +// return err +// } - // Pass the data to variables - cnpj := strings.TrimSpace(r.Data.CNPJ) - name := strings.TrimSpace(r.Data.Name) - email := strings.TrimSpace(r.Data.Email) +// // Pass the data to variables +// cnpj := strings.TrimSpace(r.Data.CNPJ) +// name := strings.TrimSpace(r.Data.Name) +// email := strings.TrimSpace(r.Data.Email) - // Check if it is a valid CNPJ - if !utils.IsValid(cnpj) { - utils.SendTestEmail(email, name, "Foi informado um CNPJ inválido") - return c.SendString("CNPJ Inválido") - } +// // Check if it is a valid CNPJ +// if !utils.IsValid(cnpj) { +// utils.SendTestEmail(email, name, "Foi informado um CNPJ inválido") +// return c.SendString("CNPJ Inválido") +// } - // Formats the CNPJ - cnpjf := fmt.Sprintf("%s.%s.%s/%s-%s", - cnpj[:2], - cnpj[2:5], - cnpj[5:8], - cnpj[8:12], - cnpj[12:]) +// // Formats the CNPJ +// cnpjf := fmt.Sprintf("%s.%s.%s/%s-%s", +// cnpj[:2], +// cnpj[2:5], +// cnpj[5:8], +// cnpj[8:12], +// cnpj[12:]) - // Let's see if it is a real CNPJ - log.Printf("CNPJ %s [%s] requisitou um teste usando o email %s (%s)\n", cnpj, cnpjf, name, email) - empresa := utils.GetEmpresa(cnpj) +// // Let's see if it is a real CNPJ +// log.Printf("CNPJ %s [%s] requisitou um teste usando o email %s (%s)\n", cnpj, cnpjf, name, email) +// empresa := utils.GetEmpresa(cnpj) - if empresa.Situacao != "ATIVA" { - utils.SendTestEmail(email, name, "Foi informado um CNPJ pertencente à uma empresa inativa") - return c.SendString("Empresa inativa") - } +// if empresa.Situacao != "ATIVA" { +// utils.SendTestEmail(email, name, "Foi informado um CNPJ pertencente à uma empresa inativa") +// return c.SendString("Empresa inativa") +// } - // Let's see if its already on database - customer := services.GetCustomerByCNPJ(cnpjf) +// // Let's see if its already on database +// customer := services.GetCustomerByCNPJ(cnpjf) - user := services.GetUserByEmail(email) +// user := services.GetUserByEmail(email) - var userdb models.SystemUser - var customerdb models.Customer +// var userdb models.SystemUser +// var customerdb models.Customer - if user.ID == 0 { - // Email not in database. Let's insert it - userdb = models.SystemUser{ - Email: email, - } +// if user.ID == 0 { +// // Email not in database. Let's insert it +// userdb = models.SystemUser{ +// Email: email, +// } - err := globals.DB.Create(&userdb) - if err != nil { - log.Printf("Cannot create test user: %v\n", err) - } +// err := globals.DB.Create(&userdb) +// if err != nil { +// log.Printf("Cannot create test user: %v\n", err) +// } - user.ID = userdb.ID - } +// user.ID = userdb.ID +// } - if customer.ID == 0 { - // Inexistent customer; insert it into database - customerwww := utils.GetEmpresa(cnpj) +// if customer.ID == 0 { +// // Inexistent customer; insert it into database +// customerwww := utils.GetEmpresa(cnpj) - customerdb = models.Customer{ - CNPJ: customerwww.CNPJ, - Nome: customerwww.Nome, - NomeFantasia: customerwww.Nome, - Tipo: customerwww.Tipo, - Porte: customerwww.Porte, - Situacao: customerwww.Situacao, - Abertura: customerwww.Abertura, - NaturezaJuridica: customerwww.NaturezaJuridica, - Logradouro: customerwww.Logradouro, - Numero: customerwww.Numero, - Complemento: customerwww.Complemento, - Municipio: customerwww.Municipio, - Bairro: customerwww.Bairro, - UF: customerwww.UF, - CEP: customerwww.CEP, - } +// customerdb = models.Customer{ +// CNPJ: customerwww.CNPJ, +// Nome: customerwww.Nome, +// NomeFantasia: customerwww.Nome, +// Tipo: customerwww.Tipo, +// Porte: customerwww.Porte, +// Situacao: customerwww.Situacao, +// Abertura: customerwww.Abertura, +// NaturezaJuridica: customerwww.NaturezaJuridica, +// Logradouro: customerwww.Logradouro, +// Numero: customerwww.Numero, +// Complemento: customerwww.Complemento, +// Municipio: customerwww.Municipio, +// Bairro: customerwww.Bairro, +// UF: customerwww.UF, +// CEP: customerwww.CEP, +// } - err := globals.DB.Create(&customerdb) - if err.Error != nil { - log.Printf("Cannot create test user: %v\n", err) - } +// err := globals.DB.Create(&customerdb) +// if err.Error != nil { +// log.Printf("Cannot create test user: %v\n", err) +// } - // Now let's create the customer channel - opts := utils.GenerationOptions{ - Length: 10, - } +// // Now let's create the customer channel +// opts := utils.GenerationOptions{ +// Length: 10, +// } - tkey, _ := utils.GenerateString(opts) +// tkey, _ := utils.GenerateString(opts) - channel := models.Channel{ - Name: cnpj + "-01", - TransmissionKey: tkey, - CustomerID: uint(customerdb.ID), - ServerID: 1, - } - err = globals.DB.Create(&channel) - if err.Error != nil { - log.Printf("Cannot create test channel: %v\n", err) - } +// channel := models.Channel{ +// Name: cnpj + "-01", +// TransmissionKey: tkey, +// CustomerID: uint(customerdb.ID), +// ServerID: 1, +// } +// err = globals.DB.Create(&channel) +// if err.Error != nil { +// log.Printf("Cannot create test channel: %v\n", err) +// } - // Finally, send an email - utils.SendTestEmailApproval(email, name, tkey, cnpj+"-01") +// // Finally, send an email +// utils.SendTestEmailApproval(email, name, tkey, cnpj+"-01") - } +// } - return c.SendString("On Test: " + empresa.Nome) -} +// return c.SendString("On Test: " + empresa.Nome) +// } func WixIntegration(c *fiber.Ctx) error { log.Println(string(c.Body())) diff --git a/controllers/websocketController.go.old b/controllers/websocketController.go.old deleted file mode 100644 index 1a900ec..0000000 --- a/controllers/websocketController.go.old +++ /dev/null @@ -1,156 +0,0 @@ -package controllers - -import ( - "encoding/json" - "fmt" - "log" - "sync" - "time" - - "github.com/gofiber/websocket/v2" -) - -// WebSocketManager handles all active WebSocket connections -type WebSocketManager struct { - connections map[*websocket.Conn]bool - mutex sync.RWMutex - broadcast chan WebSocketMessage -} - -// WebSocketMessage represents the structure of messages -type WebSocketMessage struct { - Command string `json:"command"` - Channel string `json:"channel"` - Text string `json:"text"` -} - -// Global instance of WebSocketManager -var WSManager = &WebSocketManager{ - connections: make(map[*websocket.Conn]bool), - broadcast: make(chan WebSocketMessage, 100), // Buffer size of 100 -} - -func init() { - // Start the broadcast handler - go WSManager.handleBroadcasts() -} - -func (m *WebSocketManager) handleBroadcasts() { - for message := range m.broadcast { - jsonMessage, err := json.Marshal(message) - if err != nil { - log.Printf("Error marshaling message: %v", err) - continue - } - - m.mutex.RLock() - for conn := range m.connections { - // Send message asynchronously - go func(c *websocket.Conn) { - writeTimeout := time.Now().Add(time.Second * 5) - c.SetWriteDeadline(writeTimeout) - - if err := c.WriteMessage(websocket.TextMessage, jsonMessage); err != nil { - log.Printf("Error sending message: %v", err) - m.removeConnection(c) - } - }(conn) - } - m.mutex.RUnlock() - } -} - -// BroadcastMessage sends a message to all connected clients -func (m *WebSocketManager) BroadcastMessage(command, channel, text string) { - message := WebSocketMessage{ - Command: command, - Channel: channel, - Text: text, - } - - // Non-blocking send to broadcast channel - select { - case m.broadcast <- message: - // Message queued successfully - default: - log.Println("Broadcast channel full, message dropped") - } -} - -// SendMessageToClient sends a message to a specific client -func (m *WebSocketManager) SendMessageToClient(conn *websocket.Conn, command, channel, text string) error { - message := WebSocketMessage{ - Command: command, - Channel: channel, - Text: text, - } - - jsonMessage, err := json.Marshal(message) - if err != nil { - return err - } - - m.mutex.RLock() - defer m.mutex.RUnlock() - - if _, exists := m.connections[conn]; exists { - writeTimeout := time.Now().Add(time.Second * 5) - conn.SetWriteDeadline(writeTimeout) - return conn.WriteMessage(websocket.TextMessage, jsonMessage) - } - return nil -} - -func (m *WebSocketManager) addConnection(conn *websocket.Conn) { - m.mutex.Lock() - defer m.mutex.Unlock() - m.connections[conn] = true -} - -func (m *WebSocketManager) removeConnection(conn *websocket.Conn) { - m.mutex.Lock() - defer m.mutex.Unlock() - delete(m.connections, conn) - conn.Close() -} - -// WebsocketHandler handles WebSocket connections -func WebsocketHandler(c *websocket.Conn) { - // Set read deadline - c.SetReadDeadline(time.Now().Add(time.Second * 60)) // 1 minute timeout - - // Add the connection to our manager - WSManager.addConnection(c) - defer WSManager.removeConnection(c) - - // Handle incoming messages - for { - _, message, err := c.ReadMessage() - if err != nil { - log.Println("Error reading message:", err) - break - } - - // Process message asynchronously - go func() { - var wsMessage WebSocketMessage - if err := json.Unmarshal(message, &wsMessage); err != nil { - log.Printf("Error parsing message: %v", err) - return - } - - switch wsMessage.Command { - case "chat": - WSManager.BroadcastMessage("chat", wsMessage.Channel, wsMessage.Text) - case "join": - WSManager.BroadcastMessage("system", wsMessage.Channel, - fmt.Sprintf("User joined channel %s", wsMessage.Channel)) - case "leave": - WSManager.BroadcastMessage("system", wsMessage.Channel, - fmt.Sprintf("User left channel %s", wsMessage.Channel)) - default: - WSManager.SendMessageToClient(c, "error", "", "Unknown command") - } - }() - } -} diff --git a/models/models.go b/models/models.go index 0d68b1d..07f877f 100644 --- a/models/models.go +++ b/models/models.go @@ -120,13 +120,15 @@ type SystemProgramMethodRole struct { // ==================================================================== // PCast tables -type Customer struct { +type Cliente struct { ID int32 `gorm:"primaryKey;autoIncrement;column:id"` CNPJ string `gorm:"unique;column:cnpj"` - NIC string `gorm:"unique;column:nic"` Nome string `gorm:"not null;column:nome"` NomeFantasia string `gorm:"column:nome_fantasia"` - Tipo string `gorm:"column:tipo"` + Email string `gorm:"column:email"` + TipoCliente string `gorm:"column:tipo_cliente"` + TipoServico uint `gorm:"column:tipo_servico"` + Tipo uint `gorm:"column:tipo"` Porte string `gorm:"column:porte"` Situacao string `gorm:"column:situacao"` Abertura string `gorm:"column:abertura"` @@ -138,12 +140,10 @@ type Customer struct { Bairro string `gorm:"column:bairro"` UF string `gorm:"column:uf"` CEP string `gorm:"column:cep"` - CustomerLocal string `gorm:"not null;column:customer_local"` - CustomerType string `gorm:"not null;column:customer_type"` - UserFullName string `gorm:"not null;column:userfullname"` - UserEmail string `gorm:"not null;column:useremail"` - UserName string `gorm:"not null;column:username"` - Password []byte `gorm:"not null;column:password"` + CreatedAt time.Time + CreatedBy int + UpdatedAt time.Time + UpdatedBy int } type Email struct { @@ -153,105 +153,108 @@ type Email struct { } // Server represents the servers table in the database -type Server struct { - ID uint `gorm:"primaryKey;column:id;autoIncrement"` - Name string `gorm:"column:name;type:text;not null"` - IP string `gorm:"column:ip;type:text;not null"` - Subdomain string `gorm:"column:subdomain;type:text;not null"` +type Servidor struct { + ID uint `gorm:"primaryKey;column:id;autoIncrement"` + Nome string `gorm:"column:nome;type:text;not null"` + IP string `gorm:"column:ip;type:text;not null"` + Subdominio string `gorm:"column:subdominio;type:text;not null"` // Relationship (back-reference) - Channels []Channel `gorm:"foreignKey:ServerID"` + Canais []Canal `gorm:"foreignKey:ServidorID"` } -// TableName overrides the table name -func (Server) TableName() string { - return "servers" -} +// // TableName overrides the table name +// func (Server) TableName() string { +// return "servers" +// } -// Plan represents the plans table in the database -type Plan struct { - ID uint `gorm:"primaryKey;column:id;autoIncrement"` - Name string `gorm:"column:name;type:text;not null"` - DailyLimitTransmission int `gorm:"column:daily_limit_transmission;type:integer;not null"` - MonthValue float64 `gorm:"column:month_value;type:numeric(10,2);not null"` - YearValue float64 `gorm:"column:year_value;type:numeric(10,2);not null"` +// // Plan represents the plans table in the database +// type Plan struct { +// ID uint `gorm:"primaryKey;column:id;autoIncrement"` +// Name string `gorm:"column:name;type:text;not null"` +// DailyLimitTransmission int `gorm:"column:daily_limit_transmission;type:integer;not null"` +// MonthValue float64 `gorm:"column:month_value;type:numeric(10,2);not null"` +// YearValue float64 `gorm:"column:year_value;type:numeric(10,2);not null"` - // Relationship (back-reference) - Channels []Channel `gorm:"foreignKey:PlanID"` -} +// // Relationship (back-reference) +// Channels []Channel `gorm:"foreignKey:PlanID"` +// } -// TableName overrides the table name -func (Plan) TableName() string { - return "plans" -} +// // TableName overrides the table name +// func (Plan) TableName() string { +// return "plans" +// } -// ChannelStat represents the channel_stats table in the database -type ChannelStat struct { - ID uint `gorm:"primaryKey;column:id;autoIncrement"` - Name string `gorm:"column:name;type:text;not null;uniqueIndex"` - Description string `gorm:"column:description;type:text;not null"` +// // ChannelStat represents the channel_stats table in the database +// type ChannelStat struct { +// ID uint `gorm:"primaryKey;column:id;autoIncrement"` +// Name string `gorm:"column:name;type:text;not null;uniqueIndex"` +// Description string `gorm:"column:description;type:text;not null"` - // Relationship (back-reference) - Channels []Channel `gorm:"foreignKey:ChannelStatID"` -} +// // Relationship (back-reference) +// Channels []Channel `gorm:"foreignKey:ChannelStatID"` +// } -// TableName overrides the table name -func (ChannelStat) TableName() string { - return "channel_stats" -} +// // TableName overrides the table name +// func (ChannelStat) TableName() string { +// return "channel_stats" +// } -type Channel struct { - ID uint `gorm:"primaryKey;column:id;autoIncrement"` - Name string `gorm:"column:name;type:text;not null;uniqueIndex"` - TransmissionKey string `gorm:"column:transmission_key;type:text;not null;uniqueIndex"` - DateLimit time.Time `gorm:"column:date_limit;type:date;not null"` - CustomerID uint `gorm:"column:customer_id;not null"` - ServerID uint `gorm:"column:server_id;not null"` - PlanID uint `gorm:"column:plan_id;not null"` - Status string `gorm:"column:status;not null"` +type Canal struct { + ID uint `gorm:"primaryKey;column:id;autoIncrement"` + ClienteID uint `gorm:"column:cliente_id;not null"` + ServidorID uint `gorm:"column:servidor_id;not null"` + Nome string `gorm:"column:nome;type:text;not null;uniqueIndex"` + Chave string `gorm:"column:chave;type:text;not null;uniqueIndex"` + LimiteDiario int `gorm:"column:limite_diario;not null"` + Validade time.Time `gorm:"column:validade;type:date;not null"` + CreatedAt time.Time `gorm:"column:created_at;type:timestamp;not null"` + CreatedBy int `gorm:"column:created_by;not null"` + UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp;not null"` + UpdatedBy int `gorm:"column:updated_by;not null"` // Define relationships - Customer Customer `gorm:"foreignKey:CustomerID;references:ID"` - Server Server `gorm:"foreignKey:ServerID;references:ID"` - Plan Plan `gorm:"foreignKey:PlanID;references:ID"` + Cliente Cliente `gorm:"foreignKey:ClienteID;references:ID"` + Servidor Servidor `gorm:"foreignKey:ServidorID;references:ID"` } -// TableName overrides the table name -func (Channel) TableName() string { - return "channels" -} +// // TableName overrides the table name +// func (Channel) TableName() string { +// return "channels" +// } -// TransmissionLog represents the transmissionlog table in the database -type TransmissionLog struct { - ID uint `gorm:"primaryKey;column:id;autoIncrement"` - Datetime time.Time `gorm:"column:datetime;type:timestamp;not null"` - Channel string `gorm:"column:channel;type:text;not null"` - Message string `gorm:"column:message;type:text;not null"` -} +// // TransmissionLog represents the transmissionlog table in the database +// type TransmissionLog struct { +// ID uint `gorm:"primaryKey;column:id;autoIncrement"` +// Datetime time.Time `gorm:"column:datetime;type:timestamp;not null"` +// Channel string `gorm:"column:channel;type:text;not null"` +// Message string `gorm:"column:message;type:text;not null"` +// } -// TableName overrides the table name -func (TransmissionLog) TableName() string { - return "transmissionlog" -} +// // TableName overrides the table name +// func (TransmissionLog) TableName() string { +// return "transmissionlog" +// } // Available on RAM during the execution // CurrentTransmission represents the transmissions table in the database type CurrentTransmission struct { - ID uint `gorm:"primaryKey;column:id;autoIncrement"` - Channel string `gorm:"column:channel;type:text;not null"` - CustomerID uint `gorm:"column:customer_id;not null"` - StartTime time.Time `gorm:"column:starttime;type:timestamp;not null"` - Duration int `gorm:"column:duration;not null"` - Limit time.Time `gorm:"-"` - SessionID string `gorm:"-"` - PlayerKey string `gorm:"-"` - PlanDailyLimit int `gorm:"-"` - Watchers int `gorm:"column:watchers;not null"` - Desktop int `gorm:"column:desktop;not null"` - Mobile int `gorm:"column:mobile;not null"` + ID uint `gorm:"primaryKey;column:id;autoIncrement"` + Canal string `gorm:"column:canal;type:text;not null"` + Inicio time.Time `gorm:"column:inicio;type:timestamp;not null"` + Duracao int `gorm:"column:duracao;not null"` + Assistentes int `gorm:"column:assistentes;not null"` + Desktop int `gorm:"column:desktop;not null"` + Mobile int `gorm:"column:mobile;not null"` + Mensagem string `gorm:"column:mensagem;type:text;not null"` + Ativa string `gorm:"column:ativa;type:char(1);not null"` + SessionID string `gorm:"-"` + Chave string `gorm:"-"` + Limite time.Time `gorm:"-"` + LimiteDiario int `gorm:"-"` } // TableName overrides the table name func (CurrentTransmission) TableName() string { - return "transmissions" + return "transmissao" } diff --git a/routes/routes.go b/routes/routes.go index e3e539c..9de86ea 100644 --- a/routes/routes.go +++ b/routes/routes.go @@ -10,7 +10,7 @@ import ( func Setup(app *fiber.App) { app.Post("/integration", controllers.WixIntegration) - app.Post("/test", controllers.WixTest) + // app.Post("/test", controllers.WixTest) app.Get("/version", controllers.Version) @@ -19,9 +19,9 @@ func Setup(app *fiber.App) { app.Get("/users", controllers.GetUsers) app.Get("/groups", controllers.GetGroups) - app.Post("/user", controllers.CreateUser) + // app.Post("/user", controllers.CreateUser) - app.Post("/login", controllers.Login) + // app.Post("/login", controllers.Login) // Webhooks app.Post("/on_server_start", controllers.ServerStart) diff --git a/services/channelservices.go b/services/channelservices.go index 6806906..2767314 100644 --- a/services/channelservices.go +++ b/services/channelservices.go @@ -11,15 +11,15 @@ func VerifyTransmissionsLimits() { // log.Println("Verificando") for channelname, currentTransmission := range globals.Transmissions { // If the channel has no daily transmission limit, skip the verification (Channels with 24 hours daily limit) - if time.Duration(currentTransmission.PlanDailyLimit) == 1440 { + if time.Duration(currentTransmission.LimiteDiario) == 1440 { continue } - AddTransmissionlog(channelname, "Verificando expiração de transmissão") + // AddTransmissionlog(channelname, "Verificando expiração de transmissão") // TODO: Implementar verificação de limite de transmissão diária (ou seja, quanto já foi transmitido HOJE) - if time.Now().After(currentTransmission.Limit) { - AddTransmissionlog(channelname, "Limite de transmissão diária atingido") + if time.Now().After(currentTransmission.Limite) { + // AddTransmissionlog(channelname, "Limite de transmissão diária atingido") utils.KickSession(channelname, currentTransmission.SessionID) } } @@ -27,48 +27,45 @@ func VerifyTransmissionsLimits() { func VerifyTransmissionAuthorization(channelname, sessionid, transmissionkey, playerKey string) (bool, models.CurrentTransmission) { var ( - channel models.Channel - plan models.Plan + channel models.Canal currentTransmission models.CurrentTransmission ) - globals.DB.Where("name = ?", channelname).First(&channel) - globals.DB.First(&plan, channel.PlanID) + globals.DB.Where("nome = ?", channelname).First(&channel) - currentTransmission.Channel = channel.Name - currentTransmission.CustomerID = channel.CustomerID + currentTransmission.Canal = channel.Nome currentTransmission.SessionID = sessionid - currentTransmission.PlayerKey = playerKey - currentTransmission.PlanDailyLimit = plan.DailyLimitTransmission - currentTransmission.StartTime = time.Now() + currentTransmission.Chave = transmissionkey + currentTransmission.LimiteDiario = channel.LimiteDiario + currentTransmission.Inicio = time.Now() - currentTransmission.Limit = currentTransmission.StartTime.Add(time.Duration(plan.DailyLimitTransmission) * time.Minute) + currentTransmission.Limite = currentTransmission.Inicio.Add(time.Duration(channel.LimiteDiario) * time.Hour) // If the channel is not found, kick the session if channel.ID == 0 { - AddTransmissionlog(channelname, "Canal inexistente") + // AddTransmissionlog(channelname, "Canal inexistente") utils.KickSession(channelname, sessionid) return false, currentTransmission } // If the channel expiration date is reached, kick the session - if time.Now().After(channel.DateLimit) { - AddTransmissionlog(channelname, "Canal com data de expiração vencida") + if time.Now().After(channel.Validade) { + // AddTransmissionlog(channelname, "Canal com data de expiração vencida") utils.KickSession(channelname, sessionid) return false, currentTransmission } - // If the channel is not active, kick the session - if channel.Status != "A" { - AddTransmissionlog(channelname, "Canal não está ativo") - utils.KickSession(channelname, sessionid) - return false, currentTransmission - } + // // If the channel is not active, kick the session + // if channel.Status != "A" { + // AddTransmissionlog(channelname, "Canal não está ativo") + // utils.KickSession(channelname, sessionid) + // return false, currentTransmission + // } // If the transmission key does not match, kick the session - if transmissionkey != channel.TransmissionKey { - AddTransmissionlog(channelname, "Transmissão com chave de transmissão errada") + if transmissionkey != channel.Chave { + // AddTransmissionlog(channelname, "Transmissão com chave de transmissão errada") utils.KickSession(channelname, sessionid) return false, currentTransmission } diff --git a/services/transmlogservices.go b/services/transmlogservices.go index e3d3b29..4df3e85 100644 --- a/services/transmlogservices.go +++ b/services/transmlogservices.go @@ -1,22 +1,15 @@ package services -import ( - "api/globals" - "api/models" - "log" - "time" -) +// func AddTransmissionlog(channelname, message string) { +// var tlog models.TransmissionLog -func AddTransmissionlog(channelname, message string) { - var tlog models.TransmissionLog +// tlog.Channel = channelname +// tlog.Message = message +// tlog.Datetime = time.Now() - tlog.Channel = channelname - tlog.Message = message - tlog.Datetime = time.Now() +// result := globals.DB.Create(&tlog) - result := globals.DB.Create(&tlog) - - if result.Error != nil { - log.Printf("%v\n", result.Error) - } -} +// if result.Error != nil { +// log.Printf("%v\n", result.Error) +// } +// } diff --git a/services/userservices.go b/services/userservices.go index b8363a4..eb5b2f0 100644 --- a/services/userservices.go +++ b/services/userservices.go @@ -1,38 +1,30 @@ package services -import ( - "api/globals" - "api/models" - "time" +// var jwtSecret = []byte("your_secret_key") // Replace with your actual secret - "github.com/golang-jwt/jwt/v4" -) +// func GetUserByEmail(email string) models.SystemUser { +// var user models.SystemUser -var jwtSecret = []byte("your_secret_key") // Replace with your actual secret +// globals.DB.Where("email = ?", email).Find(&user) -func GetUserByEmail(email string) models.SystemUser { - var user models.SystemUser +// return user +// } - globals.DB.Where("email = ?", email).Find(&user) +// func GetCustomerByCNPJX(cnpj string) models.Customer { +// var user models.Customer - return user -} +// globals.DB.Where("cnpj = ?", cnpj).Find(&user) -func GetCustomerByCNPJ(cnpj string) models.Customer { - var user models.Customer +// return user +// } - globals.DB.Where("cnpj = ?", cnpj).Find(&user) +// func GenerateJWT(channel models.Channel) (string, error) { +// claims := jwt.MapClaims{ +// "channel_id": channel.ID, +// "channel_name": channel.Name, +// "exp": time.Now().Add(time.Minute * 60).Unix(), +// } - return user -} - -func GenerateJWT(channel models.Channel) (string, error) { - claims := jwt.MapClaims{ - "channel_id": channel.ID, - "channel_name": channel.Name, - "exp": time.Now().Add(time.Minute * 60).Unix(), - } - - token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) - return token.SignedString(jwtSecret) -} +// token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) +// return token.SignedString(jwtSecret) +// }