apifiber/controllers/webhookController.go

341 lines
9.1 KiB
Go

package controllers
import (
"api/globals"
"api/models"
"api/services"
"api/utils"
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
"github.com/gofiber/fiber/v2"
)
func KickSession(stream_name, session_id string) {
url := "http://localhost:8083/api/ctrl/kick_session"
values := map[string]string{"stream_name": stream_name, "session_id": session_id}
jsonValue, err := json.Marshal(values)
if err != nil {
log.Printf("Error Marshall KickSession: %s\n", err)
}
resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonValue))
if err != nil {
log.Printf("Error Post KickSession: %s\n", err)
}
log.Printf("KickSession status code: %d\n", resp.StatusCode)
}
func ServerStart(c *fiber.Ctx) error {
// Creates a server struct
s := new(models.LalServer)
// Parse the body of the request to the server struct
if err := c.BodyParser(s); err != nil {
log.Printf("Error Start: %s\n", err)
return err
}
log.Printf("Server started")
// Marshal the server struct to JSON
utils.PrettyPrintJson(s)
return c.SendString("Server started: " + string(c.Body()))
}
func OnRtmpConnect(c *fiber.Ctx) error {
body := new(models.Connect)
if err := c.BodyParser(body); err != nil {
log.Printf("Error Start: %s\n", err)
return err
}
utils.PrettyPrintJson(body)
return c.SendString("On_Rtmp_Connect: " + 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 {
p := new(models.Update)
if err := c.BodyParser(p); err != nil {
log.Printf("Error SubStart: %s\n", err)
return err
}
log.Printf("SubStart")
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_Substart: " + string(c.Body()))
}
func OnPubStart(c *fiber.Ctx) error {
// ================================================================
// Called when a publisher starts streaming - Start of Transmission
// ================================================================
p := new(models.Pub)
if err := c.BodyParser(p); err != nil {
log.Printf("Error PubStart: %s\n", err)
return err
}
// Parse the URL parameters, in ordere to get the transmission key and the player key
transmissionkey, playerkey := utils.ParseTransmissionString(p.UrlParam)
log.Printf("======================== Start StreamName %s, Transmission Key %s, PlayerKey %s, SessionId %s\n", p.StreamName, transmissionkey, playerkey, p.SessionId)
// Get the channel from the database
channel := services.GetChannelByName(p.StreamName)
log.Printf("======================== %v\n", channel)
// If the channel is not found, kick the session
if channel.ID == 0 {
services.AddTransmissionlog(p.StreamName, "Canal inexistente")
KickSession(p.StreamName, p.SessionId)
return fiber.ErrForbidden
}
// If the channel is not active, kick the session
if channel.Status != "A" {
services.AddTransmissionlog(p.StreamName, "Canal não está ativo")
KickSession(p.StreamName, p.SessionId)
return fiber.ErrForbidden
}
// If the transmission key does not match, kick the session
if transmissionkey != channel.TransmissionKey {
services.AddTransmissionlog(p.StreamName, "Transmissão com chave de transmissão errada")
KickSession(p.StreamName, p.SessionId)
return fiber.ErrForbidden
}
// Check if the channel has authorized time to transmit
// KickSession(p.StreamName, p.SessionId)
// return fiber.ErrForbidden
services.AddTransmissionlog(p.StreamName, "Transmissão iniciada")
return c.SendString("On_Pub_Start: " + string(c.Body()))
}
func OnPubStop(c *fiber.Ctx) error {
// =============================================================
// Called when a publisher stops streaming - End of Transmission
// =============================================================
p := new(models.Pub)
if err := c.BodyParser(p); err != nil {
return err
}
log.Printf("======================== Stop Channel %s\n", p.StreamName)
return c.SendString("On_Pub_Stop: " + string(c.Body()))
}
type ResponseTest struct {
Data DataTest `json:"data"`
}
type DataTest struct {
CNPJ string `json:"cnpj"`
Email string `json:"email"`
Name string `json:"name"`
}
func WixTest(c *fiber.Ctx) error {
// 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)
// 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:])
// 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")
}
// Let's see if its already on database
customer := services.GetCustomerByCNPJ(cnpjf)
user := services.GetUserByEmail(email)
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,
}
err := globals.DB.Create(&userdb)
if err != nil {
log.Printf("Cannot create test user: %v\n", err)
}
user.ID = userdb.ID
}
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,
UserID: user.ID,
}
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,
}
tkey, _ := utils.GenerateString(opts)
channel := models.Channel{
Name: cnpj + "-01",
TransmissionKey: tkey,
CustomerID: uint(customerdb.UserID),
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")
}
return c.SendString("On Test: " + empresa.Nome)
}
func WixIntegration(c *fiber.Ctx) error {
log.Println(string(c.Body()))
return c.SendString("On Integration: " + string(c.Body()))
// var data models.Purchase
// if err := c.BodyParser(&data); err != nil {
// return fiber.ErrBadRequest
// }
// fmt.Println(data.Data.Contact.Email)
// fmt.Println(data.Data.Contact.Name.First + " " + data.Data.Contact.Name.Last)
// fmt.Printf("%s", data.Data.PlanOrderID)
// fmt.Println(data.Data.PlanPrice.Value)
// fmt.Println(data.Data.PlanStartDate)
// fmt.Println(data.Data.PlanValidUntil)
// fmt.Println(data.Data.PlanTitle)
// var user models.SystemUser
// result := database.DB.Debug().Where("email = ?", data.Data.Contact.Email).First(&user)
// if result.RowsAffected == 0 {
// // User does not exist. Inserts it.
// user := models.User{
// Email: data.Data.Contact.Email,
// Name: data.Data.Contact.Name.First + " " + data.Data.Contact.Name.Last,
// Blocked: "N",
// Cancelled: "N",
// }
// database.DB.Debug().Create(&user)
// }
// value, err := strconv.ParseFloat(data.Data.PlanPrice.Value, 32)
// if err != nil {
// log.Printf("Error converting plan price: %s\n", err)
// return fiber.ErrBadRequest
// }
// transaction := models.Transaction{
// Email: data.Data.Contact.Email,
// PlanOrderID: data.Data.PlanOrderID,
// Value: value,
// PlanStartDate: data.Data.PlanStartDate,
// PlanValidUntil: data.Data.PlanValidUntil,
// PlanTitle: data.Data.PlanTitle,
// Operation: "Compra",
// Obs: "",
// }
// database.DB.Debug().Create(&transaction)
// return c.JSON(transaction)
}