version 3 for the new User Area

main
Nilo Roberto C Paim 2025-12-05 22:42:50 -03:00
parent 3fb3d407b1
commit f74945f5d8
10 changed files with 291 additions and 485 deletions

View File

@ -1,5 +1,5 @@
{ {
"version": "2.1.1", "version": "3.0.0",
"apisecret": "pcast", "apisecret": "pcast",
"release": [ "release": [
{ {
@ -10,7 +10,7 @@
"DB_DRIVER": "postgres", "DB_DRIVER": "postgres",
"DB_USER": "postgres", "DB_USER": "postgres",
"DB_PASSWORD": "@407Smc837", "DB_PASSWORD": "@407Smc837",
"DB_NAME": "pcast", "DB_NAME": "area",
"DB_PORT": 5432 "DB_PORT": 5432
} }
}, },
@ -22,7 +22,7 @@
"DB_DRIVER": "postgres", "DB_DRIVER": "postgres",
"DB_USER": "postgres", "DB_USER": "postgres",
"DB_PASSWORD": "@407Smc837", "DB_PASSWORD": "@407Smc837",
"DB_NAME": "pcast", "DB_NAME": "area",
"DB_PORT": 5432 "DB_PORT": 5432
} }
} }

View File

@ -36,7 +36,7 @@ func WatchersCount(c *fiber.Ctx) error {
} }
if transmission, exists := globals.Transmissions[channel]; exists { if transmission, exists := globals.Transmissions[channel]; exists {
return c.JSON(transmission.Watchers) return c.JSON(transmission.Assistentes)
} }
return c.SendStatus(fiber.StatusNotFound) 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) log.Printf("User started watching channel on %s: %s", platform, channel)
if transmission, exists := globals.Transmissions[channel]; exists { if transmission, exists := globals.Transmissions[channel]; exists {
transmission.Watchers = transmission.Watchers + 1 transmission.Assistentes = transmission.Assistentes + 1
switch platform { switch platform {
case "desktop": case "desktop":
transmission.Desktop = transmission.Desktop + 1 transmission.Desktop = transmission.Desktop + 1
case "mobile": case "mobile":
transmission.Mobile = transmission.Mobile + 1 transmission.Mobile = transmission.Mobile + 1
} }
return c.JSON(transmission.Watchers) return c.JSON(transmission.Assistentes)
} }
return c.SendStatus(fiber.StatusNotFound) return c.SendStatus(fiber.StatusNotFound)
@ -81,9 +81,9 @@ func Leave(c *fiber.Ctx) error {
log.Printf("User stopped watching channel: %s", channel) log.Printf("User stopped watching channel: %s", channel)
if transmission, exists := globals.Transmissions[channel]; exists { if transmission, exists := globals.Transmissions[channel]; exists {
transmission.Watchers = transmission.Watchers - 1 transmission.Assistentes = transmission.Assistentes - 1
if transmission.Watchers < 0 { if transmission.Assistentes < 0 {
transmission.Watchers = 0 transmission.Assistentes = 0
} }
switch platform { switch platform {
case "desktop": case "desktop":
@ -91,7 +91,7 @@ func Leave(c *fiber.Ctx) error {
case "mobile": case "mobile":
transmission.Mobile = transmission.Mobile - 1 transmission.Mobile = transmission.Mobile - 1
} }
return c.JSON(transmission.Watchers) return c.JSON(transmission.Assistentes)
} }
return c.SendStatus(fiber.StatusNotFound) return c.SendStatus(fiber.StatusNotFound)

View File

@ -3,8 +3,6 @@ package controllers
import ( import (
"api/globals" "api/globals"
"api/models" "api/models"
"api/services"
"fmt"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
) )
@ -25,66 +23,66 @@ func GetGroups(c *fiber.Ctx) error {
return c.JSON(groups) return c.JSON(groups)
} }
func CreateUser(c *fiber.Ctx) error { // func CreateUser(c *fiber.Ctx) error {
var body map[string]interface{} // var body map[string]interface{}
if err := c.BodyParser(&body); err != nil { // if err := c.BodyParser(&body); err != nil {
return fiber.ErrBadRequest // return fiber.ErrBadRequest
} // }
email := body["email"].(string) // email := body["email"].(string)
user := services.GetUserByEmail(email) // user := services.GetUserByEmail(email)
if user.ID == 0 { // if user.ID == 0 {
fmt.Println("inexistent user") // fmt.Println("inexistent user")
} // }
return c.JSON(user) // return c.JSON(user)
} // }
func Login(c *fiber.Ctx) error { // func Login(c *fiber.Ctx) error {
var body map[string]interface{} // var body map[string]interface{}
var channel models.Channel // var channel models.Channel
var channels []models.Channel // var channels []models.Channel
if err := c.BodyParser(&body); err != nil { // if err := c.BodyParser(&body); err != nil {
return fiber.ErrBadRequest // return fiber.ErrBadRequest
} // }
channelname := body["channel"].(string) // channelname := body["channel"].(string)
password := body["password"].(string) // password := body["password"].(string)
result := globals.DB.Where("name LIKE ?", channelname+"%").Find(&channels) // result := globals.DB.Where("name LIKE ?", channelname+"%").Find(&channels)
if result.RowsAffected == 0 { // if result.RowsAffected == 0 {
return fiber.ErrNotFound // return fiber.ErrNotFound
} // }
matchFound := false // matchFound := false
for _, ch := range channels { // for _, ch := range channels {
if ch.TransmissionKey == password { // if ch.TransmissionKey == password {
channel = ch // channel = ch
matchFound = true // matchFound = true
break // break
} // }
} // }
if !matchFound { // if !matchFound {
return fiber.ErrUnauthorized // return fiber.ErrUnauthorized
} // }
customer := models.Customer{} // customer := models.Cliente{}
globals.DB.First(&customer, channel.CustomerID) // globals.DB.First(&customer, channel.CustomerID)
token, err := services.GenerateJWT(channel) // token, err := services.GenerateJWT(channel)
if err != nil { // if err != nil {
return fiber.ErrInternalServerError // return fiber.ErrInternalServerError
} // }
return c.JSON(fiber.Map{ // return c.JSON(fiber.Map{
"token": token, // "token": token,
"customer": customer, // "cliente": customer,
}) // })
} // }

View File

@ -5,9 +5,7 @@ import (
"api/models" "api/models"
"api/services" "api/services"
"api/utils" "api/utils"
"fmt"
"log" "log"
"strings"
"time" "time"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
@ -40,25 +38,6 @@ func ServerStart(c *fiber.Ctx) error {
return c.SendString("Server started: " + string(c.Body())) 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 { func OnSubStart(c *fiber.Ctx) error {
return nil return nil
} }
@ -113,7 +92,7 @@ func OnPubStop(c *fiber.Ctx) error {
} }
now := time.Now() now := time.Now()
duration := now.Sub(transm.StartTime) duration := now.Sub(transm.Inicio)
minutes := int(duration.Minutes()) minutes := int(duration.Minutes())
@ -135,123 +114,123 @@ func OnPubStop(c *fiber.Ctx) error {
// services.AddTransmissionlog(p.StreamName, msg) // services.AddTransmissionlog(p.StreamName, msg)
// Saves the transmission on the database // Saves the transmission on the database
transm.Duration = minutes transm.Duracao = minutes
globals.DB.Debug().Create(&transm) globals.DB.Debug().Create(&transm)
delete(globals.Transmissions, p.StreamName) delete(globals.Transmissions, p.StreamName)
return c.SendString("On_Pub_Stop: " + string(c.Body())) 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 // // Get the data from the callback
var r ResponseTest // var r ResponseTest
if err := c.BodyParser(&r); err != nil { // if err := c.BodyParser(&r); err != nil {
return err // return err
} // }
// Pass the data to variables // // Pass the data to variables
cnpj := strings.TrimSpace(r.Data.CNPJ) // cnpj := strings.TrimSpace(r.Data.CNPJ)
name := strings.TrimSpace(r.Data.Name) // name := strings.TrimSpace(r.Data.Name)
email := strings.TrimSpace(r.Data.Email) // email := strings.TrimSpace(r.Data.Email)
// Check if it is a valid CNPJ // // Check if it is a valid CNPJ
if !utils.IsValid(cnpj) { // if !utils.IsValid(cnpj) {
utils.SendTestEmail(email, name, "Foi informado um CNPJ inválido") // utils.SendTestEmail(email, name, "Foi informado um CNPJ inválido")
return c.SendString("CNPJ Inválido") // return c.SendString("CNPJ Inválido")
} // }
// Formats the CNPJ // // Formats the CNPJ
cnpjf := fmt.Sprintf("%s.%s.%s/%s-%s", // cnpjf := fmt.Sprintf("%s.%s.%s/%s-%s",
cnpj[:2], // cnpj[:2],
cnpj[2:5], // cnpj[2:5],
cnpj[5:8], // cnpj[5:8],
cnpj[8:12], // cnpj[8:12],
cnpj[12:]) // cnpj[12:])
// Let's see if it is a real 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) // log.Printf("CNPJ %s [%s] requisitou um teste usando o email %s (%s)\n", cnpj, cnpjf, name, email)
empresa := utils.GetEmpresa(cnpj) // empresa := utils.GetEmpresa(cnpj)
if empresa.Situacao != "ATIVA" { // if empresa.Situacao != "ATIVA" {
utils.SendTestEmail(email, name, "Foi informado um CNPJ pertencente à uma empresa inativa") // utils.SendTestEmail(email, name, "Foi informado um CNPJ pertencente à uma empresa inativa")
return c.SendString("Empresa inativa") // return c.SendString("Empresa inativa")
} // }
// Let's see if its already on database // // Let's see if its already on database
customer := services.GetCustomerByCNPJ(cnpjf) // customer := services.GetCustomerByCNPJ(cnpjf)
user := services.GetUserByEmail(email) // user := services.GetUserByEmail(email)
var userdb models.SystemUser // var userdb models.SystemUser
var customerdb models.Customer // var customerdb models.Customer
if user.ID == 0 { // if user.ID == 0 {
// Email not in database. Let's insert it // // Email not in database. Let's insert it
userdb = models.SystemUser{ // userdb = models.SystemUser{
Email: email, // Email: email,
} // }
err := globals.DB.Create(&userdb) // err := globals.DB.Create(&userdb)
if err != nil { // if err != nil {
log.Printf("Cannot create test user: %v\n", err) // log.Printf("Cannot create test user: %v\n", err)
} // }
user.ID = userdb.ID // user.ID = userdb.ID
} // }
if customer.ID == 0 { // if customer.ID == 0 {
// Inexistent customer; insert it into database // // Inexistent customer; insert it into database
customerwww := utils.GetEmpresa(cnpj) // customerwww := utils.GetEmpresa(cnpj)
customerdb = models.Customer{ // customerdb = models.Customer{
CNPJ: customerwww.CNPJ, // CNPJ: customerwww.CNPJ,
Nome: customerwww.Nome, // Nome: customerwww.Nome,
NomeFantasia: customerwww.Nome, // NomeFantasia: customerwww.Nome,
Tipo: customerwww.Tipo, // Tipo: customerwww.Tipo,
Porte: customerwww.Porte, // Porte: customerwww.Porte,
Situacao: customerwww.Situacao, // Situacao: customerwww.Situacao,
Abertura: customerwww.Abertura, // Abertura: customerwww.Abertura,
NaturezaJuridica: customerwww.NaturezaJuridica, // NaturezaJuridica: customerwww.NaturezaJuridica,
Logradouro: customerwww.Logradouro, // Logradouro: customerwww.Logradouro,
Numero: customerwww.Numero, // Numero: customerwww.Numero,
Complemento: customerwww.Complemento, // Complemento: customerwww.Complemento,
Municipio: customerwww.Municipio, // Municipio: customerwww.Municipio,
Bairro: customerwww.Bairro, // Bairro: customerwww.Bairro,
UF: customerwww.UF, // UF: customerwww.UF,
CEP: customerwww.CEP, // CEP: customerwww.CEP,
} // }
err := globals.DB.Create(&customerdb) // err := globals.DB.Create(&customerdb)
if err.Error != nil { // if err.Error != nil {
log.Printf("Cannot create test user: %v\n", err) // log.Printf("Cannot create test user: %v\n", err)
} // }
// Now let's create the customer channel // // Now let's create the customer channel
opts := utils.GenerationOptions{ // opts := utils.GenerationOptions{
Length: 10, // Length: 10,
} // }
tkey, _ := utils.GenerateString(opts) // tkey, _ := utils.GenerateString(opts)
channel := models.Channel{ // channel := models.Channel{
Name: cnpj + "-01", // Name: cnpj + "-01",
TransmissionKey: tkey, // TransmissionKey: tkey,
CustomerID: uint(customerdb.ID), // CustomerID: uint(customerdb.ID),
ServerID: 1, // ServerID: 1,
} // }
err = globals.DB.Create(&channel) // err = globals.DB.Create(&channel)
if err.Error != nil { // if err.Error != nil {
log.Printf("Cannot create test channel: %v\n", err) // log.Printf("Cannot create test channel: %v\n", err)
} // }
// Finally, send an email // // Finally, send an email
utils.SendTestEmailApproval(email, name, tkey, cnpj+"-01") // 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 { func WixIntegration(c *fiber.Ctx) error {
log.Println(string(c.Body())) log.Println(string(c.Body()))

View File

@ -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")
}
}()
}
}

