<%@ WebHandler Language="VB" Class="SIGGPS" %> 'Option Explicit On 'Option Strict On 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 ObjGPS.ObtenerNotificaciones() End Using context.Response.Write(Retorno) 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($"
") SBuilder.Append($"
{Header}
") SBuilder.Append($"
") Try SBuilder.Append($"") SBuilder.Append($"") If row.Table.Columns.Contains("Combustible") Then SBuilder.Append($"") End If If row("SPD").ToString <> "-1" Then SBuilder.Append($"") End If If ExtraBody <> "" AndAlso ExtraBody <> "-1" Then SBuilder.Append(ExtraBody) End If 'If PermisoComandos Then 'SBuilder.Append($"") SBuilder.AppendFormat("", row("Lat").ToString, row("Lng").ToString) 'End If Catch ex As Exception End Try SBuilder.Append($"
Fecha : {row("FechaTrama")}
Conductor : {row("Conductor").ToString}
Combustible : {IfNull(row("Combustible"), "NO DISPONIBLE", $"{row("Combustible").ToString.FormatoNumero} lts").ToString}
Velocidad : {row("SPD").ToString} KM/H
Comandos
Ver en google maps
") 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(" ") strBody.Append(" ") strBody.Append(" ") strBody.Append(" ") strBody.Append(" ") strBody.Append("
") strBody.Append(" ") strBody.Append("
") strBody.Append("
") strBody.Append("
Datos del Trayecto") strBody.Append("") strBody.Append("") strBody.Append("") strBody.Append("") strBody.AppendFormat("", Row("Trayecto")) strBody.Append("") strBody.Append("") strBody.Append("") strBody.AppendFormat("", Row("Vehiculo")) strBody.Append("") strBody.Append("") strBody.Append("") strBody.AppendFormat("", Row("Estatus")) strBody.Append("") strBody.Append("") strBody.Append("") strBody.Append("") strBody.AppendFormat("", Row("LatitudActual")) strBody.Append("") strBody.Append("") strBody.Append("") strBody.AppendFormat("", Row("LongitudActual")) strBody.Append("") strBody.Append("") strBody.Append("") strBody.AppendFormat("", Row("LatitudActual"), Row("LongitudActual")) strBody.Append("") If EnviarLiga Then strBody.Append("") strBody.Append("") strBody.AppendFormat("", Encripta($"CveTrayecto={Row("CveTrayecto").ToString()}")) strBody.Append("") End If strBody.Append("") strBody.AppendFormat("", Row("Liga")) strBody.Append("") strBody.Append("") strBody.Append("
 Trayecto: {0}
 Vehículo: {0}strong>
 Estatus: {0}
 Latitud: {0}
 Longitud: {0}
 Posición: Ver en google maps
 Rastreo: Rastrear Vehículo
") strBody.Append("
") strBody.Append("
") strBody.Append(" ") strBody.Append("
") strBody.Append("
") strBody.Append("") Catch ex As Exception OnError("Ocurrio un error al general el correo.", ex) End Try Return strBody.ToString() End Function #End Region End Class