Files
SIG/Ashx/SIGGPS.ashx
2023-08-23 00:04:25 -07:00

397 lines
20 KiB
Plaintext

<%@ WebHandler Language="VB" Class="SIGGPS" %>
'Option Explicit On
Option Strict Off
Imports System
Imports System.Web
Imports System.Data
Imports Newtonsoft.Json.Linq
Imports Extensiones
Imports System.IO
Imports Microsoft.AspNet.SignalR
Public Class SIGGPS : Implements IHttpHandler, IRequiresSessionState
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "text/plain"
Try
If context.Request("metodo") IsNot Nothing Then
Select Case context.Request("metodo")
Case "getimginstalacion"
GetImgInstalacion(context)
Case "EjecutarNotificaciones"
EjecutarNotificaciones(context)
Case "EjecutaTrayectos"
EnviarCorreoTrayectos(context, context.Request("CveTrayecto").ToString().ToEntero())
End Select
ElseIf context.Request.InputStream IsNot Nothing Then
Using reader As New StreamReader(context.Request.InputStream)
Dim json = reader.ReadToEnd
Dim JsonRequest As JObject = JObject.Parse(json)
If JsonRequest IsNot Nothing Then
Select Case JsonRequest("Metodo").ToString
Case "UpdateNotificacion"
UpdateNotificacion(context, JsonRequest)
Case "RastreoContinuoAF"
RastreoContinuoAF(context, JsonRequest)
End Select
End If
End Using
End If
Catch ex As Exception
ex.GuardaLog(ex.Message)
End Try
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
ReadOnly Property UsuarioActual(ByVal context As HttpContext) As Usuario
Get
UsuarioActual = DirectCast(context.Session("UsuarioSIG"), Usuario)
End Get
End Property
Private Function Parametros(Cadena As String) As Hashtable
Dim P1() As String = Cadena.Split("&"c)
Dim Tmp As String
Dim P2() As String
Dim URLParametros As New Hashtable
For Each Tmp In P1
P2 = Tmp.Replace("%26%", "&").Split("="c)
URLParametros.Add(P2(0).ToString.ToUpper, P2(1))
Next
Return URLParametros
End Function
Private Sub EjecutarNotificaciones(ByVal context As HttpContext)
Dim Retorno As String = "[]"
'Dim contextc = Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext(Of MyGPSHub)()
'SendNotificacionGPS(contextc, 5, 1727, "Encabezado", "Mensaje", 2, "{""timeOut"":15000, ""extendedTimeOut"":16000}", "142608__autistic-lucario__error.wav", 0, SQLToGmapsJArray("POINT (-99.211688 19.717715)", "POINT").ToString())
Using ObjGPS As New ClsSisNotificaciones
Retorno = $"[""IsOk""=""{ObjGPS.ObtenerNotificaciones()}""]"
End Using
context.Response.ContentType = "text/json"
context.Response.StatusCode = 200
context.Response.Write(Retorno)
context.Response.Flush()
context.Response.Close()
context.Response.End()
End Sub
Public Sub SendNotificacionGPS(context As Microsoft.AspNet.SignalR.IHubContext, CveNotificacionBitacora As Integer, CveUsuario As Integer, Encabezado As String, Mensaje As String, TipoNotificacion As Integer, Pie As String, Sonido As String, Persistencia As Boolean, Coords As String)
context.Clients.All.addLatestNotification(Mensaje, CveUsuario, Encabezado, TipoNotificacion, Pie, Sonido, CveNotificacionBitacora, Persistencia, Coords)
End Sub
Private Sub GetImgInstalacion(ByVal context As HttpContext)
Dim params As String = Decripta(context.Request("r").ToString)
Dim Parametros = Me.Parametros(params)
Dim Archivo As String = Parametros("ARCHIVO").ToString()
Dim CveDispositivo As Integer = Parametros("CVEDISPOSITIVO").ToString().ToEntero()
Dim Extension As String = Path.GetExtension(Archivo).Replace(".", "")
Dim Usuario As Usuario = UsuarioActual(context)
If Not IsNothing(Usuario) Then
Dim Url = String.Format("{0}\Empresas\{1}\Dispositivos\{2}\Imagenes\{3}", ModExtensiones.DirectorioBaseEmpresas, Usuario.CveEmpresa, CveDispositivo, Archivo)
If File.Exists(Url) Then
context.Response.ContentType = String.Format("image/{0}", Extension)
context.Response.Flush()
context.Response.WriteFile(Url)
context.Response.End()
End If
End If
End Sub
Private Sub UpdateNotificacion(ByVal context As HttpContext, ByVal Json As JObject)
Dim CveBitacora As Integer = Json("Params")("CveBitacora").ToEntero
Dim CveUsuario As Integer = Json("Params")("Cve").ToEntero
Dim Notificaciones As New StringBuilder
Dim countNotificaciones = 0
If CveUsuario > 0 Then
Using ObjNoti As New ClsSisNotificaciones
If CveBitacora > 0 Then
ObjNoti.UpdateNotificacionesCampanaNotifico(CveBitacora, 1)
End If
ObjNoti.GetNotificacionesCampanaPendientes(CveUsuario)
For Each row As DataRow In ObjNoti.DtResultados.Rows
countNotificaciones += row("NumNotificaciones").ToString.ToEntero
Dim TipoMensaje = If(row("TipoMensaje").ToString = "EMG", $"Hay {row("NumNotificaciones")} notificaciones de Emergencia", $"Hay {row("NumNotificaciones")} notificaciones de Alerta")
Dim Icono = If(row("TipoMensaje").ToString = "EMG", "fa fa-exclamation-triangle", "fa fa-bullhorn")
Dim Tipo = If(row("TipoMensaje").ToString = "EMG", "danger", "warning")
Notificaciones.Append(ItemNotificaciones(TipoMensaje, "Hoy", Icono, Tipo, $"/GPS/Notificaciones.aspx?Tipo={row("TipoMensaje")}"))
Next
End Using
End If
Dim Retorno As New JObject(
New JProperty("Titulo", $"({countNotificaciones}) SIG GPS"),
New JProperty("NumNotificaciones", countNotificaciones),
New JProperty("CssClass", If(countNotificaciones > 0, "badge-danger", "badge-default")),
New JProperty("Html", Notificaciones.ToString())
)
context.Response.Write(Retorno.ToString())
End Sub
Private Sub RastreoContinuoAF(ByVal context As HttpContext, ByVal Json As JObject)
Dim CveDispositivo As Integer = Json("Params")("CveDispositivo").ToEntero
Dim CveCliente As Integer = Json("Params")("CveCliente").ToEntero
Dim FechaCliente As DateTime = Json("Params")("FechaCliente").ToDateTime
Dim PoscionesAnteriores As JArray = JArray.Parse(Json("Params")("Posiciones").ToString())
Dim CoordActual As JObject = Nothing
Dim SBJS As New StringBuilder
Dim ObjGPS As New ClsGPS
Try
Dim Fecha = "", Vehiculo = "", Icono = "", Info As String = ""
If ObjGPS.UltimaPosicionEquipoGet(String.Format("{0};", CveDispositivo), CveCliente) Then
If ObjGPS.DtResultados.Rows.Count > 0 Then
For Each Row As DataRow In ObjGPS.DtResultados.Rows
CoordActual = JObject.Parse(SQLToGmapsJArray(Row("Posicion").ToString, "POINT")(0).ToString())
Fecha = Row("FechaTrama").ToString
Vehiculo = Row("Vehiculo").ToString
Info = InfoWindowCombustible(String.Format(" Vehículo: {0}", Vehiculo), "", CveDispositivo, Row, False)
Dim Diferencia As Long = DateDiff(DateInterval.Minute, Fecha.ToDateTime(), FechaCliente)
If Diferencia >= 30 AndAlso Diferencia < 120 Then
Icono = "/Imagenes/rsz_11rsz_car_disconnected.png"
ElseIf Diferencia >= 120 Then
Icono = "/Imagenes/rsz_11rsz_car_disable.png"
Else
If Row("SPD").ToString.ToDouble > 1 Then
Icono = String.Format("/Imagenes/{0}green.png", Row("Icono").ToString)
Else
Icono = String.Format("/Imagenes/{0}.png", Row("Icono").ToString)
End If
End If
PoscionesAnteriores.Add(CoordActual)
SBJS.AppendFormat("creaPolylineRastreo({0},'#4B77BE','{1}',{2},'{3}','{4}',{5}, 1); DeleteMarkersRastreo();", PoscionesAnteriores.ToString(), Info, CoordActual.ToString(), Vehiculo, Icono, CveDispositivo)
Next
End If
End If
Catch ex As Exception
GuardaLog(ex.ToString())
Finally
ObjGPS.Dispose()
End Try
Dim Retorno As New JObject(
New JProperty("CoordActual", CoordActual),
New JProperty("JS", SBJS.ToString())
)
context.Response.Write(Retorno.ToString())
End Sub
Public Function InfoWindowCombustible(Header As String, ExtraBody As String, CveDispositivo As Integer, row As DataRow, Optional PermisoComandos As Boolean = True) As String
Dim SBuilder As New StringBuilder
SBuilder.Clear()
SBuilder.Append($"<div>")
SBuilder.Append($"<div><h5><b>{Header}</b></h5></div>")
SBuilder.Append($"<div><table>")
Try
SBuilder.Append($"<tr><td>Fecha : {row("FechaTrama")} </td></tr>")
SBuilder.Append($"<tr><td>Conductor : {row("Conductor").ToString}</td></tr>")
If row.Table.Columns.Contains("Combustible") Then
SBuilder.Append($"<tr><td>Combustible : {IfNull(row("Combustible"), "NO DISPONIBLE", $"{row("Combustible").ToString.FormatoNumero} lts").ToString}</td></tr>")
End If
If row("SPD").ToString <> "-1" Then
SBuilder.Append($"<tr><td>Velocidad : {row("SPD").ToString} KM/H </td></tr>")
End If
If ExtraBody <> "" AndAlso ExtraBody <> "-1" Then
SBuilder.Append(ExtraBody)
End If
'If PermisoComandos Then
'SBuilder.Append($"<tr><td><a href=""javascript:;"" onclick=""CargaComandos(\'{row("Vehiculo").ToString}\',{CveDispositivo});"">Comandos</a></td></tr>")
SBuilder.AppendFormat("<tr><td><a target=\'_blank\' href=\'https://www.google.com/maps/search/{0},{1}/\'>Ver en google maps</a></td></tr>", row("Lat").ToString, row("Lng").ToString)
'End If
Catch ex As Exception
End Try
SBuilder.Append($"</table></div><div></div></div>")
Return SBuilder.ToString
End Function
Private Function SQLToGmapsJArray(CoordsSQL As String, Tipo As String) As JArray
Dim CoordsPoligono As String = CoordsSQL.Replace($"{Tipo}", "").Replace(")", "").Replace("(", "")
Dim CoordsPuntos() As String = CoordsPoligono.Split(","c)
Dim Json As New JArray(From coord In CoordsPuntos
Let c = coord.Trim.Split(" "c)
Select New JObject(
New JProperty("lat", c(1).ToDouble),
New JProperty("lng", c(0).ToDouble)
)
)
Return Json
End Function
#Region "N O T F I C A C I O N - T R A Y E C T O S"
Private Sub EnviarCorreoTrayectos(ByVal context As HttpContext, CveTrayecto As Integer)
Dim Retorno As JObject = New JObject(New JProperty("EnvioCorreo", False), New JProperty("Mensaje", ""))
Try
Dim DtInfoTrayecto As DataTable = Nothing
Dim DtTrayecto As DataTable = Nothing
Using ObjGPS As New ClsGPS
If ObjGPS.GetTrayectos(CveTrayecto, -1, -1) AndAlso ObjGPS.DtResultados.Rows.Count > 0 Then
DtTrayecto = ObjGPS.DtResultados.Copy()
End If
If ObjGPS.GetTrayectosDatos(CveTrayecto) Then
DtInfoTrayecto = ObjGPS.DtSetResultados.Tables(0).Copy()
End If
End Using
If DtTrayecto IsNot Nothing AndAlso DtInfoTrayecto IsNot Nothing AndAlso DtInfoTrayecto.Rows.Count > 0 Then
Dim RowTrayecto As DataRow = DtTrayecto.Rows(0)
Dim RowInfo As DataRow = DtInfoTrayecto.Rows(0)
Dim EnviarLiga As Boolean = CBool(RowTrayecto("EnviarLiga").ToString())
Dim Asunto As String = "Estatus de Trayecto"
Dim Cuerpo As String = GeneraCorreo(CveTrayecto, EnviarLiga, RowInfo)
Dim Correos As String = RowTrayecto("CorreosNotificacion").ToString()
Dim ObjMail As New ClsSisMail
If ObjMail.SendMail(ClsPaginas.EmpresaNotificaciones, Correos, Asunto, Cuerpo) Then
Retorno("EnvioCorreo") = True
Retorno("Mensaje") = "El correo fue enviado correctamente"
Else
Retorno("EnvioCorreo") = False
Retorno("Mensaje") = "Ocurrió un error al enviar el correo"
End If
End If
Catch ex As Exception
OnError("Ocurrió un error al enviar el correo", ex)
End Try
context.Response.Write(Retorno.ToString())
End Sub
Protected Function GeneraCorreo(CveTrayecto As Integer, EnviarLiga As Boolean, Row As DataRow) As String
Dim strBody As New StringBuilder
Try
strBody.Append("<html xmlns=""http://www.w3.org/1999/xhtml""> ")
strBody.Append("<head> ")
strBody.Append(" <style type=""text/css""> ")
strBody.Append(" body ")
strBody.Append(" { ")
strBody.Append(" margin:0px; ")
strBody.Append(" padding:0px 0px 0px 0px; ")
strBody.Append(" font-family: Verdana, Arial, Helvetica, sans-serif; ")
strBody.Append(" font-size: 10px; ")
strBody.Append(" background-color:#F0F0F0; ")
strBody.Append(" } ")
strBody.Append(" a.Texto ")
strBody.Append(" { ")
strBody.Append(" font-size:11px; ")
strBody.Append(" background-color:#F7F6F3; ")
strBody.Append(" text-decoration:none; ")
strBody.Append(" font-weight:bold; ")
strBody.Append(" } ")
strBody.Append(" .Texto ")
strBody.Append(" { ")
strBody.Append(" background-color:#F7F6F3; color:Black; font-family:Verdana; font-size:10px; text-align:center; vertical-align:middle; height:20px;")
strBody.Append(" } ")
strBody.Append(" .TextoAlterno ")
strBody.Append(" { ")
strBody.Append(" background-color:White; color:Black; font-family:Verdana; font-size:10px; text-align:center; ")
strBody.Append(" vertical-align:middle; height:20px;")
strBody.Append(" } ")
strBody.Append(" .BarraIdentidad ")
strBody.Append(" { ")
strBody.Append(" color:#FFFFFF; ")
strBody.Append(" background:#F0F0F0; ")
strBody.Append(" font-weight:bold; ")
strBody.Append(" font-size:19px; ")
strBody.Append(" font-style:oblique; ")
strBody.Append(" } ")
strBody.Append(" .Titulos ")
strBody.Append(" { ")
strBody.Append(" background-color: Gray;")
strBody.Append(" color:White; ")
strBody.Append(" font-family:Verdana; font-size:12px; text-align:center; ")
strBody.Append(" vertical-align:middle; font-weight:bold; height:30px; ")
strBody.Append(" text-decoration:none; ")
strBody.Append(" } ")
strBody.Append(" .Verde {color: #00CC00;} ")
strBody.Append(" .Negro {color: #000000;} ")
strBody.Append(" .Rojo {color: #FF0000;} ")
strBody.Append(" </style> ")
strBody.Append("</head> ")
strBody.Append("<body> ")
strBody.Append(" <h5> ")
strBody.Append(" ")
strBody.Append(" </h5> ")
strBody.Append(" <div id=""C_divOC"" > ")
strBody.Append("<div><fieldset><legend><strong> Datos del Trayecto</strong></legend>")
strBody.Append("<table style=""width: 726.5px;"" border=""0"" cellspacing=""0"" cellpadding=""0"">")
strBody.Append("<tbody>")
strBody.Append("<tr>")
strBody.Append("<td style=""width: 36.5px;"">&nbsp;Trayecto:</td>")
strBody.AppendFormat("<td style=""width: 167px;"" colspan=""3""><strong>&nbsp;{0}</strong></td>", Row("Trayecto"))
strBody.Append("</tr>")
strBody.Append("<tr>")
strBody.Append("<td style=""width: 36.5px;"">&nbsp;Vehículo:</td>")
strBody.AppendFormat("<td style=""width: 167px;"" colspan=""3""><strong>&nbsp;{0}strong></td>", Row("Vehiculo"))
strBody.Append("</tr>")
strBody.Append("<tr>")
strBody.Append("<td style=""width: 36.5px;"">&nbsp;Estatus:</td>")
strBody.AppendFormat("<td style=""width: 167px;"" colspan=""3""><strong>&nbsp;{0}</strong></td>", Row("Estatus"))
strBody.Append("</tr>")
strBody.Append("<tr>")
strBody.Append("<tr>")
strBody.Append("<td style=""width: 36.5px;"">&nbsp;Latitud:</td>")
strBody.AppendFormat("<td style=""width: 167px;"" colspan=""3""><strong>&nbsp;{0}</strong></td>", Row("LatitudActual"))
strBody.Append("</tr>")
strBody.Append("<tr>")
strBody.Append("<td style=""width: 36.5px;"">&nbsp;Longitud:</td>")
strBody.AppendFormat("<td style=""width: 167px;"" colspan=""3""><strong>&nbsp;{0}</strong></td>", Row("LongitudActual"))
strBody.Append("</tr>")
strBody.Append("<tr>")
strBody.Append("<td style=""width: 36.5px;"">&nbsp;Posición:</td>")
strBody.AppendFormat("<td style=""width: 187px;"" colspan=""3""><strong>&nbsp;<a href=""https://www.google.com/maps/search/{0},{1}/\"" target=""_blank"" rel=""noopener"">Ver en google maps</a></strong></td>", Row("LatitudActual"), Row("LongitudActual"))
strBody.Append("</tr>")
If EnviarLiga Then
strBody.Append("<tr>")
strBody.Append("<td style=""width: 36.5px;"">&nbsp;Rastreo:</td>")
strBody.AppendFormat("<td style=""width: 187px;"" colspan=""3""><strong>&nbsp;<a href=""http://gps.signalsgps.com/GPS/RastreoTrayectos.aspx?P={0}"" target=""_blank"" rel=""noopener"">Rastrear Vehículo</a></strong></td>", Encripta($"CveTrayecto={Row("CveTrayecto").ToString()}"))
strBody.Append("</tr>")
End If
strBody.Append("<tr>")
strBody.AppendFormat("<td style=""width: 187px;"" colspan=""3""><img src=""{0}"" /></td>", Row("Liga"))
strBody.Append("</tr>")
strBody.Append("</tbody>")
strBody.Append("</table>")
strBody.Append("</fieldset></div>")
strBody.Append(" <h5> ")
strBody.Append(" ")
strBody.Append(" </h5> ")
strBody.Append(" </div> ")
strBody.Append("</body></html>")
Catch ex As Exception
OnError("Ocurrio un error al general el correo.", ex)
End Try
Return strBody.ToString()
End Function
#End Region
End Class