View File

@ -120,13 +120,15 @@ type SystemProgramMethodRole struct {
// ==================================================================== // ====================================================================
// PCast tables // PCast tables
type Customer struct { type Cliente struct {
ID int32 `gorm:"primaryKey;autoIncrement;column:id"` ID int32 `gorm:"primaryKey;autoIncrement;column:id"`
CNPJ string `gorm:"unique;column:cnpj"` CNPJ string `gorm:"unique;column:cnpj"`
NIC string `gorm:"unique;column:nic"`
Nome string `gorm:"not null;column:nome"` Nome string `gorm:"not null;column:nome"`
NomeFantasia string `gorm:"column:nome_fantasia"` 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"` Porte string `gorm:"column:porte"`
Situacao string `gorm:"column:situacao"` Situacao string `gorm:"column:situacao"`
Abertura string `gorm:"column:abertura"` Abertura string `gorm:"column:abertura"`
@ -138,12 +140,10 @@ type Customer struct {
Bairro string `gorm:"column:bairro"` Bairro string `gorm:"column:bairro"`
UF string `gorm:"column:uf"` UF string `gorm:"column:uf"`
CEP string `gorm:"column:cep"` CEP string `gorm:"column:cep"`
CustomerLocal string `gorm:"not null;column:customer_local"` CreatedAt time.Time
CustomerType string `gorm:"not null;column:customer_type"` CreatedBy int
UserFullName string `gorm:"not null;column:userfullname"` UpdatedAt time.Time
UserEmail string `gorm:"not null;column:useremail"` UpdatedBy int
UserName string `gorm:"not null;column:username"`
Password []byte `gorm:"not null;column:password"`
} }
type Email struct { type Email struct {
@ -153,105 +153,108 @@ type Email struct {
} }
// Server represents the servers table in the database // Server represents the servers table in the database
type Server struct { type Servidor struct {
ID uint `gorm:"primaryKey;column:id;autoIncrement"` ID uint `gorm:"primaryKey;column:id;autoIncrement"`
Name string `gorm:"column:name;type:text;not null"` Nome string `gorm:"column:nome;type:text;not null"`
IP string `gorm:"column:ip;type:text;not null"` IP string `gorm:"column:ip;type:text;not null"`
Subdomain string `gorm:"column:subdomain;type:text;not null"` Subdominio string `gorm:"column:subdominio;type:text;not null"`
// Relationship (back-reference) // Relationship (back-reference)
Channels []Channel `gorm:"foreignKey:ServerID"` Canais []Canal `gorm:"foreignKey:ServidorID"`
} }
// TableName overrides the table name // // TableName overrides the table name
func (Server) TableName() string { // func (Server) TableName() string {
return "servers" // return "servers"
} // }
// Plan represents the plans table in the database // // Plan represents the plans table in the database
type Plan struct { // type Plan struct {
ID uint `gorm:"primaryKey;column:id;autoIncrement"` // ID uint `gorm:"primaryKey;column:id;autoIncrement"`
Name string `gorm:"column:name;type:text;not null"` // Name string `gorm:"column:name;type:text;not null"`
DailyLimitTransmission int `gorm:"column:daily_limit_transmission;type:integer;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"` // MonthValue float64 `gorm:"column:month_value;type:numeric(10,2);not null"`
YearValue float64 `gorm:"column:year_value;type:numeric(10,2);not null"` // YearValue float64 `gorm:"column:year_value;type:numeric(10,2);not null"`
// Relationship (back-reference) // // Relationship (back-reference)
Channels []Channel `gorm:"foreignKey:PlanID"` // Channels []Channel `gorm:"foreignKey:PlanID"`
} // }
// TableName overrides the table name // // TableName overrides the table name
func (Plan) TableName() string { // func (Plan) TableName() string {
return "plans" // return "plans"
} // }
// ChannelStat represents the channel_stats table in the database // // ChannelStat represents the channel_stats table in the database
type ChannelStat struct { // type ChannelStat struct {
ID uint `gorm:"primaryKey;column:id;autoIncrement"` // ID uint `gorm:"primaryKey;column:id;autoIncrement"`
Name string `gorm:"column:name;type:text;not null;uniqueIndex"` // Name string `gorm:"column:name;type:text;not null;uniqueIndex"`
Description string `gorm:"column:description;type:text;not null"` // Description string `gorm:"column:description;type:text;not null"`
// Relationship (back-reference) // // Relationship (back-reference)
Channels []Channel `gorm:"foreignKey:ChannelStatID"` // Channels []Channel `gorm:"foreignKey:ChannelStatID"`
} // }
// TableName overrides the table name // // TableName overrides the table name
func (ChannelStat) TableName() string { // func (ChannelStat) TableName() string {
return "channel_stats" // return "channel_stats"
} // }
type Channel struct { type Canal struct {
ID uint `gorm:"primaryKey;column:id;autoIncrement"` ID uint `gorm:"primaryKey;column:id;autoIncrement"`
Name string `gorm:"column:name;type:text;not null;uniqueIndex"` ClienteID uint `gorm:"column:cliente_id;not null"`
TransmissionKey string `gorm:"column:transmission_key;type:text;not null;uniqueIndex"` ServidorID uint `gorm:"column:servidor_id;not null"`
DateLimit time.Time `gorm:"column:date_limit;type:date;not null"` Nome string `gorm:"column:nome;type:text;not null;uniqueIndex"`
CustomerID uint `gorm:"column:customer_id;not null"` Chave string `gorm:"column:chave;type:text;not null;uniqueIndex"`
ServerID uint `gorm:"column:server_id;not null"` LimiteDiario int `gorm:"column:limite_diario;not null"`
PlanID uint `gorm:"column:plan_id;not null"` Validade time.Time `gorm:"column:validade;type:date;not null"`
Status string `gorm:"column:status;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 // Define relationships
Customer Customer `gorm:"foreignKey:CustomerID;references:ID"` Cliente Cliente `gorm:"foreignKey:ClienteID;references:ID"`
Server Server `gorm:"foreignKey:ServerID;references:ID"` Servidor Servidor `gorm:"foreignKey:ServidorID;references:ID"`
Plan Plan `gorm:"foreignKey:PlanID;references:ID"`
} }
// TableName overrides the table name // // TableName overrides the table name
func (Channel) TableName() string { // func (Channel) TableName() string {
return "channels" // return "channels"
} // }
// TransmissionLog represents the transmissionlog table in the database // // TransmissionLog represents the transmissionlog table in the database
type TransmissionLog struct { // type TransmissionLog struct {
ID uint `gorm:"primaryKey;column:id;autoIncrement"` // ID uint `gorm:"primaryKey;column:id;autoIncrement"`
Datetime time.Time `gorm:"column:datetime;type:timestamp;not null"` // Datetime time.Time `gorm:"column:datetime;type:timestamp;not null"`
Channel string `gorm:"column:channel;type:text;not null"` // Channel string `gorm:"column:channel;type:text;not null"`
Message string `gorm:"column:message;type:text;not null"` // Message string `gorm:"column:message;type:text;not null"`
} // }
// TableName overrides the table name // // TableName overrides the table name
func (TransmissionLog) TableName() string { // func (TransmissionLog) TableName() string {
return "transmissionlog" // return "transmissionlog"
} // }
// Available on RAM during the execution // Available on RAM during the execution
// CurrentTransmission represents the transmissions table in the database // CurrentTransmission represents the transmissions table in the database
type CurrentTransmission struct { type CurrentTransmission struct {
ID uint `gorm:"primaryKey;column:id;autoIncrement"` ID uint `gorm:"primaryKey;column:id;autoIncrement"`
Channel string `gorm:"column:channel;type:text;not null"` Canal string `gorm:"column:canal;type:text;not null"`
CustomerID uint `gorm:"column:customer_id;not null"` Inicio time.Time `gorm:"column:inicio;type:timestamp;not null"`
StartTime time.Time `gorm:"column:starttime;type:timestamp;not null"` Duracao int `gorm:"column:duracao;not null"`
Duration int `gorm:"column:duration;not null"` Assistentes int `gorm:"column:assistentes;not null"`
Limit time.Time `gorm:"-"` Desktop int `gorm:"column:desktop;not null"`
SessionID string `gorm:"-"` Mobile int `gorm:"column:mobile;not null"`
PlayerKey string `gorm:"-"` Mensagem string `gorm:"column:mensagem;type:text;not null"`
PlanDailyLimit int `gorm:"-"` Ativa string `gorm:"column:ativa;type:char(1);not null"`
Watchers int `gorm:"column:watchers;not null"` SessionID string `gorm:"-"`
Desktop int `gorm:"column:desktop;not null"` Chave string `gorm:"-"`
Mobile int `gorm:"column:mobile;not null"` Limite time.Time `gorm:"-"`
LimiteDiario int `gorm:"-"`
} }
// TableName overrides the table name // TableName overrides the table name
func (CurrentTransmission) TableName() string { func (CurrentTransmission) TableName() string {
return "transmissions" return "transmissao"
} }

View File

@ -10,7 +10,7 @@ import (
func Setup(app *fiber.App) { func Setup(app *fiber.App) {
app.Post("/integration", controllers.WixIntegration) app.Post("/integration", controllers.WixIntegration)
app.Post("/test", controllers.WixTest) // app.Post("/test", controllers.WixTest)
app.Get("/version", controllers.Version) app.Get("/version", controllers.Version)
@ -19,9 +19,9 @@ func Setup(app *fiber.App) {
app.Get("/users", controllers.GetUsers) app.Get("/users", controllers.GetUsers)
app.Get("/groups", controllers.GetGroups) 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 // Webhooks
app.Post("/on_server_start", controllers.ServerStart) app.Post("/on_server_start", controllers.ServerStart)

View File

@ -11,15 +11,15 @@ func VerifyTransmissionsLimits() {
// log.Println("Verificando") // log.Println("Verificando")
for channelname, currentTransmission := range globals.Transmissions { for channelname, currentTransmission := range globals.Transmissions {
// If the channel has no daily transmission limit, skip the verification (Channels with 24 hours daily limit) // 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 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) // TODO: Implementar verificação de limite de transmissão diária (ou seja, quanto já foi transmitido HOJE)
if time.Now().After(currentTransmission.Limit) { if time.Now().After(currentTransmission.Limite) {
AddTransmissionlog(channelname, "Limite de transmissão diária atingido") // AddTransmissionlog(channelname, "Limite de transmissão diária atingido")
utils.KickSession(channelname, currentTransmission.SessionID) utils.KickSession(channelname, currentTransmission.SessionID)
} }
} }
@ -27,48 +27,45 @@ func VerifyTransmissionsLimits() {
func VerifyTransmissionAuthorization(channelname, sessionid, transmissionkey, playerKey string) (bool, models.CurrentTransmission) { func VerifyTransmissionAuthorization(channelname, sessionid, transmissionkey, playerKey string) (bool, models.CurrentTransmission) {
var ( var (
channel models.Channel channel models.Canal
plan models.Plan
currentTransmission models.CurrentTransmission currentTransmission models.CurrentTransmission
) )
globals.DB.Where("name = ?", channelname).First(&channel) globals.DB.Where("nome = ?", channelname).First(&channel)
globals.DB.First(&plan, channel.PlanID)
currentTransmission.Channel = channel.Name currentTransmission.Canal = channel.Nome
currentTransmission.CustomerID = channel.CustomerID
currentTransmission.SessionID = sessionid currentTransmission.SessionID = sessionid
currentTransmission.PlayerKey = playerKey currentTransmission.Chave = transmissionkey
currentTransmission.PlanDailyLimit = plan.DailyLimitTransmission currentTransmission.LimiteDiario = channel.LimiteDiario
currentTransmission.StartTime = time.Now() 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 the channel is not found, kick the session
if channel.ID == 0 { if channel.ID == 0 {
AddTransmissionlog(channelname, "Canal inexistente") // AddTransmissionlog(channelname, "Canal inexistente")
utils.KickSession(channelname, sessionid) utils.KickSession(channelname, sessionid)
return false, currentTransmission return false, currentTransmission
} }
// If the channel expiration date is reached, kick the session // If the channel expiration date is reached, kick the session
if time.Now().After(channel.DateLimit) { if time.Now().After(channel.Validade) {
AddTransmissionlog(channelname, "Canal com data de expiração vencida") // AddTransmissionlog(channelname, "Canal com data de expiração vencida")
utils.KickSession(channelname, sessionid) utils.KickSession(channelname, sessionid)
return false, currentTransmission return false, currentTransmission
} }
// If the channel is not active, kick the session // // If the channel is not active, kick the session
if channel.Status != "A" { // if channel.Status != "A" {
AddTransmissionlog(channelname, "Canal não está ativo") // AddTransmissionlog(channelname, "Canal não está ativo")
utils.KickSession(channelname, sessionid) // utils.KickSession(channelname, sessionid)
return false, currentTransmission // return false, currentTransmission
} // }
// If the transmission key does not match, kick the session // If the transmission key does not match, kick the session
if transmissionkey != channel.TransmissionKey { if transmissionkey != channel.Chave {
AddTransmissionlog(channelname, "Transmissão com chave de transmissão errada") // AddTransmissionlog(channelname, "Transmissão com chave de transmissão errada")
utils.KickSession(channelname, sessionid) utils.KickSession(channelname, sessionid)
return false, currentTransmission return false, currentTransmission
} }

View File

@ -1,22 +1,15 @@
package services package services
import ( // func AddTransmissionlog(channelname, message string) {
"api/globals" // var tlog models.TransmissionLog
"api/models"
"log"
"time"
)
func AddTransmissionlog(channelname, message string) { // tlog.Channel = channelname
var tlog models.TransmissionLog // tlog.Message = message
// tlog.Datetime = time.Now()
tlog.Channel = channelname // result := globals.DB.Create(&tlog)
tlog.Message = message
tlog.Datetime = time.Now()
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) // }
}
}

View File

@ -1,38 +1,30 @@
package services package services
import ( // var jwtSecret = []byte("your_secret_key") // Replace with your actual secret
"api/globals"
"api/models"
"time"
"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 { // return user
var user models.SystemUser // }
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 { // return user
var user models.Customer // }
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 // token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
} // return token.SignedString(jwtSecret)
// }
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)
}