index int64 | repo_name string | branch_name string | path string | content string | import_graph string |
|---|---|---|---|---|---|
61,061 | CIGAUNAM/SIA | refs/heads/master | /formacion_recursos_humanos/apps.py | from django.apps import AppConfig
class FormacionRecursosHumanosConfig(AppConfig):
name = 'formacion_recursos_humanos'
| {"/apoyo_institucional/models.py": ["/nucleo/models.py"], "/experiencia_laboral/serializers.py": ["/experiencia_laboral/models.py"], "/vinculacion/admin.py": ["/vinculacion/models.py"], "/nucleo/serializers.py": ["/nucleo/models.py", "/formacion_academica/models.py"], "/formacion_academica/serializers.py": ["/formacion_academica/models.py"], "/formacion_recursos_humanos/admin.py": ["/formacion_recursos_humanos/models.py"], "/movilidad_academica/models.py": ["/nucleo/models.py", "/vinculacion/models.py"], "/difusion_cientifica/models.py": ["/nucleo/models.py"], "/experiencia_laboral/views.py": ["/experiencia_laboral/serializers.py"], "/nucleo/views.py": ["/nucleo/models.py", "/nucleo/serializers.py"], "/desarrollo_tecnologico/models.py": ["/nucleo/models.py"], "/formacion_academica/admin.py": ["/formacion_academica/models.py"], "/investigacion/admin.py": ["/investigacion/models.py"], "/difusion_cientifica/admin.py": ["/difusion_cientifica/models.py"], "/investigacion/models.py": ["/nucleo/models.py"], "/formacion_academica/models.py": ["/nucleo/models.py"], "/movilidad_academica/admin.py": ["/movilidad_academica/models.py"], "/geom/envolvente.py": ["/geom/funciones.py"], "/nucleo/admin.py": ["/nucleo/models.py"], "/vinculacion/models.py": ["/nucleo/models.py", "/investigacion/models.py"], "/divulgacion_cientifica/admin.py": ["/divulgacion_cientifica/models.py"], "/experiencia_laboral/models.py": ["/nucleo/models.py"], "/docencia/models.py": ["/nucleo/models.py", "/vinculacion/models.py", "/formacion_academica/models.py"], "/experiencia_laboral/admin.py": ["/experiencia_laboral/models.py"], "/desarrollo_tecnologico/admin.py": ["/desarrollo_tecnologico/models.py"], "/divulgacion_cientifica/models.py": ["/nucleo/models.py"], "/formacion_academica/views.py": ["/formacion_academica/serializers.py"], "/apoyo_institucional/admin.py": ["/apoyo_institucional/models.py"], "/formacion_recursos_humanos/models.py": ["/nucleo/models.py"], "/distinciones/models.py": ["/nucleo/models.py"]} |
61,062 | CIGAUNAM/SIA | refs/heads/master | /formacion_academica/admin.py | from django.contrib import admin
# Register your models here.
from . models import CursoEspecializacion, Licenciatura, \
Maestria, Doctorado, PostDoctorado
admin.site.register(CursoEspecializacion)
admin.site.register(Licenciatura)
admin.site.register(Maestria)
admin.site.register(Doctorado)
admin.site.register(PostDoctorado) | {"/apoyo_institucional/models.py": ["/nucleo/models.py"], "/experiencia_laboral/serializers.py": ["/experiencia_laboral/models.py"], "/vinculacion/admin.py": ["/vinculacion/models.py"], "/nucleo/serializers.py": ["/nucleo/models.py", "/formacion_academica/models.py"], "/formacion_academica/serializers.py": ["/formacion_academica/models.py"], "/formacion_recursos_humanos/admin.py": ["/formacion_recursos_humanos/models.py"], "/movilidad_academica/models.py": ["/nucleo/models.py", "/vinculacion/models.py"], "/difusion_cientifica/models.py": ["/nucleo/models.py"], "/experiencia_laboral/views.py": ["/experiencia_laboral/serializers.py"], "/nucleo/views.py": ["/nucleo/models.py", "/nucleo/serializers.py"], "/desarrollo_tecnologico/models.py": ["/nucleo/models.py"], "/formacion_academica/admin.py": ["/formacion_academica/models.py"], "/investigacion/admin.py": ["/investigacion/models.py"], "/difusion_cientifica/admin.py": ["/difusion_cientifica/models.py"], "/investigacion/models.py": ["/nucleo/models.py"], "/formacion_academica/models.py": ["/nucleo/models.py"], "/movilidad_academica/admin.py": ["/movilidad_academica/models.py"], "/geom/envolvente.py": ["/geom/funciones.py"], "/nucleo/admin.py": ["/nucleo/models.py"], "/vinculacion/models.py": ["/nucleo/models.py", "/investigacion/models.py"], "/divulgacion_cientifica/admin.py": ["/divulgacion_cientifica/models.py"], "/experiencia_laboral/models.py": ["/nucleo/models.py"], "/docencia/models.py": ["/nucleo/models.py", "/vinculacion/models.py", "/formacion_academica/models.py"], "/experiencia_laboral/admin.py": ["/experiencia_laboral/models.py"], "/desarrollo_tecnologico/admin.py": ["/desarrollo_tecnologico/models.py"], "/divulgacion_cientifica/models.py": ["/nucleo/models.py"], "/formacion_academica/views.py": ["/formacion_academica/serializers.py"], "/apoyo_institucional/admin.py": ["/apoyo_institucional/models.py"], "/formacion_recursos_humanos/models.py": ["/nucleo/models.py"], "/distinciones/models.py": ["/nucleo/models.py"]} |
61,063 | CIGAUNAM/SIA | refs/heads/master | /nucleo/urls.py | from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from nucleo import views
urlpatterns = [
url(r'^tags/', views.TagLista.as_view()),
url(r'^rest/tags/$', views.TagList.as_view()),
url(r'^rest/tag/(?P<pk>[0-9]+)/$', views.TagDetail.as_view()),
url(r'^rest/zonas.paises/$', views.ZonaPaisList.as_view()),
url(r'^rest/zona.pais/(?P<pk>[0-9]+)/$', views.ZonaPaisDetail.as_view()),
url(r'^rest/paises/$', views.PaisList.as_view()),
url(r'^rest/pais/(?P<pk>[0-9]+)/$', views.PaisDetail.as_view()),
url(r'^rest/estados/$', views.EstadoList.as_view()),
url(r'^rest/estado/(?P<pk>[0-9]+)/$', views.EstadoDetail.as_view()),
url(r'^rest/ciudades/$', views.CiudadList.as_view()),
url(r'^rest/ciudad/(?P<pk>[0-9]+)/$', views.CiudadDetail.as_view()),
url(r'^rest/users/$', views.UserList.as_view()),
url(r'^rest/user/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),
url(r'^rest/instituciones/$', views.InstitucionList.as_view()),
url(r'^rest/institucion/(?P<pk>[0-9]+)/$', views.InstitucionDetail.as_view()),
url(r'^rest/dependencias/$', views.DependenciaList.as_view()),
url(r'^rest/dependencia/(?P<pk>[0-9]+)/$', views.DependenciaDetail.as_view()),
url(r'^rest/cargos/$', views.CargoList.as_view()),
url(r'^rest/cargo/(?P<pk>[0-9]+)/$', views.CargoDetail.as_view()),
url(r'^rest/nombramientos/$', views.NombramientoList.as_view()),
url(r'^rest/nombramientos/(?P<pk>[0-9]+)/$', views.NombramientoDetail.as_view()),
url(r'^rest/areas.conocimiento/$', views.AreaConocimientoList.as_view()),
url(r'^rest/area.conocimiento/(?P<pk>[0-9]+)/$', views.AreaConocimientoDetail.as_view()),
url(r'^rest/areas.especialidad/$', views.AreaEspecialidadList.as_view()),
url(r'^rest/area.especialidad/(?P<pk>[0-9]+)/$', views.AreaEspecialidadDetail.as_view()),
url(r'^rest/impactos.sociales/$', views.ImpactoSocialList.as_view()),
url(r'^rest/impacto.social/(?P<pk>[0-9]+)/$', views.ImpactoSocialDetail.as_view()),
url(r'^rest/programas.financiamiento/$', views.ProgramaFinanciamientoList.as_view()),
url(r'^rest/programa.financiamiento/(?P<pk>[0-9]+)/$', views.ProgramaFinanciamientoDetail.as_view()),
url(r'^rest/financiamientos/$', views.FinanciamientoList.as_view()),
url(r'^rest/financiamiento/(?P<pk>[0-9]+)/$', views.FinanciamientoDetail.as_view()),
url(r'^rest/metodologias/$', views.MetodologiaList.as_view()),
url(r'^rest/metodologia/(?P<pk>[0-9]+)/$', views.MetodologiaDetail.as_view()),
url(r'^rest/programas.licenciatura/$', views.ProgramaLicenciaturaList.as_view()),
url(r'^rest/programa.licenciatura/(?P<pk>[0-9]+)/$', views.ProgramaLicenciaturaDetail.as_view()),
url(r'^rest/programas.maestria/$', views.ProgramaMaestriaList.as_view()),
url(r'^rest/programa.maestria/(?P<pk>[0-9]+)/$', views.ProgramaMaestriaDetail.as_view()),
url(r'^rest/programas.doctorado/$', views.ProgramaDoctoradoList.as_view()),
url(r'^rest/programa.doctorado/(?P<pk>[0-9]+)/$', views.ProgramaDoctoradoDetail.as_view()),
url(r'^rest/proyectos/$', views.ProyectoList.as_view()),
url(r'^rest/proyecto/(?P<pk>[0-9]+)/$', views.ProyectoDetail.as_view())
]
urlpatterns = format_suffix_patterns(urlpatterns) | {"/apoyo_institucional/models.py": ["/nucleo/models.py"], "/experiencia_laboral/serializers.py": ["/experiencia_laboral/models.py"], "/vinculacion/admin.py": ["/vinculacion/models.py"], "/nucleo/serializers.py": ["/nucleo/models.py", "/formacion_academica/models.py"], "/formacion_academica/serializers.py": ["/formacion_academica/models.py"], "/formacion_recursos_humanos/admin.py": ["/formacion_recursos_humanos/models.py"], "/movilidad_academica/models.py": ["/nucleo/models.py", "/vinculacion/models.py"], "/difusion_cientifica/models.py": ["/nucleo/models.py"], "/experiencia_laboral/views.py": ["/experiencia_laboral/serializers.py"], "/nucleo/views.py": ["/nucleo/models.py", "/nucleo/serializers.py"], "/desarrollo_tecnologico/models.py": ["/nucleo/models.py"], "/formacion_academica/admin.py": ["/formacion_academica/models.py"], "/investigacion/admin.py": ["/investigacion/models.py"], "/difusion_cientifica/admin.py": ["/difusion_cientifica/models.py"], "/investigacion/models.py": ["/nucleo/models.py"], "/formacion_academica/models.py": ["/nucleo/models.py"], "/movilidad_academica/admin.py": ["/movilidad_academica/models.py"], "/geom/envolvente.py": ["/geom/funciones.py"], "/nucleo/admin.py": ["/nucleo/models.py"], "/vinculacion/models.py": ["/nucleo/models.py", "/investigacion/models.py"], "/divulgacion_cientifica/admin.py": ["/divulgacion_cientifica/models.py"], "/experiencia_laboral/models.py": ["/nucleo/models.py"], "/docencia/models.py": ["/nucleo/models.py", "/vinculacion/models.py", "/formacion_academica/models.py"], "/experiencia_laboral/admin.py": ["/experiencia_laboral/models.py"], "/desarrollo_tecnologico/admin.py": ["/desarrollo_tecnologico/models.py"], "/divulgacion_cientifica/models.py": ["/nucleo/models.py"], "/formacion_academica/views.py": ["/formacion_academica/serializers.py"], "/apoyo_institucional/admin.py": ["/apoyo_institucional/models.py"], "/formacion_recursos_humanos/models.py": ["/nucleo/models.py"], "/distinciones/models.py": ["/nucleo/models.py"]} |
61,064 | CIGAUNAM/SIA | refs/heads/master | /investigacion/admin.py | from django.contrib import admin
# Register your models here.
from . models import ArticuloCientifico, CapituloLibroInvestigacion, MapaArbitrado, InformeTecnico
admin.site.register(ArticuloCientifico)
admin.site.register(CapituloLibroInvestigacion)
admin.site.register(MapaArbitrado)
admin.site.register(InformeTecnico) | {"/apoyo_institucional/models.py": ["/nucleo/models.py"], "/experiencia_laboral/serializers.py": ["/experiencia_laboral/models.py"], "/vinculacion/admin.py": ["/vinculacion/models.py"], "/nucleo/serializers.py": ["/nucleo/models.py", "/formacion_academica/models.py"], "/formacion_academica/serializers.py": ["/formacion_academica/models.py"], "/formacion_recursos_humanos/admin.py": ["/formacion_recursos_humanos/models.py"], "/movilidad_academica/models.py": ["/nucleo/models.py", "/vinculacion/models.py"], "/difusion_cientifica/models.py": ["/nucleo/models.py"], "/experiencia_laboral/views.py": ["/experiencia_laboral/serializers.py"], "/nucleo/views.py": ["/nucleo/models.py", "/nucleo/serializers.py"], "/desarrollo_tecnologico/models.py": ["/nucleo/models.py"], "/formacion_academica/admin.py": ["/formacion_academica/models.py"], "/investigacion/admin.py": ["/investigacion/models.py"], "/difusion_cientifica/admin.py": ["/difusion_cientifica/models.py"], "/investigacion/models.py": ["/nucleo/models.py"], "/formacion_academica/models.py": ["/nucleo/models.py"], "/movilidad_academica/admin.py": ["/movilidad_academica/models.py"], "/geom/envolvente.py": ["/geom/funciones.py"], "/nucleo/admin.py": ["/nucleo/models.py"], "/vinculacion/models.py": ["/nucleo/models.py", "/investigacion/models.py"], "/divulgacion_cientifica/admin.py": ["/divulgacion_cientifica/models.py"], "/experiencia_laboral/models.py": ["/nucleo/models.py"], "/docencia/models.py": ["/nucleo/models.py", "/vinculacion/models.py", "/formacion_academica/models.py"], "/experiencia_laboral/admin.py": ["/experiencia_laboral/models.py"], "/desarrollo_tecnologico/admin.py": ["/desarrollo_tecnologico/models.py"], "/divulgacion_cientifica/models.py": ["/nucleo/models.py"], "/formacion_academica/views.py": ["/formacion_academica/serializers.py"], "/apoyo_institucional/admin.py": ["/apoyo_institucional/models.py"], "/formacion_recursos_humanos/models.py": ["/nucleo/models.py"], "/distinciones/models.py": ["/nucleo/models.py"]} |
61,065 | CIGAUNAM/SIA | refs/heads/master | /difusion_cientifica/admin.py | from django.contrib import admin
# Register your models here.
from . models import MemoriaInExtenso, PrologoLibro, Resena, OrganizacionEventoAcademico, ParticipacionEventoAcademico
admin.site.register(MemoriaInExtenso)
admin.site.register(PrologoLibro)
admin.site.register(Resena)
admin.site.register(OrganizacionEventoAcademico)
admin.site.register(ParticipacionEventoAcademico) | {"/apoyo_institucional/models.py": ["/nucleo/models.py"], "/experiencia_laboral/serializers.py": ["/experiencia_laboral/models.py"], "/vinculacion/admin.py": ["/vinculacion/models.py"], "/nucleo/serializers.py": ["/nucleo/models.py", "/formacion_academica/models.py"], "/formacion_academica/serializers.py": ["/formacion_academica/models.py"], "/formacion_recursos_humanos/admin.py": ["/formacion_recursos_humanos/models.py"], "/movilidad_academica/models.py": ["/nucleo/models.py", "/vinculacion/models.py"], "/difusion_cientifica/models.py": ["/nucleo/models.py"], "/experiencia_laboral/views.py": ["/experiencia_laboral/serializers.py"], "/nucleo/views.py": ["/nucleo/models.py", "/nucleo/serializers.py"], "/desarrollo_tecnologico/models.py": ["/nucleo/models.py"], "/formacion_academica/admin.py": ["/formacion_academica/models.py"], "/investigacion/admin.py": ["/investigacion/models.py"], "/difusion_cientifica/admin.py": ["/difusion_cientifica/models.py"], "/investigacion/models.py": ["/nucleo/models.py"], "/formacion_academica/models.py": ["/nucleo/models.py"], "/movilidad_academica/admin.py": ["/movilidad_academica/models.py"], "/geom/envolvente.py": ["/geom/funciones.py"], "/nucleo/admin.py": ["/nucleo/models.py"], "/vinculacion/models.py": ["/nucleo/models.py", "/investigacion/models.py"], "/divulgacion_cientifica/admin.py": ["/divulgacion_cientifica/models.py"], "/experiencia_laboral/models.py": ["/nucleo/models.py"], "/docencia/models.py": ["/nucleo/models.py", "/vinculacion/models.py", "/formacion_academica/models.py"], "/experiencia_laboral/admin.py": ["/experiencia_laboral/models.py"], "/desarrollo_tecnologico/admin.py": ["/desarrollo_tecnologico/models.py"], "/divulgacion_cientifica/models.py": ["/nucleo/models.py"], "/formacion_academica/views.py": ["/formacion_academica/serializers.py"], "/apoyo_institucional/admin.py": ["/apoyo_institucional/models.py"], "/formacion_recursos_humanos/models.py": ["/nucleo/models.py"], "/distinciones/models.py": ["/nucleo/models.py"]} |
61,066 | CIGAUNAM/SIA | refs/heads/master | /vinculacion/apps.py | from django.apps import AppConfig
class VinculacionConfig(AppConfig):
name = 'vinculacion'
| {"/apoyo_institucional/models.py": ["/nucleo/models.py"], "/experiencia_laboral/serializers.py": ["/experiencia_laboral/models.py"], "/vinculacion/admin.py": ["/vinculacion/models.py"], "/nucleo/serializers.py": ["/nucleo/models.py", "/formacion_academica/models.py"], "/formacion_academica/serializers.py": ["/formacion_academica/models.py"], "/formacion_recursos_humanos/admin.py": ["/formacion_recursos_humanos/models.py"], "/movilidad_academica/models.py": ["/nucleo/models.py", "/vinculacion/models.py"], "/difusion_cientifica/models.py": ["/nucleo/models.py"], "/experiencia_laboral/views.py": ["/experiencia_laboral/serializers.py"], "/nucleo/views.py": ["/nucleo/models.py", "/nucleo/serializers.py"], "/desarrollo_tecnologico/models.py": ["/nucleo/models.py"], "/formacion_academica/admin.py": ["/formacion_academica/models.py"], "/investigacion/admin.py": ["/investigacion/models.py"], "/difusion_cientifica/admin.py": ["/difusion_cientifica/models.py"], "/investigacion/models.py": ["/nucleo/models.py"], "/formacion_academica/models.py": ["/nucleo/models.py"], "/movilidad_academica/admin.py": ["/movilidad_academica/models.py"], "/geom/envolvente.py": ["/geom/funciones.py"], "/nucleo/admin.py": ["/nucleo/models.py"], "/vinculacion/models.py": ["/nucleo/models.py", "/investigacion/models.py"], "/divulgacion_cientifica/admin.py": ["/divulgacion_cientifica/models.py"], "/experiencia_laboral/models.py": ["/nucleo/models.py"], "/docencia/models.py": ["/nucleo/models.py", "/vinculacion/models.py", "/formacion_academica/models.py"], "/experiencia_laboral/admin.py": ["/experiencia_laboral/models.py"], "/desarrollo_tecnologico/admin.py": ["/desarrollo_tecnologico/models.py"], "/divulgacion_cientifica/models.py": ["/nucleo/models.py"], "/formacion_academica/views.py": ["/formacion_academica/serializers.py"], "/apoyo_institucional/admin.py": ["/apoyo_institucional/models.py"], "/formacion_recursos_humanos/models.py": ["/nucleo/models.py"], "/distinciones/models.py": ["/nucleo/models.py"]} |
61,067 | CIGAUNAM/SIA | refs/heads/master | /experiencia_laboral/urls.py | from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from experiencia_laboral import views
urlpatterns = [
url(r'^experiencias.laborales/$', views.ExperienciaLaboralList.as_view()),
url(r'^experiencia.laboral/(?P<pk>[0-9]+)/$', views.ExperienciaLaboralDetail.as_view()),
url(r'^lineas.investigacion/$', views.LineaInvestigacionList.as_view()),
url(r'^linea.investigacion/(?P<pk>[0-9]+)/$', views.LineaInvestigacionDetail.as_view()),
url(r'^capacidades.potencialidades/$', views.CapacidadPotencialidadList.as_view()),
url(r'^capacidad.potencialidad/(?P<pk>[0-9]+)/$', views.CapacidadPotencialidadDetail.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns) | {"/apoyo_institucional/models.py": ["/nucleo/models.py"], "/experiencia_laboral/serializers.py": ["/experiencia_laboral/models.py"], "/vinculacion/admin.py": ["/vinculacion/models.py"], "/nucleo/serializers.py": ["/nucleo/models.py", "/formacion_academica/models.py"], "/formacion_academica/serializers.py": ["/formacion_academica/models.py"], "/formacion_recursos_humanos/admin.py": ["/formacion_recursos_humanos/models.py"], "/movilidad_academica/models.py": ["/nucleo/models.py", "/vinculacion/models.py"], "/difusion_cientifica/models.py": ["/nucleo/models.py"], "/experiencia_laboral/views.py": ["/experiencia_laboral/serializers.py"], "/nucleo/views.py": ["/nucleo/models.py", "/nucleo/serializers.py"], "/desarrollo_tecnologico/models.py": ["/nucleo/models.py"], "/formacion_academica/admin.py": ["/formacion_academica/models.py"], "/investigacion/admin.py": ["/investigacion/models.py"], "/difusion_cientifica/admin.py": ["/difusion_cientifica/models.py"], "/investigacion/models.py": ["/nucleo/models.py"], "/formacion_academica/models.py": ["/nucleo/models.py"], "/movilidad_academica/admin.py": ["/movilidad_academica/models.py"], "/geom/envolvente.py": ["/geom/funciones.py"], "/nucleo/admin.py": ["/nucleo/models.py"], "/vinculacion/models.py": ["/nucleo/models.py", "/investigacion/models.py"], "/divulgacion_cientifica/admin.py": ["/divulgacion_cientifica/models.py"], "/experiencia_laboral/models.py": ["/nucleo/models.py"], "/docencia/models.py": ["/nucleo/models.py", "/vinculacion/models.py", "/formacion_academica/models.py"], "/experiencia_laboral/admin.py": ["/experiencia_laboral/models.py"], "/desarrollo_tecnologico/admin.py": ["/desarrollo_tecnologico/models.py"], "/divulgacion_cientifica/models.py": ["/nucleo/models.py"], "/formacion_academica/views.py": ["/formacion_academica/serializers.py"], "/apoyo_institucional/admin.py": ["/apoyo_institucional/models.py"], "/formacion_recursos_humanos/models.py": ["/nucleo/models.py"], "/distinciones/models.py": ["/nucleo/models.py"]} |
61,068 | CIGAUNAM/SIA | refs/heads/master | /investigacion/models.py | from django.db import models
from django.conf import settings
from autoslug import AutoSlugField
from nucleo.models import User, Tag, Pais, Estado, Ciudad, Ubicacion, Institucion, Dependencia, Cargo, Proyecto, TipoDocumento, Revista, Indice, Libro, Editorial, Coleccion
STATUS_PUBLICACION = getattr(settings, 'STATUS_PUBLICACION', (('PUBLICADO', 'Publicado'), ('EN_PRENSA', 'En prensa'), ('ACEPTADO', 'Aceptado'), ('ENVIADO', 'Enviado'), ('OTRO', 'Otro')))
# Create your models here.
class ArticuloCientifico(models.Model):
titulo = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='titulo', unique=True)
descripcion = models.TextField(blank=True)
tipo = models.CharField(max_length=16, choices=(('ARTICULO', 'Artículo'), ('ACTA', 'Acta'), ('CARTA', 'Carta'), ('RESENA', 'Reseña'), ('OTRO', 'Otro')))
revista = models.ForeignKey(Revista)
status = models.CharField(max_length=20, choices=STATUS_PUBLICACION)
solo_electronico = models.BooleanField(default=False)
autores = models.ManyToManyField(User, related_name='articulo_cientifico_autores')
alumnos = models.ManyToManyField(User, related_name='articulo_cientifico_alumnos', blank=True)
indices = models.ManyToManyField(Indice, related_name='articulo_cientifico_indices', blank=True)
nombre_abreviado_wos = models.CharField(max_length=255, blank=True)
url = models.URLField(blank=True)
fecha = models.DateField(auto_now=False)
volumen = models.CharField(max_length=100, blank=True)
numero = models.CharField(max_length=100, blank=True)
issn_impreso = models.CharField(max_length=40, blank=True, verbose_name='ISSN Impreso')
issn_online = models.CharField(max_length=40, blank=True, verbose_name='ISSN Online')
pagina_inicio = models.PositiveIntegerField()
pagina_fin = models.PositiveIntegerField()
id_doi = models.CharField(max_length=100, blank=True)
id_wos = models.CharField(max_length=100, blank=True)
proyectos = models.ManyToManyField(Proyecto, related_name='articulo_cientifico_proyectos')
#usuario = models.ForeignKey(User)
tags = models.ManyToManyField(Tag, related_name='articulo_cientifico_tags', blank=True)
def __str__(self):
return "{} : {} : {}".format(self.titulo, self.tipo.title(), self.revista)
class Meta:
verbose_name = "Artículo científico"
verbose_name_plural = "Artículos científicos"
ordering = ['fecha', 'titulo']
class CapituloLibroInvestigacion(models.Model):
titulo = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='titulo', unique=True)
descripcion = models.TextField(blank=True)
libro = models.ForeignKey(Libro)
#status = models.CharField(max_length=20, choices=STATUS_PUBLICACION)
pagina_inicio = models.PositiveIntegerField()
pagina_fin = models.PositiveIntegerField()
proyectos = models.ManyToManyField(Proyecto, related_name='capitulo_libro_investigacion_proyectos', blank=True)
tags = models.ManyToManyField(Tag, related_name='capitulo_libro_investigacion_tags', blank=True)
def __str__(self):
return "{} : {}".format(self.titulo, self.libro)
class Meta:
verbose_name = "Capítulo en libro"
verbose_name_plural = "Capítulos en libros"
ordering = ['titulo']
class MapaArbitrado(models.Model):
titulo = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='titulo', unique=True)
descripcion = models.TextField(blank=True)
escala = models.CharField(max_length=30)
autores = models.ManyToManyField(User, related_name='mapa_arbitrado_autores')
editores = models.ManyToManyField(User, related_name='mapa_arbitrado_editores', blank=True)
coordinadores = models.ManyToManyField(User, related_name='mapa_arbitrado_coordinadores', blank=True)
status = models.CharField(max_length=20, choices=STATUS_PUBLICACION)
ciudad = models.ForeignKey(Ciudad)
editorial = models.ForeignKey(Editorial)
fecha = models.DateField(auto_now=False)
numero_edicion = models.PositiveIntegerField(default=1)
numero_paginas = models.PositiveIntegerField(default=1)
coleccion = models.ForeignKey(Coleccion, blank=True)
volumen = models.CharField(max_length=255, blank=True)
isbn = models.SlugField(max_length=30, blank=True)
url = models.URLField(blank=True)
proyectos = models.ManyToManyField(Proyecto, related_name='mapa_arbitrado_proyectos', blank=True)
tags = models.ManyToManyField(Tag, related_name='mapa_arbitrado_tags', blank=True)
def __str__(self):
return "{} : ({}) : {}".format(self.titulo, self.escala, self.fecha)
class Meta:
verbose_name = "Mapa arbitrado"
verbose_name_plural = "Mapas arbitrados"
ordering = ['fecha', 'titulo']
class InformeTecnico(models.Model):
titulo = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='titulo', unique=True)
descripcion = models.TextField(blank=True)
autores = models.ManyToManyField(User, related_name='informe_tecnico_autores')
fecha = models.DateField(auto_now=False)
numero_paginas = models.PositiveIntegerField(default=1)
proyectos = models.ManyToManyField(Proyecto, related_name='informe_tecnico_proyectos')
url = models.URLField(blank=True)
tags = models.ManyToManyField(Tag, related_name='informe_tecnico_tags', blank=True)
def __str__(self):
return "{} : {}".format(self.titulo, self.fecha)
class Meta:
verbose_name = "Informe técnico de acceso público"
verbose_name_plural = "Informes técnicos de acceso público"
ordering = ['fecha', 'titulo']
| {"/apoyo_institucional/models.py": ["/nucleo/models.py"], "/experiencia_laboral/serializers.py": ["/experiencia_laboral/models.py"], "/vinculacion/admin.py": ["/vinculacion/models.py"], "/nucleo/serializers.py": ["/nucleo/models.py", "/formacion_academica/models.py"], "/formacion_academica/serializers.py": ["/formacion_academica/models.py"], "/formacion_recursos_humanos/admin.py": ["/formacion_recursos_humanos/models.py"], "/movilidad_academica/models.py": ["/nucleo/models.py", "/vinculacion/models.py"], "/difusion_cientifica/models.py": ["/nucleo/models.py"], "/experiencia_laboral/views.py": ["/experiencia_laboral/serializers.py"], "/nucleo/views.py": ["/nucleo/models.py", "/nucleo/serializers.py"], "/desarrollo_tecnologico/models.py": ["/nucleo/models.py"], "/formacion_academica/admin.py": ["/formacion_academica/models.py"], "/investigacion/admin.py": ["/investigacion/models.py"], "/difusion_cientifica/admin.py": ["/difusion_cientifica/models.py"], "/investigacion/models.py": ["/nucleo/models.py"], "/formacion_academica/models.py": ["/nucleo/models.py"], "/movilidad_academica/admin.py": ["/movilidad_academica/models.py"], "/geom/envolvente.py": ["/geom/funciones.py"], "/nucleo/admin.py": ["/nucleo/models.py"], "/vinculacion/models.py": ["/nucleo/models.py", "/investigacion/models.py"], "/divulgacion_cientifica/admin.py": ["/divulgacion_cientifica/models.py"], "/experiencia_laboral/models.py": ["/nucleo/models.py"], "/docencia/models.py": ["/nucleo/models.py", "/vinculacion/models.py", "/formacion_academica/models.py"], "/experiencia_laboral/admin.py": ["/experiencia_laboral/models.py"], "/desarrollo_tecnologico/admin.py": ["/desarrollo_tecnologico/models.py"], "/divulgacion_cientifica/models.py": ["/nucleo/models.py"], "/formacion_academica/views.py": ["/formacion_academica/serializers.py"], "/apoyo_institucional/admin.py": ["/apoyo_institucional/models.py"], "/formacion_recursos_humanos/models.py": ["/nucleo/models.py"], "/distinciones/models.py": ["/nucleo/models.py"]} |
61,069 | CIGAUNAM/SIA | refs/heads/master | /formacion_academica/urls.py | from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from formacion_academica import views
urlpatterns = [
url(r'^cursos.especializacion/$', views.CursoEspecializacionList.as_view()),
url(r'^curso.especializacion/(?P<pk>[0-9]+)/$', views.CursoEspecializacionDetail.as_view()),
url(r'^licenciaturas/$', views.LicenciaturaList.as_view()),
url(r'^licenciatura/(?P<pk>[0-9]+)/$', views.LicenciaturaDetail.as_view()),
url(r'^maestrias/$', views.MaestriaList.as_view()),
url(r'^maestria/(?P<pk>[0-9]+)/$', views.MaestriaDetail.as_view()),
url(r'^doctorados/$', views.DoctoradoList.as_view()),
url(r'^doctorado/(?P<pk>[0-9]+)/$', views.DoctoradoDetail.as_view()),
url(r'^postdoctorados/$', views.PostDoctoradoList.as_view()),
url(r'^postdoctorado/(?P<pk>[0-9]+)/$', views.PostDoctoradoDetail.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns)
| {"/apoyo_institucional/models.py": ["/nucleo/models.py"], "/experiencia_laboral/serializers.py": ["/experiencia_laboral/models.py"], "/vinculacion/admin.py": ["/vinculacion/models.py"], "/nucleo/serializers.py": ["/nucleo/models.py", "/formacion_academica/models.py"], "/formacion_academica/serializers.py": ["/formacion_academica/models.py"], "/formacion_recursos_humanos/admin.py": ["/formacion_recursos_humanos/models.py"], "/movilidad_academica/models.py": ["/nucleo/models.py", "/vinculacion/models.py"], "/difusion_cientifica/models.py": ["/nucleo/models.py"], "/experiencia_laboral/views.py": ["/experiencia_laboral/serializers.py"], "/nucleo/views.py": ["/nucleo/models.py", "/nucleo/serializers.py"], "/desarrollo_tecnologico/models.py": ["/nucleo/models.py"], "/formacion_academica/admin.py": ["/formacion_academica/models.py"], "/investigacion/admin.py": ["/investigacion/models.py"], "/difusion_cientifica/admin.py": ["/difusion_cientifica/models.py"], "/investigacion/models.py": ["/nucleo/models.py"], "/formacion_academica/models.py": ["/nucleo/models.py"], "/movilidad_academica/admin.py": ["/movilidad_academica/models.py"], "/geom/envolvente.py": ["/geom/funciones.py"], "/nucleo/admin.py": ["/nucleo/models.py"], "/vinculacion/models.py": ["/nucleo/models.py", "/investigacion/models.py"], "/divulgacion_cientifica/admin.py": ["/divulgacion_cientifica/models.py"], "/experiencia_laboral/models.py": ["/nucleo/models.py"], "/docencia/models.py": ["/nucleo/models.py", "/vinculacion/models.py", "/formacion_academica/models.py"], "/experiencia_laboral/admin.py": ["/experiencia_laboral/models.py"], "/desarrollo_tecnologico/admin.py": ["/desarrollo_tecnologico/models.py"], "/divulgacion_cientifica/models.py": ["/nucleo/models.py"], "/formacion_academica/views.py": ["/formacion_academica/serializers.py"], "/apoyo_institucional/admin.py": ["/apoyo_institucional/models.py"], "/formacion_recursos_humanos/models.py": ["/nucleo/models.py"], "/distinciones/models.py": ["/nucleo/models.py"]} |
61,070 | CIGAUNAM/SIA | refs/heads/master | /formacion_academica/models.py | from django.db import models
from django.conf import settings
from autoslug import AutoSlugField
from nucleo.models import User, Tag, Dependencia, AreaConocimiento, ProgramaLicenciatura, ProgramaMaestria, ProgramaDoctorado, Proyecto
CURSO_ESPECIALIZACION_TIPO = getattr(settings, 'CURSO_ESPECIALIZACION_TIPO', (('CURSO', 'Curso'), ('DIPLOMADO', 'Diplomado'), ('CERTIFICACION', 'Certificación'), ('OTRO', 'Otro')))
CURSO_ESPECIALIZACION_MODALIDAD = getattr(settings, 'CURSO_ESPECIALIZACION_MODALIDAD', (('PRESENCIAL', 'Presencial'), ('EN_LINEA', 'En línea'), ('MIXTO', 'Mixto'), ('OTRO', 'Otro')))
# Create your models here.
class CursoEspecializacion(models.Model):
nombre_curso = models.CharField(max_length=255, verbose_name='Nombre del curso')
slug = AutoSlugField(populate_from='nombre_curso', unique=True)
descripcion = models.TextField(verbose_name='Descripción', blank=True)
tipo = models.CharField(max_length=20, choices=CURSO_ESPECIALIZACION_TIPO, verbose_name='Tipo de curso')
horas = models.PositiveIntegerField(verbose_name='Número de horas')
fecha_inicio = models.DateField('Fecha de inicio')
fecha_fin = models.DateField('Fecha de finalización', blank=True, null=True)
modalidad = models.CharField(max_length=20, choices=CURSO_ESPECIALIZACION_MODALIDAD)
area_conocimiento = models.ForeignKey(AreaConocimiento, verbose_name='Área de conocimiento')
dependencia = models.ForeignKey(Dependencia)
usuario = models.ForeignKey(User, related_name='cursos_especializacion')
tags = models.ManyToManyField(Tag, related_name='curso_especializacion_tags', blank=True)
def __str__(self):
return "{} : {} : {}".format(self.nombre_curso, self.fecha_inicio, self.usuario)
class Meta:
ordering = ['fecha_inicio']
verbose_name = 'Curso de especialización'
verbose_name_plural = 'Cursos de especialización'
unique_together = ['nombre_curso', 'fecha_inicio', 'usuario']
class Licenciatura(models.Model):
carrera = models.ForeignKey(ProgramaLicenciatura)
descripcion = models.TextField(verbose_name='Descripición', blank=True)
dependencia = models.ForeignKey(Dependencia)
titulo_tesis = models.CharField(max_length=255)
slug = AutoSlugField(populate_from='titulo_tesis', unique=True)
#tesis = models.FileField(blank=True)
tesis_url = models.URLField(blank=True)
fecha_inicio = models.DateField('Fecha de inicio de licenciatura')
fecha_fin = models.DateField('Fecha de terminación de licenciatura')
fecha_grado = models.DateField('Fecha de obtención de grado licenciatura')
usuario = models.ForeignKey(User, related_name='licenciaturas')
tags = models.ManyToManyField(Tag, related_name='licenciatura_tags', blank=True)
def __str__(self):
return "{} : {} : {}".format(self.dependencia, str(self.carrera.programa), self.titulo_tesis)
class Meta:
ordering = ['dependencia', 'carrera', 'titulo_tesis']
class Maestria(models.Model):
programa = models.ForeignKey(ProgramaMaestria)
descripcion = models.TextField(verbose_name='Descripición', blank=True)
dependencia = models.ForeignKey(Dependencia)
titulo_tesis = models.CharField(max_length=255)
slug = AutoSlugField(populate_from='titulo_tesis', unique=True)
#tesis = models.FileField(blank=True)
tesis_url = models.URLField(blank=True)
fecha_inicio = models.DateField('Fecha de inicio de maestría')
fecha_fin = models.DateField('Fecha de terminación de maestría')
fecha_grado = models.DateField('Fecha de obtención de grado de maestría')
usuario = models.ForeignKey(User, related_name='maestrias')
tags = models.ManyToManyField(Tag, related_name='maestria_tags', blank=True)
def __str__(self):
return "{} : {} : {}".format(self.dependencia, self.programa.programa, self.titulo_tesis)
class Meta:
ordering = ['dependencia', 'programa', 'titulo_tesis']
class Doctorado(models.Model):
programa = models.ForeignKey(ProgramaDoctorado)
descripcion = models.TextField(verbose_name='Descripición', blank=True)
dependencia = models.ForeignKey(Dependencia)
titulo_tesis = models.CharField(max_length=255)
slug = AutoSlugField(populate_from='titulo_tesis', unique=True)
#tesis = models.FileField(blank=True)
tesis_url = models.URLField(blank=True)
fecha_inicio = models.DateField('Fecha de inicio de doctorado', auto_now=False)
fecha_fin = models.DateField('Fecha de terminación de doctorado', auto_now=False, blank=True, null=True)
fecha_grado = models.DateField('Fecha de obtención de grado de doctorado', auto_now=False, blank=True)
usuario = models.ForeignKey(User, related_name='doctorados')
tags = models.ManyToManyField(Tag, related_name='doctorado_tags', blank=True)
def __str__(self):
return "{} : {} : {}".format(self.dependencia, self.programa.programa, self.titulo_tesis)
class Meta:
ordering = ['fecha_grado', 'dependencia', 'titulo_tesis']
proyectos = [
('Ninguno', 1900, 1, 1, 2900, 1, 1, 'OTRO', 'OTRO', 'INDIVIDUAL', 'OTRO', )
]
class PostDoctorado(models.Model):
titulo = models.CharField(max_length=255)
descripcion = models.TextField(verbose_name='Descripición', blank=True)
area_conocimiento = models.ForeignKey(AreaConocimiento, related_name='postdoctorado_area_conocimiento', verbose_name='Área de conocimiento')
dependencia = models.ForeignKey(Dependencia)
proyecto = models.ForeignKey(Proyecto)
fecha_inicio = models.DateField('Fecha de inicio de postdoctorado', auto_now=False)
fecha_fin = models.DateField('Fecha de terminación de postdoctorado', auto_now=False)
usuario = models.ForeignKey(User, related_name='postdoctorados')
tags = models.ManyToManyField(Tag, related_name='post_doctorado_tags', blank=True)
def __str__(self):
return "{} : {} : {}".format(self.usuario, self.dependencia, self.area_conocimiento)
class Meta:
ordering = ['fecha_fin', 'dependencia'] | {"/apoyo_institucional/models.py": ["/nucleo/models.py"], "/experiencia_laboral/serializers.py": ["/experiencia_laboral/models.py"], "/vinculacion/admin.py": ["/vinculacion/models.py"], "/nucleo/serializers.py": ["/nucleo/models.py", "/formacion_academica/models.py"], "/formacion_academica/serializers.py": ["/formacion_academica/models.py"], "/formacion_recursos_humanos/admin.py": ["/formacion_recursos_humanos/models.py"], "/movilidad_academica/models.py": ["/nucleo/models.py", "/vinculacion/models.py"], "/difusion_cientifica/models.py": ["/nucleo/models.py"], "/experiencia_laboral/views.py": ["/experiencia_laboral/serializers.py"], "/nucleo/views.py": ["/nucleo/models.py", "/nucleo/serializers.py"], "/desarrollo_tecnologico/models.py": ["/nucleo/models.py"], "/formacion_academica/admin.py": ["/formacion_academica/models.py"], "/investigacion/admin.py": ["/investigacion/models.py"], "/difusion_cientifica/admin.py": ["/difusion_cientifica/models.py"], "/investigacion/models.py": ["/nucleo/models.py"], "/formacion_academica/models.py": ["/nucleo/models.py"], "/movilidad_academica/admin.py": ["/movilidad_academica/models.py"], "/geom/envolvente.py": ["/geom/funciones.py"], "/nucleo/admin.py": ["/nucleo/models.py"], "/vinculacion/models.py": ["/nucleo/models.py", "/investigacion/models.py"], "/divulgacion_cientifica/admin.py": ["/divulgacion_cientifica/models.py"], "/experiencia_laboral/models.py": ["/nucleo/models.py"], "/docencia/models.py": ["/nucleo/models.py", "/vinculacion/models.py", "/formacion_academica/models.py"], "/experiencia_laboral/admin.py": ["/experiencia_laboral/models.py"], "/desarrollo_tecnologico/admin.py": ["/desarrollo_tecnologico/models.py"], "/divulgacion_cientifica/models.py": ["/nucleo/models.py"], "/formacion_academica/views.py": ["/formacion_academica/serializers.py"], "/apoyo_institucional/admin.py": ["/apoyo_institucional/models.py"], "/formacion_recursos_humanos/models.py": ["/nucleo/models.py"], "/distinciones/models.py": ["/nucleo/models.py"]} |
61,071 | CIGAUNAM/SIA | refs/heads/master | /movilidad_academica/admin.py | from django.contrib import admin
# Register your models here.
from . models import EstanciaColaboracion
admin.site.register(EstanciaColaboracion) | {"/apoyo_institucional/models.py": ["/nucleo/models.py"], "/experiencia_laboral/serializers.py": ["/experiencia_laboral/models.py"], "/vinculacion/admin.py": ["/vinculacion/models.py"], "/nucleo/serializers.py": ["/nucleo/models.py", "/formacion_academica/models.py"], "/formacion_academica/serializers.py": ["/formacion_academica/models.py"], "/formacion_recursos_humanos/admin.py": ["/formacion_recursos_humanos/models.py"], "/movilidad_academica/models.py": ["/nucleo/models.py", "/vinculacion/models.py"], "/difusion_cientifica/models.py": ["/nucleo/models.py"], "/experiencia_laboral/views.py": ["/experiencia_laboral/serializers.py"], "/nucleo/views.py": ["/nucleo/models.py", "/nucleo/serializers.py"], "/desarrollo_tecnologico/models.py": ["/nucleo/models.py"], "/formacion_academica/admin.py": ["/formacion_academica/models.py"], "/investigacion/admin.py": ["/investigacion/models.py"], "/difusion_cientifica/admin.py": ["/difusion_cientifica/models.py"], "/investigacion/models.py": ["/nucleo/models.py"], "/formacion_academica/models.py": ["/nucleo/models.py"], "/movilidad_academica/admin.py": ["/movilidad_academica/models.py"], "/geom/envolvente.py": ["/geom/funciones.py"], "/nucleo/admin.py": ["/nucleo/models.py"], "/vinculacion/models.py": ["/nucleo/models.py", "/investigacion/models.py"], "/divulgacion_cientifica/admin.py": ["/divulgacion_cientifica/models.py"], "/experiencia_laboral/models.py": ["/nucleo/models.py"], "/docencia/models.py": ["/nucleo/models.py", "/vinculacion/models.py", "/formacion_academica/models.py"], "/experiencia_laboral/admin.py": ["/experiencia_laboral/models.py"], "/desarrollo_tecnologico/admin.py": ["/desarrollo_tecnologico/models.py"], "/divulgacion_cientifica/models.py": ["/nucleo/models.py"], "/formacion_academica/views.py": ["/formacion_academica/serializers.py"], "/apoyo_institucional/admin.py": ["/apoyo_institucional/models.py"], "/formacion_recursos_humanos/models.py": ["/nucleo/models.py"], "/distinciones/models.py": ["/nucleo/models.py"]} |
61,072 | CIGAUNAM/SIA | refs/heads/master | /geom/envolvente.py | from random import randrange
from geom.geomcom import Punto2D
from geom.funciones import *
import pygame, sys
from pygame.locals import *
puntos = []
ps = [(181, 40), (119, 121), (245, 226), (180, 90), (377, 225), (293, 285), (294, 46)]
for i in ps:
puntos.append(Punto2D(i[0], i[1]))
pt = puntos.copy()
pygame.init()
# set up the window
DISPLAYSURF = pygame.display.set_mode((500, 400), 0, 32)
pygame.display.set_caption('Drawing')
# set up the colors
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = ( 0, 255, 0)
BLUE = ( 0, 0, 255)
# draw on the surface object
DISPLAYSURF.fill(WHITE)
for i in puntos:
pygame.draw.circle(DISPLAYSURF, RED, (i.x, i.y), 2, 0)
print(puntos)
envolvente = []
D = {}
for i in range(len(ps)):
for j in range(len(ps)):
if i is not j:
if j > i:
pt.remove(pt[j])
pt.remove(pt[i])
else:
pt.remove(pt[i])
pt.remove(pt[j])
for k in pt:
if not is_to_the_left_of_line(k, puntos[i], puntos[j]):
break
else:
D[i] = j
pt = puntos.copy()
print(ps)
print(envolvente)
print(D)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
| {"/apoyo_institucional/models.py": ["/nucleo/models.py"], "/experiencia_laboral/serializers.py": ["/experiencia_laboral/models.py"], "/vinculacion/admin.py": ["/vinculacion/models.py"], "/nucleo/serializers.py": ["/nucleo/models.py", "/formacion_academica/models.py"], "/formacion_academica/serializers.py": ["/formacion_academica/models.py"], "/formacion_recursos_humanos/admin.py": ["/formacion_recursos_humanos/models.py"], "/movilidad_academica/models.py": ["/nucleo/models.py", "/vinculacion/models.py"], "/difusion_cientifica/models.py": ["/nucleo/models.py"], "/experiencia_laboral/views.py": ["/experiencia_laboral/serializers.py"], "/nucleo/views.py": ["/nucleo/models.py", "/nucleo/serializers.py"], "/desarrollo_tecnologico/models.py": ["/nucleo/models.py"], "/formacion_academica/admin.py": ["/formacion_academica/models.py"], "/investigacion/admin.py": ["/investigacion/models.py"], "/difusion_cientifica/admin.py": ["/difusion_cientifica/models.py"], "/investigacion/models.py": ["/nucleo/models.py"], "/formacion_academica/models.py": ["/nucleo/models.py"], "/movilidad_academica/admin.py": ["/movilidad_academica/models.py"], "/geom/envolvente.py": ["/geom/funciones.py"], "/nucleo/admin.py": ["/nucleo/models.py"], "/vinculacion/models.py": ["/nucleo/models.py", "/investigacion/models.py"], "/divulgacion_cientifica/admin.py": ["/divulgacion_cientifica/models.py"], "/experiencia_laboral/models.py": ["/nucleo/models.py"], "/docencia/models.py": ["/nucleo/models.py", "/vinculacion/models.py", "/formacion_academica/models.py"], "/experiencia_laboral/admin.py": ["/experiencia_laboral/models.py"], "/desarrollo_tecnologico/admin.py": ["/desarrollo_tecnologico/models.py"], "/divulgacion_cientifica/models.py": ["/nucleo/models.py"], "/formacion_academica/views.py": ["/formacion_academica/serializers.py"], "/apoyo_institucional/admin.py": ["/apoyo_institucional/models.py"], "/formacion_recursos_humanos/models.py": ["/nucleo/models.py"], "/distinciones/models.py": ["/nucleo/models.py"]} |
61,073 | CIGAUNAM/SIA | refs/heads/master | /nucleo/models.py | from django.db import models
from django.contrib.auth.models import AbstractUser
from django.conf import settings
from autoslug import AutoSlugField
STATUS_PROYECTO = getattr(settings, 'STATUS_PROYECTO', (('NUEVO', 'Nuevo'), ('EN_PROCESO', 'En proceso'), ('CONCLUIDO', 'Concluído'), ('OTRO', 'Otro')))
CLASIFICACION_PROYECTO = getattr(settings, 'CLASIFICACION_PROYECTO', (('BASICO', 'Básico'), ('APLICADO', 'Aplicado'), ('DESARROLLO_TECNOLOGICO', 'Desarrollo tecnológico'), ('INNOVACION', 'Innovación'), ('INVESTIGACION_FRONTERA', 'Investigación de frontera'), ('OTRO', 'Otro')))
ORGANIZACION_PROYECTO = getattr(settings, 'ORGANIZACION_PROYECTO', (('INDIVIDUAL', 'Individual'), ('COLECTIVO', 'Colectivo')))
MODALIDAD_PROYECTO = getattr(settings, 'MODALIDAD_PROYECTO', (('DISCIPLINARIO', 'Disciplinario'), ('MULTIDISCIPLINARIO', 'Multidisciplinario'), ('INTERDISCIPLINARIO', 'Interisciplinario'), ('TRANSDISCIPLINARIO', 'Transdisciplinario'), ('OTRA', 'Otra')))
FINANCIAMIENTO_UNAM = getattr(settings, 'FINANCIAMIENTO_UNAM', (('ASIGNADO', 'Presupuesto asignado a la entidad'), ('CONCURSADO', 'Presupuesto concursado por la entidad'), ('AUTOGENERADO', 'Recursos autogenerados (extraordinarios)'), ('OTRO', 'Otro')))
FINANCIAMIENTO_EXTERNO = getattr(settings, 'FINANCIAMIENTO_UNAM', (('ESTATAL', 'Gubernamental Estatal'), ('FEDERAL', 'Gubernamental Federal'), ('LUCRATIVO', 'Privado lucrativo'), ('NO_LUCRATIVO', 'Privado no lucrativo'), ('EXTRANJERO', 'Recursos del extranjero')))
FINANCIAMIENTO_TIPO = getattr(settings, 'FINANCIAMIENTO_TIPO', (('UNAM', FINANCIAMIENTO_UNAM), ('Externo', FINANCIAMIENTO_EXTERNO)))
CARGO__TIPO_CARGO = getattr(settings, 'CARGO__TIPO_CARGO', (('ACADEMICO', 'Académico'), ('ADMINISTRATIVO', 'Administrativo')))
GRADO_ACADEMICO = getattr(settings, 'GRADO_ACADEMICO', (('LICENCIATURA', 'licenciatura'), ('MAESTRIA', 'Maestría'), ('DOCTORADO', 'Doctorado')))
STATUS_PUBLICACION = getattr(settings, 'STATUS_PUBLICACION', (('PUBLICADO', 'Publicado'), ('EN_PRENSA', 'En prensa'), ('ACEPTADO', 'Aceptado'), ('ENVIADO', 'Enviado'), ('OTRO', 'Otro')))
# Create your models here.
class Tag(models.Model):
tag = models.CharField(max_length=50, unique=True)
slug = AutoSlugField(populate_from='tag')
help_text = 'Etiqueta para configuraciòn de URL.'
def __str__(self):
return self.tag
class Meta:
ordering = ['tag']
class ZonaPais(models.Model):
zona = models.CharField(max_length=60, unique=True)
slug = AutoSlugField(populate_from='zona')
def __str__(self):
return self.zona
class Meta:
ordering = ['zona']
verbose_name = 'Zona de paises'
verbose_name_plural = 'Zonas de paises'
class Pais(models.Model):
pais = models.CharField(max_length=60, unique=True)
slug = AutoSlugField(populate_from='pais', unique=True)
nombre_extendido = models.CharField(max_length=200, unique=True)
codigo = models.SlugField(max_length=2, unique=True)
zona = models.ForeignKey(ZonaPais)
def __str__(self):
return self.pais
class Meta:
ordering = ['pais']
verbose_name_plural = 'Paises'
verbose_name = 'País'
class Estado(models.Model):
estado = models.CharField(max_length=200)
slug = AutoSlugField(populate_from='estado')
pais = models.ForeignKey(Pais)
def __str__(self):
return "{} : {}".format(self.pais, self.estado)
class Meta:
unique_together = ['estado', 'pais']
ordering = ['pais', 'estado']
class Ciudad(models.Model):
ciudad = models.CharField(max_length=255)
slug = AutoSlugField(populate_from='ciudad')
estado = models.ForeignKey(Estado)
def __str__(self):
return "{} : {} ".format(self.estado, self.ciudad)
class Meta:
unique_together = ['ciudad', 'estado']
ordering = ['estado', 'ciudad']
verbose_name_plural = 'Ciudades'
class Region(models.Model):
region = models.CharField(max_length=200)
slug = AutoSlugField(populate_from='region', unique=True)
descripcion = models.TextField(blank=True)
paises = models.ManyToManyField(Pais, related_name='region_paises', blank=True)
estados = models.ManyToManyField(Estado, related_name='region_estados', blank=True)
ciudades = models.ManyToManyField(Ciudad, related_name='region_ciudades', blank=True)
def __str__(self):
return self.region
class Meta:
ordering = ['region']
verbose_name = 'Región'
verbose_name_plural = 'Regiones'
class Ubicacion(models.Model):
direccion1 = models.CharField('Dirección', max_length=255)
direccion2 = models.CharField('Dirección (continuación)', blank=True, max_length=255)
slug = AutoSlugField(populate_from='direccion1', unique=True)
descripcion = models.TextField(blank=True)
ciudad = models.ForeignKey(Ciudad)
codigo_postal = models.CharField(max_length=7, blank=True)
telefono = models.SlugField(max_length=20, blank=True)
def __str__(self):
return "{} : {} : {}".format(self.direccion1, self.direccion2, self.ciudad)
class Meta:
ordering = ['ciudad', 'direccion1']
unique_together = ['direccion1', 'direccion2', 'ciudad']
verbose_name = 'Ubicación'
verbose_name_plural = 'Ubicaciones'
class User(AbstractUser):
descripcion = models.TextField(blank=True)
tipo = models.CharField(max_length=30, choices=(('INVESTIGADOR', 'Investigador'), ('ADMINISTRATIVO', 'Administrativo'), ('TECNICO', 'Técnico'), ('OTRO', 'Otro')), default='OTRO')
fecha_nacimiento = models.DateField(null=True, blank=True)
pais_origen = models.ForeignKey(Pais, default=1)
rfc = models.SlugField(max_length=20, unique=True)
direccion1 = models.CharField(max_length=255)
direccion2 = models.CharField(max_length=255, blank=True)
ciudad = models.ForeignKey(Ciudad, default=1)
telefono = models.SlugField(max_length=20, blank=True)
celular = models.SlugField(max_length=20, blank=True)
url = models.URLField(blank=True, null=True)
sni = models.PositiveSmallIntegerField(default=0)
pride = models.CharField(max_length=2, choices=(('-', '-'), ('A', 'A'), ('B', 'B'), ('C', 'C'), ('D', 'D')), default='-')
ingreso_unam = models.DateField(null=True, blank=True)
ingreso_entidad = models.DateField(null=True, blank=True)
def __str__(self):
return "{} : {} {} : {}".format(self.username, self.first_name, self.last_name, self.rfc)
class Meta:
ordering = ['last_name']
class Institucion(models.Model):
institucion = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='institucion', max_length=255, unique=True)
descripcion = models.TextField(blank=True)
pais = models.ForeignKey(Pais)
def __str__(self):
return self.institucion
class Meta:
ordering = ['institucion']
verbose_name = 'Institución'
verbose_name_plural = 'Instituciones'
class Dependencia(models.Model):
dependencia = models.CharField(max_length=255)
slug = AutoSlugField(populate_from='dependencia', max_length=255, unique=True)
descripcion = models.TextField(blank=True)
institucion = models.ForeignKey(Institucion)
ciudad = models.ForeignKey(Ciudad)
subsistema_unam = models.CharField(max_length=50, choices=(('DIFUSION_CULTURAL', 'Subsistema de Difusión Cultural'),
('ESTUDIOS_POSGRADO', 'Subsistema de Estudios de Posgrado'),
('HUMANIDADES', 'Subsistema de Humanidades'),
('INVESTIGACION_CIENTIFICA', 'Subsistema de Investigación Científica'),
('ESCUELAS', 'Facultades y Escuelas'),
('DESARROLLO_INSTITUCIONAL', 'Desarrollo Institucional'),
('NO', 'No')), default='NO', verbose_name='Subsistema UNAM')
def __str__(self):
return "{} : {}".format(self.institucion, self.dependencia)
class Meta:
unique_together = ('dependencia', 'institucion')
ordering = ['institucion', 'dependencia']
class Departamento(models.Model):
departamento = models.CharField(max_length=255)
slug = AutoSlugField(populate_from='dependencia', unique=True)
descripcion = models.TextField(blank=True)
dependencia = models.ForeignKey(Dependencia)
def __str__(self):
return "{} : {}".format(self.dependencia, self.departamento)
class Meta:
unique_together = ('departamento', 'dependencia')
ordering = ['departamento', 'dependencia']
class Cargo(models.Model):
cargo = models.CharField(max_length=255)
slug = AutoSlugField(populate_from='cargo', unique=True)
descripcion = models.TextField(blank=True)
tipo_cargo = models.CharField(max_length=20, choices=(('ACADEMICO', 'Académico'), ('ADMINISTRATIVO', 'Administrativo'), ('OTRO', 'Otro')))
def __str__(self):
return self.cargo
class Meta:
unique_together = ['cargo', 'tipo_cargo']
ordering = ['cargo']
class Nombramiento(models.Model):
nombramiento = models.CharField(max_length=255, unique=True)
clave = models.CharField(max_length=20, unique=True)
slug = AutoSlugField(populate_from='nombramiento', unique=True)
descripcion = models.TextField(blank=True)
def __str__(self):
return self.nombramiento
class Meta:
ordering = ['id']
class AreaConocimiento(models.Model):
categoria = models.CharField(max_length=20, choices=(
('LSBM', 'Life Sciences and Biomedicine'), ('PHYS', 'Physical Sciences'), ('TECH', 'Technology'),
('ARTH', 'Arts and Humanities'), ('SS', 'Social Sciences'), ('ZTRA', 'Otra')))
area_conocimiento = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='area_conocimiento', unique=True)
descripcion = models.TextField(blank=True)
def __str__(self):
return self.area_conocimiento
class Meta:
ordering = ['categoria', 'area_conocimiento']
verbose_name = 'Área General de Conocimiento'
verbose_name_plural = 'Áreas Generales de Conocimiento'
class AreaEspecialidad(models.Model):
especialidad = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='especialidad', unique=True)
descripcion = models.TextField(blank=True)
area_conocimiento = models.ForeignKey(AreaConocimiento)
def __str__(self):
return self.especialidad
class Meta:
ordering = ['especialidad']
verbose_name = 'Área de especialidad de WOS y otras entidades'
verbose_name_plural = 'Áreas de especialidades de WOS y otras entidades'
class ImpactoSocial(models.Model):
impacto_social = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='impacto_social', unique=True)
descripcion = models.TextField(blank=True)
def __str__(self):
return self.impacto_social
class Meta:
ordering = ['impacto_social']
verbose_name = 'Impacto social'
verbose_name_plural = 'Impactos sociales'
class ProgramaFinanciamiento(models.Model):
programa_financiamiento = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='programa_financiamiento', unique=True)
descripcion = models.TextField(blank=True)
def __str__(self):
return self.programa_financiamiento
class Meta:
ordering = ['programa_financiamiento']
class Financiamiento(models.Model):
tipo_financiamiento = models.CharField(max_length=80, choices=FINANCIAMIENTO_TIPO)
descripcion = models.TextField(blank=True)
programas_financiamiento = models.ManyToManyField(ProgramaFinanciamiento, related_name='financiamiento_programas_financiamiento', blank=True)
#dependencias_financiamiento = models.ManyToManyField(Dependencia, related_name='financiamientos', blank=True)
dependencias_financiamiento = models.ManyToManyField(Dependencia, related_name='financiamiento_dependencias_financiamiento', blank=True)
clave_proyecto = models.CharField(max_length=255)
def __str__(self):
return "{} : {}".format(self.financiamiento, self.clave_proyecto)
class Meta:
verbose_name = 'Financiamiento'
verbose_name_plural = 'Financiamientos'
class Metodologia(models.Model):
metodologia = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='metodologia', unique=True)
descripcion = models.TextField(blank=True)
def __str__(self):
return self.metodologia
class Meta:
ordering = ['metodologia']
class Beca(models.Model):
beca = models.CharField(max_length=200, unique=True)
slug = AutoSlugField(populate_from='beca', unique=True)
descripcion = models.TextField(blank=True)
institucion = models.ForeignKey(Institucion)
def __str__(self):
return "{} : {}".format(self.beca, str(self.dependencia.dependencia))
class Reconocimiento(models.Model):
reconocimiento = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='reconocimiento', unique=True)
descripcion = models.TextField(blank=True)
def __str__(self):
return self.reconocimiento
class Meta:
ordering = ['reconocimiento']
class Tesis(models.Model):
titulo = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='titulo')
descripcion = models.TextField(blank=True)
grado_academico = models.CharField(max_length=20, choices=GRADO_ACADEMICO)
documento_tesis = models.FileField()
alumno = models.ForeignKey(User, related_name='tesis_alumno')
dependencia = models.ForeignKey(Dependencia)
beca = models.ForeignKey(Beca)
reconocimiento = models.ForeignKey(Reconocimiento, blank=True, null=True)
fecha_examen = models.DateField()
def __str__(self):
return "{} : {}".format(self.titulo, self.alumno, self.grado_academico)
class Meta:
ordering = ['-fecha_examen']
verbose_name = 'Tesis'
verbose_name_plural = 'Tesis'
class ProgramaLicenciatura(models.Model):
programa = models.CharField(max_length=255, unique=True)
descripcion = models.TextField(blank=True)
slug = AutoSlugField(populate_from='programa', unique=True)
area_conocimiento = models.ForeignKey(AreaConocimiento, verbose_name='Área de conocimiento')
def __str__(self):
return self.programa
class Meta:
ordering = ['programa']
verbose_name = 'Programa de licenciatura'
verbose_name_plural = 'Programas de licenciatura'
class ProgramaMaestria(models.Model):
programa = models.CharField(max_length=255, unique=True)
descripcion = models.TextField(blank=True)
slug = AutoSlugField(populate_from='programa', unique=True)
area_conocimiento = models.ForeignKey(AreaConocimiento, verbose_name='Área de conocimiento')
def __str__(self):
return self.programa
class Meta:
ordering = ['programa']
verbose_name = 'Programa de maestria'
verbose_name_plural = 'Programas de maestria'
class ProgramaDoctorado(models.Model):
programa = models.CharField(max_length=255, unique=True)
descripcion = models.TextField(blank=True)
slug = AutoSlugField(populate_from='programa', unique=True)
area_conocimiento = models.ForeignKey(AreaConocimiento, verbose_name='Área de conocimiento')
def __str__(self):
return self.programa
class Meta:
ordering = ['programa']
verbose_name = 'Programa de doctorado'
verbose_name_plural = 'Programas de doctorado'
class TipoEvento(models.Model):
tipo_evento = models.CharField(max_length=100, unique=True)
slug = AutoSlugField(populate_from='tipo_evento')
descripcion = models.TextField(blank=True)
def __str__(self):
return self.tipo_evento
class Meta:
verbose_name = 'Tipo de evento'
verbose_name_plural = 'Tipos de eventos'
class Evento(models.Model):
nombre_evento = models.CharField(max_length=255)
slug = AutoSlugField(populate_from='nombre_evento', unique=True)
descripcion = models.TextField(blank=True)
tipo = models.ForeignKey(TipoEvento)
fecha_inicio = models.DateField()
fecha_fin = models.DateField()
dependencias = models.ManyToManyField(Dependencia, related_name='evento_dependencias')
ubicacion = models.ForeignKey(Ubicacion)
def __str__(self):
return "{} : {} : {}".format(self.nombre_evento, self.fecha_inicio, self.ubicacion.ciudad)
class Meta:
ordering = ['fecha_inicio', 'nombre_evento']
unique_together = ['fecha_inicio', 'nombre_evento']
class Distincion(models.Model):
nombre_distincion = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='nombre_distincion', unique=True)
descripcion = models.TextField(blank=True)
tipo = models.CharField(max_length=30, choices=(('PREMIO', 'Premio'), ('DISTINCION', 'Distinción'), ('RECONOCIMIENTO', 'Reconocimiento'), ('MEDALLA', 'Medalla'), ('GUGGENHEIM', 'Beca Guggenheim'), ('HONORIS_CAUSA', 'Doctorado Honoris Causa'), ('OTRO', 'Otro')))
def __str__(self):
return self.nombre_distincion
class Meta:
ordering = ['nombre_distincion']
verbose_name = 'Distinción'
verbose_name_plural = 'Distinciones'
class ProblemaNacionalConacyt(models.Model):
nombre = models.CharField(max_length=200, unique=True)
slug = AutoSlugField(populate_from='nombre', unique=True)
descripcion = models.TextField(blank=True)
def __str__(self):
return self.nombre
class Meta:
verbose_name = ['Problemática Nacional CONACYT']
verbose_name_plural = ['Problemáticas Nacionales CONACYT']
class Proyecto(models.Model):
nombre_proyecto = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='nombre_proyecto', unique=True)
descripcion = models.TextField(blank=True)
tipo = models.CharField(max_length=50, choices=(('INVESTIGACION', 'Investigación'), ('OTRO', 'Otro')))
es_permanente = models.BooleanField(default=False)
fecha_inicio = models.DateField()
fecha_fin = models.DateField()
responsables = models.ManyToManyField(User, related_name='proyecto_responsables')
participantes = models.ManyToManyField(User, related_name='proyecto_participantes', blank=True)
status = models.CharField(max_length=30, choices=STATUS_PROYECTO)
clasificacion = models.CharField(max_length=30, choices=CLASIFICACION_PROYECTO)
organizacion = models.CharField(max_length=30, choices=ORGANIZACION_PROYECTO)
modalidad = models.CharField(max_length=30, choices=MODALIDAD_PROYECTO)
tematica_genero = models.BooleanField(default=False)
problemas_nacionales_conacyt = models.ManyToManyField(ProblemaNacionalConacyt)
descripcion_problema_nacional_conacyt = models.TextField(blank=True)
dependencias = models.ManyToManyField(Dependencia, related_name='proyecto_dependencias', blank=True)
financiamientos = models.ManyToManyField(Financiamiento, blank=True)
metodologias = models.ManyToManyField(Metodologia, related_name='proyecto_metodologias', blank=True)
especialidades = models.ManyToManyField(AreaEspecialidad, related_name='proyecto_especialidades', blank=True)
impactos_sociales = models.ManyToManyField(ImpactoSocial, related_name='proyecto_impactos_sociales', blank=True)
tecnicos = models.ManyToManyField(User, related_name='proyecto_impactos_tecnicos', blank=True)
alumnos_doctorado = models.ManyToManyField(User, related_name='proyecto_alumnos_doctorado', blank=True)
alumnos_maestria = models.ManyToManyField(User, related_name='proyecto_alumnos_maestria', blank=True)
alumnos_licenciatura = models.ManyToManyField(User, related_name='proyecto_alumnos_licenciatura', blank=True)
def __str__(self):
if self.nombre_proyecto == 'Ningúno':
return self.nombre_proyecto
else:
return "{} : {}".format(self.nombre_proyecto, self.fecha_inicio)
class Meta:
ordering = ['fecha_inicio', 'nombre_proyecto']
###################
class TipoDocumento(models.Model):
tipo = models.CharField(max_length=50, unique=True)
slug = AutoSlugField(populate_from='tipo', unique=True)
descripcion = models.TextField(blank=True)
def __str__(self):
return self.tipo
class Meta:
ordering = ['tipo']
verbose_name = 'Tipo de documento'
verbose_name_plural = 'Tipos de documentos'
class Indice(models.Model):
indice = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='indice', unique=True)
descripcion = models.TextField(blank=True)
def __str__(self):
return self.indice
class Memoria(models.Model):
memoria = models.CharField(max_length=255, unique=True)
descripcion = models.TextField(blank=True)
slug = AutoSlugField(populate_from='memoria')
def __str__(self):
return self.memoria
class Editorial(models.Model):
editorial = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='editorial', unique=True)
descripcion = models.TextField(blank=True)
pais = models.ForeignKey(Pais)
def __str__(self):
return self.editorial
class Meta:
ordering = ['editorial']
verbose_name_plural = 'Editoriales'
class Coleccion(models.Model):
coleccion = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='coleccion', unique=True)
descripcion = models.TextField(blank=True)
def __str__(self):
return self.coleccion
class Meta:
ordering = ['coleccion']
verbose_name = 'Colección'
verbose_name_plural = 'Colecciones'
class StatusPublicacion(models.Model):
status = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='status', unique=True)
def __str__(self):
return self.status
class Meta:
verbose_name = 'Status de publicacion'
verbose_name_plural = 'Status de publicaciones'
class Libro(models.Model):
nombre_libro = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='nombre_libro', unique=True)
descripcion = models.TextField(blank=True)
tipo = models.TextField(max_length=50, choices=(('INVESTIGACION', 'Investigación'), ('DIVULGACION', 'Divulgaciòn')))
autores = models.ManyToManyField(User, related_name='libro_autores')
editores = models.ManyToManyField(User, related_name='libro_editores', blank=True)
coordinadores = models.ManyToManyField(User, related_name='libro_coordinadores', blank=True)
editorial = models.ForeignKey(Editorial)
ciudad = models.ForeignKey(Ciudad)
fecha = models.DateField(auto_now=False)
numero_edicion = models.PositiveIntegerField(default=1)
numero_paginas = models.PositiveIntegerField(default=0)
coleccion = models.ForeignKey(Coleccion, blank=True, default=1)
volumen = models.CharField(max_length=255, blank=True)
isbn = models.SlugField(max_length=30)
url = models.URLField(blank=True)
tags = models.ManyToManyField(Tag, related_name='libro_tags', blank=True)
status = models.CharField(max_length=20, choices=STATUS_PUBLICACION)
def __str__(self):
return "{} : {} : {} : {}".format(self.nombre_libro, self.editorial, self.ciudad, self.isbn)
class Meta:
ordering = ['nombre_libro']
get_latest_by = ['fecha', 'nombre_libro', 'editorial']
class Revista(models.Model):
nombre_revista = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='nombre_revista', unique=True)
descripcion = models.TextField(blank=True)
editorial = models.ForeignKey(Editorial)
#pais = models.ForeignKey(Pais)
url = models.URLField(blank=True)
def __str__(self):
return "{} : {}".format(self.nombre_revista, self.editorial)
class Meta:
ordering = ['nombre_revista']
get_latest_by = ['fecha', 'nombre_revista', 'editorial'] | {"/apoyo_institucional/models.py": ["/nucleo/models.py"], "/experiencia_laboral/serializers.py": ["/experiencia_laboral/models.py"], "/vinculacion/admin.py": ["/vinculacion/models.py"], "/nucleo/serializers.py": ["/nucleo/models.py", "/formacion_academica/models.py"], "/formacion_academica/serializers.py": ["/formacion_academica/models.py"], "/formacion_recursos_humanos/admin.py": ["/formacion_recursos_humanos/models.py"], "/movilidad_academica/models.py": ["/nucleo/models.py", "/vinculacion/models.py"], "/difusion_cientifica/models.py": ["/nucleo/models.py"], "/experiencia_laboral/views.py": ["/experiencia_laboral/serializers.py"], "/nucleo/views.py": ["/nucleo/models.py", "/nucleo/serializers.py"], "/desarrollo_tecnologico/models.py": ["/nucleo/models.py"], "/formacion_academica/admin.py": ["/formacion_academica/models.py"], "/investigacion/admin.py": ["/investigacion/models.py"], "/difusion_cientifica/admin.py": ["/difusion_cientifica/models.py"], "/investigacion/models.py": ["/nucleo/models.py"], "/formacion_academica/models.py": ["/nucleo/models.py"], "/movilidad_academica/admin.py": ["/movilidad_academica/models.py"], "/geom/envolvente.py": ["/geom/funciones.py"], "/nucleo/admin.py": ["/nucleo/models.py"], "/vinculacion/models.py": ["/nucleo/models.py", "/investigacion/models.py"], "/divulgacion_cientifica/admin.py": ["/divulgacion_cientifica/models.py"], "/experiencia_laboral/models.py": ["/nucleo/models.py"], "/docencia/models.py": ["/nucleo/models.py", "/vinculacion/models.py", "/formacion_academica/models.py"], "/experiencia_laboral/admin.py": ["/experiencia_laboral/models.py"], "/desarrollo_tecnologico/admin.py": ["/desarrollo_tecnologico/models.py"], "/divulgacion_cientifica/models.py": ["/nucleo/models.py"], "/formacion_academica/views.py": ["/formacion_academica/serializers.py"], "/apoyo_institucional/admin.py": ["/apoyo_institucional/models.py"], "/formacion_recursos_humanos/models.py": ["/nucleo/models.py"], "/distinciones/models.py": ["/nucleo/models.py"]} |
61,074 | CIGAUNAM/SIA | refs/heads/master | /nucleo/admin.py | from django.contrib import admin
# Register your models here.
from . models import Tag, ZonaPais, Pais, Estado, Ciudad, Region, Ubicacion, Institucion, Dependencia, Departamento, \
User, ProgramaFinanciamiento, AreaConocimiento, AreaEspecialidad, ImpactoSocial, Cargo, Financiamiento, \
Metodologia, Beca, Tesis, ProgramaLicenciatura, \
ProgramaMaestria, ProgramaDoctorado, TipoEvento, Evento, ProblemaNacionalConacyt, Proyecto, Nombramiento, \
TipoDocumento, Indice, Editorial, StatusPublicacion, Coleccion, Libro, Revista
admin.site.register(Tag)
admin.site.register(ZonaPais)
admin.site.register(Pais)
admin.site.register(Estado)
admin.site.register(Ciudad)
admin.site.register(Region)
admin.site.register(Ubicacion)
admin.site.register(Institucion)
admin.site.register(Dependencia)
admin.site.register(Departamento)
admin.site.register(User)
admin.site.register(ProgramaFinanciamiento)
admin.site.register(AreaConocimiento)
admin.site.register(AreaEspecialidad)
admin.site.register(ImpactoSocial)
admin.site.register(Cargo)
admin.site.register(Financiamiento)
admin.site.register(Metodologia)
admin.site.register(Beca)
admin.site.register(Tesis)
admin.site.register(ProgramaLicenciatura)
admin.site.register(ProgramaMaestria)
admin.site.register(ProgramaDoctorado)
admin.site.register(TipoEvento)
admin.site.register(Evento)
admin.site.register(ProblemaNacionalConacyt)
admin.site.register(Proyecto)
admin.site.register(Nombramiento)
admin.site.register(TipoDocumento)
admin.site.register(Indice)
admin.site.register(Editorial)
admin.site.register(StatusPublicacion)
admin.site.register(Coleccion)
admin.site.register(Libro)
admin.site.register(Revista) | {"/apoyo_institucional/models.py": ["/nucleo/models.py"], "/experiencia_laboral/serializers.py": ["/experiencia_laboral/models.py"], "/vinculacion/admin.py": ["/vinculacion/models.py"], "/nucleo/serializers.py": ["/nucleo/models.py", "/formacion_academica/models.py"], "/formacion_academica/serializers.py": ["/formacion_academica/models.py"], "/formacion_recursos_humanos/admin.py": ["/formacion_recursos_humanos/models.py"], "/movilidad_academica/models.py": ["/nucleo/models.py", "/vinculacion/models.py"], "/difusion_cientifica/models.py": ["/nucleo/models.py"], "/experiencia_laboral/views.py": ["/experiencia_laboral/serializers.py"], "/nucleo/views.py": ["/nucleo/models.py", "/nucleo/serializers.py"], "/desarrollo_tecnologico/models.py": ["/nucleo/models.py"], "/formacion_academica/admin.py": ["/formacion_academica/models.py"], "/investigacion/admin.py": ["/investigacion/models.py"], "/difusion_cientifica/admin.py": ["/difusion_cientifica/models.py"], "/investigacion/models.py": ["/nucleo/models.py"], "/formacion_academica/models.py": ["/nucleo/models.py"], "/movilidad_academica/admin.py": ["/movilidad_academica/models.py"], "/geom/envolvente.py": ["/geom/funciones.py"], "/nucleo/admin.py": ["/nucleo/models.py"], "/vinculacion/models.py": ["/nucleo/models.py", "/investigacion/models.py"], "/divulgacion_cientifica/admin.py": ["/divulgacion_cientifica/models.py"], "/experiencia_laboral/models.py": ["/nucleo/models.py"], "/docencia/models.py": ["/nucleo/models.py", "/vinculacion/models.py", "/formacion_academica/models.py"], "/experiencia_laboral/admin.py": ["/experiencia_laboral/models.py"], "/desarrollo_tecnologico/admin.py": ["/desarrollo_tecnologico/models.py"], "/divulgacion_cientifica/models.py": ["/nucleo/models.py"], "/formacion_academica/views.py": ["/formacion_academica/serializers.py"], "/apoyo_institucional/admin.py": ["/apoyo_institucional/models.py"], "/formacion_recursos_humanos/models.py": ["/nucleo/models.py"], "/distinciones/models.py": ["/nucleo/models.py"]} |
61,075 | CIGAUNAM/SIA | refs/heads/master | /vinculacion/models.py | from django.db import models
from django.conf import settings
from autoslug import AutoSlugField
from nucleo.models import User, Tag, Pais, Estado, Ciudad, Region, Ubicacion, Institucion, Dependencia, Cargo, Proyecto, TipoDocumento, Revista, Indice, Libro, Editorial, Coleccion
from investigacion.models import CapituloLibroInvestigacion
RED_ACADEMICA__CLASIFICACION = getattr (settings, 'RED_ACADEMICA__CLASIFICACION', (('LOCAL', 'Local'), ('REGIONAL', 'Regional'), ('NACIONAL', 'Nacional'), ('INTERNACIONAL', 'Internacional'), ('OTRO', 'Otro')))
ENTIDAD_NO_ACADEMICA__CLASIFICACION = getattr (settings, 'ENTIDAD_NO_ACADEMICA__CLASIFICACION', (('FEDERAL', 'Gubernamental federal'), ('ESTATAL', 'Gubernamental estatal'), ('PRIVADO', 'Sector privado'), ('NO_LUCRATIVO', 'Sector privado no lucrativo'), ('EXTRANJERO', 'Extranjero'), ('OTRO', 'Otro')))
# Create your models here.
class ArbitrajePublicacionAcademica(models.Model):
descripcion = models.TextField(blank=True)
tipo_publicacion = models.CharField(max_length=20, choices=(('REVISTA', 'Revista'), ('LIBRO', 'Libro'), ('CAPITULO_LIBRO', 'Capitulo en libro')))
indices = models.ManyToManyField(Indice, related_name='arbitraje_publicacion_indices', blank=True)
revista = models.ForeignKey(Revista, blank=True)
libro = models.ForeignKey(Libro, blank=True)
capitulo_libro = models.ForeignKey(CapituloLibroInvestigacion, blank=True)
fecha_dictamen = models.DateField()
participantes = models.ManyToManyField(User, related_name='arbitraje_publicacion_participantes', blank=True)
tags = models.ManyToManyField(Tag, related_name='arbitraje_publicacion_academica_tags', blank=True)
def __str__(self):
lista_titulos = [self.revista, self.libro, self.capitulo_libro]
titulo = [x for x in lista_titulos if x != 'n/a']
titulo = titulo[0]
return "{} : {}".format(self.tipo_publicacion.title(), titulo, self.fecha_dictamen)
class Meta:
ordering = ['-fecha_dictamen']
verbose_name = 'Arbitraje en publicaciones académicas'
verbose_name_plural = 'Arbitrajes en publicaciones académicas'
class ArbitrajeProyectoInvestigacion(models.Model):
fecha = models.DateField()
descripcion = models.TextField(blank=True)
proyecto = models.ForeignKey(Proyecto)
participantes = models.ManyToManyField(User, related_name='arbitraje_proyecto_investigacion_participantes', blank=True)
tags = models.ManyToManyField(Tag, related_name='arbitraje_proyecto_investigacion_tags', blank=True)
def __str__(self):
return "{} : {}".format(str(self.proyecto), self.fecha)
class Meta:
ordering = ['-fecha']
verbose_name = 'Arbitraje de proyectos de investigación'
verbose_name_plural = 'Arbitrajes de proyectos de investigación'
class ArbitrajeOtrasActividades(models.Model):
actividad = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='actividad', unique=True)
descripcion = models.TextField(blank=True)
dependencia = models.ForeignKey(Dependencia)
fecha = models.DateField()
participantes = models.ManyToManyField(User, related_name='arbitraje_otras_actividades_participantes', blank=True)
tags = models.ManyToManyField(Tag, related_name='arbitraje_otras_actividades_tags', blank=True)
def __str__(self):
return "{} : {}".format(self.actividad, self.dependencia)
class Meta:
ordering = ['-fecha']
verbose_name = 'Arbitraje en otras actividades'
verbose_name_plural = 'Arbitraje en otras actividades'
class RedAcademica(models.Model):
nombre = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='nombre', unique=True)
descripcion = models.TextField(blank=True)
clasificacion = models.CharField(max_length=20, choices=RED_ACADEMICA__CLASIFICACION)
regiones = models.ManyToManyField(Region, related_name='red_academica_regiones', blank=True)
paises = models.ManyToManyField(Pais, related_name='red_academica_paises', blank=True)
objetivos = models.TextField()
fecha_constitucion = models.DateField()
vigente = models.BooleanField(default=False)
academicos = models.ManyToManyField(User, related_name='red_academica_academicos')
proyectos = models.ManyToManyField(Proyecto, related_name='red_academica_proyectos', blank=True)
tags = models.ManyToManyField(Tag, related_name='red_academica_tags', blank=True)
def __str__(self):
return "{} : {}".format(self.nombre, self.fecha_constitucion)
class Meta:
ordering = ['-fecha_constitucion']
verbose_name = 'Red académica'
verbose_name_plural = 'Redes académicas'
class ConvenioEntidadNoAcademica(models.Model):
nombre = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='nombre', unique=True)
descripcion = models.TextField(blank=True)
es_agradecimiento = models.BooleanField(blank=True)
clasificacion_entidad = models.CharField(max_length=20, choices=ENTIDAD_NO_ACADEMICA__CLASIFICACION)
dependencias = models.ManyToManyField(Dependencia, related_name='convenio_entidad_no_academica_dependencias')
objetivos = models.TextField()
fecha_inicio = models.DateField()
fecha_fin = models.DateField()
es_renovacion = models.BooleanField(default=False)
incluye_financiamiento = models.BooleanField(default=False)
tags = models.ManyToManyField(Tag, related_name='convenio_entidad_academica_tags', blank=True)
def __str__(self):
return "{} : {}".format(self.nombre, self.fecha_inicio)
class Meta:
ordering = ['-fecha_inicio']
verbose_name = 'Convenio con entidades no académicas'
verbose_name_plural = 'Convenios con entidades no académicas'
class ClasificacionServicio(models.Model):
nombre = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='nombre', unique=True)
descripcion = models.TextField(blank=True)
def __str__(self):
return self.nombre
class Meta:
verbose_name = 'Clasificación de servicio'
verbose_name_plural = 'Clasificaciones de servicios'
class ServicioExternoEntidadNoAcademica(models.Model):
nombre_servicio = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='nombre_servicio', unique=True)
clasificacion_servicio = models.ForeignKey(ClasificacionServicio)
descripcion = models.TextField(blank=True)
dependencia = models.ForeignKey(Dependencia)
clasificacion_entidad = models.CharField(max_length=20, choices=ENTIDAD_NO_ACADEMICA__CLASIFICACION)
fecha_inicio = models.DateField()
fecha_fin = models.DateField()
incluye_financiamiento = models.BooleanField(default=False)
tags = models.ManyToManyField(Tag, related_name='servicio_externo_entidad_academica_tags', blank=True)
def __str__(self):
return "{} : {}".format(self.nombre_servicio, self.fecha_inicio)
class Meta:
ordering = ['-fecha_inicio']
verbose_name = 'Servicio o asesoria externa a entidades no académicas'
verbose_name_plural = 'Servicios o asesorias externas a entidades no académicas'
class OtroProgramaVinculacion(models.Model):
nombre_servicio = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='nombre_servicio', unique=True)
fecha = models.DateField()
tipo = models.CharField(max_length=20, choices=(('VINCULLACION', 'Vinculación'), ('COLABORACION', 'Colaboración'), ('COOPERACION', 'Cooperación'), ('OTRO', 'Otro')))
descripcion = models.TextField()
dependencias = models.ManyToManyField(Dependencia)
resultados = models.TextField(blank=True)
tags = models.ManyToManyField(Tag, related_name='otro_programa_vinculacion_tags', blank=True)
def __str__(self):
return "{} : {}".format(self.nombre_servicio, self.fecha)
class Meta:
ordering = ['-fecha', 'nombre_servicio']
verbose_name = 'Otro programa o acción de vinculación, colaboración y/o cooperación'
verbose_name_plural = 'Otros programas o acciones de vinculación, colaboración y/o cooperación' | {"/apoyo_institucional/models.py": ["/nucleo/models.py"], "/experiencia_laboral/serializers.py": ["/experiencia_laboral/models.py"], "/vinculacion/admin.py": ["/vinculacion/models.py"], "/nucleo/serializers.py": ["/nucleo/models.py", "/formacion_academica/models.py"], "/formacion_academica/serializers.py": ["/formacion_academica/models.py"], "/formacion_recursos_humanos/admin.py": ["/formacion_recursos_humanos/models.py"], "/movilidad_academica/models.py": ["/nucleo/models.py", "/vinculacion/models.py"], "/difusion_cientifica/models.py": ["/nucleo/models.py"], "/experiencia_laboral/views.py": ["/experiencia_laboral/serializers.py"], "/nucleo/views.py": ["/nucleo/models.py", "/nucleo/serializers.py"], "/desarrollo_tecnologico/models.py": ["/nucleo/models.py"], "/formacion_academica/admin.py": ["/formacion_academica/models.py"], "/investigacion/admin.py": ["/investigacion/models.py"], "/difusion_cientifica/admin.py": ["/difusion_cientifica/models.py"], "/investigacion/models.py": ["/nucleo/models.py"], "/formacion_academica/models.py": ["/nucleo/models.py"], "/movilidad_academica/admin.py": ["/movilidad_academica/models.py"], "/geom/envolvente.py": ["/geom/funciones.py"], "/nucleo/admin.py": ["/nucleo/models.py"], "/vinculacion/models.py": ["/nucleo/models.py", "/investigacion/models.py"], "/divulgacion_cientifica/admin.py": ["/divulgacion_cientifica/models.py"], "/experiencia_laboral/models.py": ["/nucleo/models.py"], "/docencia/models.py": ["/nucleo/models.py", "/vinculacion/models.py", "/formacion_academica/models.py"], "/experiencia_laboral/admin.py": ["/experiencia_laboral/models.py"], "/desarrollo_tecnologico/admin.py": ["/desarrollo_tecnologico/models.py"], "/divulgacion_cientifica/models.py": ["/nucleo/models.py"], "/formacion_academica/views.py": ["/formacion_academica/serializers.py"], "/apoyo_institucional/admin.py": ["/apoyo_institucional/models.py"], "/formacion_recursos_humanos/models.py": ["/nucleo/models.py"], "/distinciones/models.py": ["/nucleo/models.py"]} |
61,076 | CIGAUNAM/SIA | refs/heads/master | /divulgacion_cientifica/admin.py | from django.contrib import admin
# Register your models here.
from . models import ArticuloDivulgacion, LibroDivulgacion, CapituloLibroDivulgacion, OrganizacionEvento, ParticipacionEvento, MedioDivulgacion, ProgramaRadioTelevisionInternet
admin.site.register(ArticuloDivulgacion)
admin.site.register(LibroDivulgacion)
admin.site.register(CapituloLibroDivulgacion)
admin.site.register(OrganizacionEvento)
admin.site.register(ParticipacionEvento)
admin.site.register(MedioDivulgacion)
admin.site.register(ProgramaRadioTelevisionInternet) | {"/apoyo_institucional/models.py": ["/nucleo/models.py"], "/experiencia_laboral/serializers.py": ["/experiencia_laboral/models.py"], "/vinculacion/admin.py": ["/vinculacion/models.py"], "/nucleo/serializers.py": ["/nucleo/models.py", "/formacion_academica/models.py"], "/formacion_academica/serializers.py": ["/formacion_academica/models.py"], "/formacion_recursos_humanos/admin.py": ["/formacion_recursos_humanos/models.py"], "/movilidad_academica/models.py": ["/nucleo/models.py", "/vinculacion/models.py"], "/difusion_cientifica/models.py": ["/nucleo/models.py"], "/experiencia_laboral/views.py": ["/experiencia_laboral/serializers.py"], "/nucleo/views.py": ["/nucleo/models.py", "/nucleo/serializers.py"], "/desarrollo_tecnologico/models.py": ["/nucleo/models.py"], "/formacion_academica/admin.py": ["/formacion_academica/models.py"], "/investigacion/admin.py": ["/investigacion/models.py"], "/difusion_cientifica/admin.py": ["/difusion_cientifica/models.py"], "/investigacion/models.py": ["/nucleo/models.py"], "/formacion_academica/models.py": ["/nucleo/models.py"], "/movilidad_academica/admin.py": ["/movilidad_academica/models.py"], "/geom/envolvente.py": ["/geom/funciones.py"], "/nucleo/admin.py": ["/nucleo/models.py"], "/vinculacion/models.py": ["/nucleo/models.py", "/investigacion/models.py"], "/divulgacion_cientifica/admin.py": ["/divulgacion_cientifica/models.py"], "/experiencia_laboral/models.py": ["/nucleo/models.py"], "/docencia/models.py": ["/nucleo/models.py", "/vinculacion/models.py", "/formacion_academica/models.py"], "/experiencia_laboral/admin.py": ["/experiencia_laboral/models.py"], "/desarrollo_tecnologico/admin.py": ["/desarrollo_tecnologico/models.py"], "/divulgacion_cientifica/models.py": ["/nucleo/models.py"], "/formacion_academica/views.py": ["/formacion_academica/serializers.py"], "/apoyo_institucional/admin.py": ["/apoyo_institucional/models.py"], "/formacion_recursos_humanos/models.py": ["/nucleo/models.py"], "/distinciones/models.py": ["/nucleo/models.py"]} |
61,077 | CIGAUNAM/SIA | refs/heads/master | /experiencia_laboral/models.py | from django.db import models
from nucleo.models import User, Tag, Cargo, Nombramiento, Dependencia
# Create your models here.
class ExperienciaLaboral(models.Model):
dependencia = models.ForeignKey(Dependencia)
nombramiento = models.ForeignKey(Nombramiento, blank=True, null=True)
es_nombramiento_definitivo = models.BooleanField(default=False)
cargo = models.ForeignKey(Cargo)
descripcion = models.TextField(blank=True)
fecha_inicio = models.DateField()
fecha_fin = models.DateField(blank=True, null=True)
usuario = models.ForeignKey(User)
tags = models.ManyToManyField(Tag, related_name='experiencia_laboral_tags', blank=True)
def __str__(self):
return "{} : {} : {}".format(self.usuario, self.dependencia, self.cargo)
class Meta:
ordering = ['fecha_inicio', 'dependencia']
verbose_name = "Experiencia Laboral"
verbose_name_plural = "Experiencias Laborales"
class LineaInvestigacion(models.Model):
linea_investigacion = models.CharField(max_length=255)
descripcion = models.TextField(blank=True)
dependencia = models.ForeignKey(Dependencia)
fecha_inicio = models.DateField()
fecha_fin = models.DateField(blank=True, null=True)
usuario = models.ForeignKey(User)
tags = models.ManyToManyField(Tag, related_name='linea_investigacion_tags', blank=True)
def __str__(self):
return "{} : {}".format(self.usuario, self.linea_investigacion)
class Meta:
ordering = ['fecha_inicio', 'linea_investigacion']
verbose_name = "Línea de investigación"
verbose_name_plural = "Líneas de investigación"
class CapacidadPotencialidad(models.Model):
competencia = models.CharField(max_length=255)
descripcion = models.TextField(blank=True)
fecha_inicio = models.DateField()
fecha_fin = models.DateField(blank=True, null=True)
usuario = models.ForeignKey(User)
tags = models.ManyToManyField(Tag, related_name='capacidad_potencialidad_tags', blank=True)
def __str__(self):
return "{} : {}".format(self.usuario, self.competencia)
class Meta:
ordering = ['competencia']
verbose_name = "Capacidad y potencialid"
verbose_name_plural = "Capacidades y potencialidades" | {"/apoyo_institucional/models.py": ["/nucleo/models.py"], "/experiencia_laboral/serializers.py": ["/experiencia_laboral/models.py"], "/vinculacion/admin.py": ["/vinculacion/models.py"], "/nucleo/serializers.py": ["/nucleo/models.py", "/formacion_academica/models.py"], "/formacion_academica/serializers.py": ["/formacion_academica/models.py"], "/formacion_recursos_humanos/admin.py": ["/formacion_recursos_humanos/models.py"], "/movilidad_academica/models.py": ["/nucleo/models.py", "/vinculacion/models.py"], "/difusion_cientifica/models.py": ["/nucleo/models.py"], "/experiencia_laboral/views.py": ["/experiencia_laboral/serializers.py"], "/nucleo/views.py": ["/nucleo/models.py", "/nucleo/serializers.py"], "/desarrollo_tecnologico/models.py": ["/nucleo/models.py"], "/formacion_academica/admin.py": ["/formacion_academica/models.py"], "/investigacion/admin.py": ["/investigacion/models.py"], "/difusion_cientifica/admin.py": ["/difusion_cientifica/models.py"], "/investigacion/models.py": ["/nucleo/models.py"], "/formacion_academica/models.py": ["/nucleo/models.py"], "/movilidad_academica/admin.py": ["/movilidad_academica/models.py"], "/geom/envolvente.py": ["/geom/funciones.py"], "/nucleo/admin.py": ["/nucleo/models.py"], "/vinculacion/models.py": ["/nucleo/models.py", "/investigacion/models.py"], "/divulgacion_cientifica/admin.py": ["/divulgacion_cientifica/models.py"], "/experiencia_laboral/models.py": ["/nucleo/models.py"], "/docencia/models.py": ["/nucleo/models.py", "/vinculacion/models.py", "/formacion_academica/models.py"], "/experiencia_laboral/admin.py": ["/experiencia_laboral/models.py"], "/desarrollo_tecnologico/admin.py": ["/desarrollo_tecnologico/models.py"], "/divulgacion_cientifica/models.py": ["/nucleo/models.py"], "/formacion_academica/views.py": ["/formacion_academica/serializers.py"], "/apoyo_institucional/admin.py": ["/apoyo_institucional/models.py"], "/formacion_recursos_humanos/models.py": ["/nucleo/models.py"], "/distinciones/models.py": ["/nucleo/models.py"]} |
61,078 | CIGAUNAM/SIA | refs/heads/master | /docencia/models.py | from django.db import models
#from django.contrib.auth.models import User
from autoslug import AutoSlugField
from nucleo.models import User, Tag, Dependencia, Proyecto
from vinculacion.models import RedAcademica
from formacion_academica.models import Licenciatura, Maestria, Doctorado
# Create your models here.
class Asignatura(models.Model):
asignatura = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='asignatura', unique=True)
descripcion = models.TextField(blank=True)
def __str__(self):
return self.asignatura
class Curso(models.Model):
nivel = models.CharField(max_length=30, choices=(('LICENCIATURA', 'Licenciatura'), ('MAESTRIA', 'Maestría'), ('DOCTORADO', 'Doctorado')))
tipo = models.CharField(max_length=20, choices=(('ESCOLARIZADO', 'Escolarizado'), ('EXTRACURRICULAR', 'Extracurricular')))
licenciatura = models.ForeignKey(Licenciatura)
maestria = models.ForeignKey(Maestria)
doctorado = models.ForeignKey(Doctorado)
asignatura = models.ForeignKey(Asignatura)
tipo = models.CharField(max_length=30, choices=(('PRESENCIAL', 'Presencial'), ('EN_LINEA', 'En línea')))
nivel_participacion = models.CharField(max_length=30, choices=(('TITULAR', 'Titular / Responsable'), ('COLABORADOR', 'Colaborador / Invitado')))
dependencia = models.ForeignKey(Dependencia)
fecha_inicio = models.DateField()
fecha_fin = models.DateField()
total_horas = models.PositiveIntegerField()
docente = models.ForeignKey(User, related_name='curso_escolarizado_docente')
otros_academicos = models.ManyToManyField(User, related_name='curso_escolarizado_otros_academicos', blank=True)
otras_dependencias_participantes = models.ManyToManyField(User, related_name='curso_escolarizado_otras_dependencias_participantes', blank=True)
def __str__(self):
return "{} : {} : {}".format(self.asignatura, str(self.dependencia.dependencia), self.fecha_inicio)
class Meta:
ordering = ['-fecha_inicio']
verbose_name = 'Curso'
verbose_name_plural = 'Cursos'
| {"/apoyo_institucional/models.py": ["/nucleo/models.py"], "/experiencia_laboral/serializers.py": ["/experiencia_laboral/models.py"], "/vinculacion/admin.py": ["/vinculacion/models.py"], "/nucleo/serializers.py": ["/nucleo/models.py", "/formacion_academica/models.py"], "/formacion_academica/serializers.py": ["/formacion_academica/models.py"], "/formacion_recursos_humanos/admin.py": ["/formacion_recursos_humanos/models.py"], "/movilidad_academica/models.py": ["/nucleo/models.py", "/vinculacion/models.py"], "/difusion_cientifica/models.py": ["/nucleo/models.py"], "/experiencia_laboral/views.py": ["/experiencia_laboral/serializers.py"], "/nucleo/views.py": ["/nucleo/models.py", "/nucleo/serializers.py"], "/desarrollo_tecnologico/models.py": ["/nucleo/models.py"], "/formacion_academica/admin.py": ["/formacion_academica/models.py"], "/investigacion/admin.py": ["/investigacion/models.py"], "/difusion_cientifica/admin.py": ["/difusion_cientifica/models.py"], "/investigacion/models.py": ["/nucleo/models.py"], "/formacion_academica/models.py": ["/nucleo/models.py"], "/movilidad_academica/admin.py": ["/movilidad_academica/models.py"], "/geom/envolvente.py": ["/geom/funciones.py"], "/nucleo/admin.py": ["/nucleo/models.py"], "/vinculacion/models.py": ["/nucleo/models.py", "/investigacion/models.py"], "/divulgacion_cientifica/admin.py": ["/divulgacion_cientifica/models.py"], "/experiencia_laboral/models.py": ["/nucleo/models.py"], "/docencia/models.py": ["/nucleo/models.py", "/vinculacion/models.py", "/formacion_academica/models.py"], "/experiencia_laboral/admin.py": ["/experiencia_laboral/models.py"], "/desarrollo_tecnologico/admin.py": ["/desarrollo_tecnologico/models.py"], "/divulgacion_cientifica/models.py": ["/nucleo/models.py"], "/formacion_academica/views.py": ["/formacion_academica/serializers.py"], "/apoyo_institucional/admin.py": ["/apoyo_institucional/models.py"], "/formacion_recursos_humanos/models.py": ["/nucleo/models.py"], "/distinciones/models.py": ["/nucleo/models.py"]} |
61,079 | CIGAUNAM/SIA | refs/heads/master | /experiencia_laboral/admin.py | from django.contrib import admin
# Register your models here.
from . models import ExperienciaLaboral, LineaInvestigacion, CapacidadPotencialidad
admin.site.register(ExperienciaLaboral)
admin.site.register(LineaInvestigacion)
admin.site.register(CapacidadPotencialidad)
| {"/apoyo_institucional/models.py": ["/nucleo/models.py"], "/experiencia_laboral/serializers.py": ["/experiencia_laboral/models.py"], "/vinculacion/admin.py": ["/vinculacion/models.py"], "/nucleo/serializers.py": ["/nucleo/models.py", "/formacion_academica/models.py"], "/formacion_academica/serializers.py": ["/formacion_academica/models.py"], "/formacion_recursos_humanos/admin.py": ["/formacion_recursos_humanos/models.py"], "/movilidad_academica/models.py": ["/nucleo/models.py", "/vinculacion/models.py"], "/difusion_cientifica/models.py": ["/nucleo/models.py"], "/experiencia_laboral/views.py": ["/experiencia_laboral/serializers.py"], "/nucleo/views.py": ["/nucleo/models.py", "/nucleo/serializers.py"], "/desarrollo_tecnologico/models.py": ["/nucleo/models.py"], "/formacion_academica/admin.py": ["/formacion_academica/models.py"], "/investigacion/admin.py": ["/investigacion/models.py"], "/difusion_cientifica/admin.py": ["/difusion_cientifica/models.py"], "/investigacion/models.py": ["/nucleo/models.py"], "/formacion_academica/models.py": ["/nucleo/models.py"], "/movilidad_academica/admin.py": ["/movilidad_academica/models.py"], "/geom/envolvente.py": ["/geom/funciones.py"], "/nucleo/admin.py": ["/nucleo/models.py"], "/vinculacion/models.py": ["/nucleo/models.py", "/investigacion/models.py"], "/divulgacion_cientifica/admin.py": ["/divulgacion_cientifica/models.py"], "/experiencia_laboral/models.py": ["/nucleo/models.py"], "/docencia/models.py": ["/nucleo/models.py", "/vinculacion/models.py", "/formacion_academica/models.py"], "/experiencia_laboral/admin.py": ["/experiencia_laboral/models.py"], "/desarrollo_tecnologico/admin.py": ["/desarrollo_tecnologico/models.py"], "/divulgacion_cientifica/models.py": ["/nucleo/models.py"], "/formacion_academica/views.py": ["/formacion_academica/serializers.py"], "/apoyo_institucional/admin.py": ["/apoyo_institucional/models.py"], "/formacion_recursos_humanos/models.py": ["/nucleo/models.py"], "/distinciones/models.py": ["/nucleo/models.py"]} |
61,080 | CIGAUNAM/SIA | refs/heads/master | /distinciones/apps.py | from django.apps import AppConfig
class DistincionesConfig(AppConfig):
name = 'distinciones'
| {"/apoyo_institucional/models.py": ["/nucleo/models.py"], "/experiencia_laboral/serializers.py": ["/experiencia_laboral/models.py"], "/vinculacion/admin.py": ["/vinculacion/models.py"], "/nucleo/serializers.py": ["/nucleo/models.py", "/formacion_academica/models.py"], "/formacion_academica/serializers.py": ["/formacion_academica/models.py"], "/formacion_recursos_humanos/admin.py": ["/formacion_recursos_humanos/models.py"], "/movilidad_academica/models.py": ["/nucleo/models.py", "/vinculacion/models.py"], "/difusion_cientifica/models.py": ["/nucleo/models.py"], "/experiencia_laboral/views.py": ["/experiencia_laboral/serializers.py"], "/nucleo/views.py": ["/nucleo/models.py", "/nucleo/serializers.py"], "/desarrollo_tecnologico/models.py": ["/nucleo/models.py"], "/formacion_academica/admin.py": ["/formacion_academica/models.py"], "/investigacion/admin.py": ["/investigacion/models.py"], "/difusion_cientifica/admin.py": ["/difusion_cientifica/models.py"], "/investigacion/models.py": ["/nucleo/models.py"], "/formacion_academica/models.py": ["/nucleo/models.py"], "/movilidad_academica/admin.py": ["/movilidad_academica/models.py"], "/geom/envolvente.py": ["/geom/funciones.py"], "/nucleo/admin.py": ["/nucleo/models.py"], "/vinculacion/models.py": ["/nucleo/models.py", "/investigacion/models.py"], "/divulgacion_cientifica/admin.py": ["/divulgacion_cientifica/models.py"], "/experiencia_laboral/models.py": ["/nucleo/models.py"], "/docencia/models.py": ["/nucleo/models.py", "/vinculacion/models.py", "/formacion_academica/models.py"], "/experiencia_laboral/admin.py": ["/experiencia_laboral/models.py"], "/desarrollo_tecnologico/admin.py": ["/desarrollo_tecnologico/models.py"], "/divulgacion_cientifica/models.py": ["/nucleo/models.py"], "/formacion_academica/views.py": ["/formacion_academica/serializers.py"], "/apoyo_institucional/admin.py": ["/apoyo_institucional/models.py"], "/formacion_recursos_humanos/models.py": ["/nucleo/models.py"], "/distinciones/models.py": ["/nucleo/models.py"]} |
61,081 | CIGAUNAM/SIA | refs/heads/master | /desarrollo_tecnologico/admin.py | from django.contrib import admin
# Register your models here.
from . models import TipoDesarrollo, Licencia, DesarrolloTecnologico
admin.site.register(TipoDesarrollo)
admin.site.register(Licencia)
admin.site.register(DesarrolloTecnologico) | {"/apoyo_institucional/models.py": ["/nucleo/models.py"], "/experiencia_laboral/serializers.py": ["/experiencia_laboral/models.py"], "/vinculacion/admin.py": ["/vinculacion/models.py"], "/nucleo/serializers.py": ["/nucleo/models.py", "/formacion_academica/models.py"], "/formacion_academica/serializers.py": ["/formacion_academica/models.py"], "/formacion_recursos_humanos/admin.py": ["/formacion_recursos_humanos/models.py"], "/movilidad_academica/models.py": ["/nucleo/models.py", "/vinculacion/models.py"], "/difusion_cientifica/models.py": ["/nucleo/models.py"], "/experiencia_laboral/views.py": ["/experiencia_laboral/serializers.py"], "/nucleo/views.py": ["/nucleo/models.py", "/nucleo/serializers.py"], "/desarrollo_tecnologico/models.py": ["/nucleo/models.py"], "/formacion_academica/admin.py": ["/formacion_academica/models.py"], "/investigacion/admin.py": ["/investigacion/models.py"], "/difusion_cientifica/admin.py": ["/difusion_cientifica/models.py"], "/investigacion/models.py": ["/nucleo/models.py"], "/formacion_academica/models.py": ["/nucleo/models.py"], "/movilidad_academica/admin.py": ["/movilidad_academica/models.py"], "/geom/envolvente.py": ["/geom/funciones.py"], "/nucleo/admin.py": ["/nucleo/models.py"], "/vinculacion/models.py": ["/nucleo/models.py", "/investigacion/models.py"], "/divulgacion_cientifica/admin.py": ["/divulgacion_cientifica/models.py"], "/experiencia_laboral/models.py": ["/nucleo/models.py"], "/docencia/models.py": ["/nucleo/models.py", "/vinculacion/models.py", "/formacion_academica/models.py"], "/experiencia_laboral/admin.py": ["/experiencia_laboral/models.py"], "/desarrollo_tecnologico/admin.py": ["/desarrollo_tecnologico/models.py"], "/divulgacion_cientifica/models.py": ["/nucleo/models.py"], "/formacion_academica/views.py": ["/formacion_academica/serializers.py"], "/apoyo_institucional/admin.py": ["/apoyo_institucional/models.py"], "/formacion_recursos_humanos/models.py": ["/nucleo/models.py"], "/distinciones/models.py": ["/nucleo/models.py"]} |
61,082 | CIGAUNAM/SIA | refs/heads/master | /divulgacion_cientifica/models.py | from django.db import models
from django.conf import settings
#from django.contrib.auth.models import User
from autoslug import AutoSlugField
from nucleo.models import User, Tag, Pais, Ciudad, Ubicacion, Proyecto, TipoEvento, Evento, Libro, Revista, Indice
EVENTO__AMBITO = getattr(settings, 'EVENTO__AMBITO', (('INSTITUCIONAL', 'Institucional'), ('REGIONAL', 'Regional'), ('NACIONAL', 'Nacional'), ('INTERNACIONAL', 'Internacional'), ('OTRO', 'Otro')))
EVENTO__RESPONSABILIDAD = getattr(settings, 'EVENTO__RESPONSABILIDAD', (('COORDINADOR', 'Coordinador general'), ('COMITE', 'Comité organizador'), ('AYUDANTE', 'Ayudante'), ('TECNICO', 'Apoyo técnico'), ('OTRO', 'Otro')))
STATUS_PUBLICACION = getattr(settings, 'STATUS_PUBLICACION', (('PUBLICADO', 'Publicado'), ('EN_PRENSA', 'En prensa'), ('ACEPTADO', 'Aceptado'), ('ENVIADO', 'Enviado'), ('OTRO', 'Otro')))
# Create your models here.
class ArticuloDivulgacion(models.Model):
titulo = models.CharField(max_length=255, unique=True)
documento_articulo = models.FileField()
slug = AutoSlugField(populate_from='titulo', unique=True)
descripcion = models.TextField(blank=True)
tipo = models.CharField(max_length=16, choices=(('ARTICULO', 'Artículo'), ('ACTA', 'Acta'), ('CARTA', 'Carta'), ('RESENA', 'Reseña'), ('OTRO', 'Otro')))
revista = models.ForeignKey(Revista)
status = models.CharField(max_length=20, choices=STATUS_PUBLICACION)
indizado = models.BooleanField(default=False)
autores = models.ManyToManyField(User, related_name='articulo_divulgracion_autores')
alumnos = models.ManyToManyField(User, related_name='articulo_divulgracion_alumnos', blank=True)
indices = models.ManyToManyField(Indice, related_name='articulo_divulgracion_indices', blank=True)
solo_electronico = models.BooleanField(default=False)
url = models.URLField(blank=True)
fecha = models.DateField(auto_now=False)
volumen = models.CharField(max_length=100, blank=True)
numero = models.CharField(max_length=100, blank=True)
issn = models.CharField(max_length=30, blank=True)
pagina_inicio = models.PositiveIntegerField()
pagina_fin = models.PositiveIntegerField()
id_doi = models.CharField(max_length=100, blank=True)
proyectos = models.ManyToManyField(Proyecto, related_name='articulo_divulgracion_proyectos', blank=True)
tags = models.ManyToManyField(Tag, related_name='articulo_divulgacion_tags', blank=True)
def __str__(self):
return "{} : {} : {}".format(self.titulo, self.tipo.title(), self.revista)
class Meta:
verbose_name = "Artículo de divulgación"
verbose_name_plural = "Artículos de divulgación"
ordering = ['fecha', 'titulo']
class LibroDivulgacion(models.Model):
libro = models.ForeignKey(Libro)
slug = AutoSlugField(populate_from='libro', unique=True)
descripcion = models.TextField(blank=True)
#status = models.CharField(max_length=20, choices=STATUS_PUBLICACION)
proyectos = models.ManyToManyField(Proyecto, related_name='libro_divulgracion_proyectos', blank=True)
tags = models.ManyToManyField(Tag, related_name='libro_divulgacion_tags', blank=True)
def __str__(self):
return str(self.libro)
class Meta:
verbose_name = "Libro de divulgación"
verbose_name_plural = "Libro de divulgación"
ordering = ['libro']
class CapituloLibroDivulgacion(models.Model):
titulo = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='titulo', unique=True)
descripcion = models.TextField(blank=True)
libro = models.ForeignKey(Libro)
#status = models.CharField(max_length=20, choices=STATUS_PUBLICACION)
pagina_inicio = models.PositiveIntegerField()
pagina_fin = models.PositiveIntegerField()
proyectos = models.ManyToManyField(Proyecto, related_name='capitulo_libro_divulgracion_proyectos', blank=True)
tags = models.ManyToManyField(Tag, related_name='capitulo_libro_divulgacion_tags', blank=True)
def __str__(self):
return "{} : {}".format(self.titulo, self.libro)
class Meta:
verbose_name = "Capítulo en libro de divulgación"
verbose_name_plural = "Capítulos en libros de divulgración"
ordering = ['titulo']
class OrganizacionEvento(models.Model):
evento = models.ForeignKey(Evento)
descripcion = models.TextField(blank=True)
responsabilidad = models.CharField(max_length=30, choices=EVENTO__RESPONSABILIDAD)
numero_ponentes = models.PositiveIntegerField()
numero_asistentes = models.PositiveIntegerField()
ambito = models.CharField(max_length=20, choices=EVENTO__AMBITO)
tags = models.ManyToManyField(Tag, related_name='organizacion_evento_tags', blank=True)
def __str__(self):
return str(self.evento)
class Meta:
verbose_name = 'Organización de evento académico'
verbose_name_plural= 'Organización de eventos académicos'
class ParticipacionEvento(models.Model):
titulo = models.CharField(max_length=255)
slug = AutoSlugField(populate_from='titulo', unique=True)
descripcion = models.TextField(blank=True)
evento = models.ForeignKey(Evento)
resumen_publicado = models.BooleanField(default=False)
autores = models.ManyToManyField(User, related_name='participacion_evento_autores')
ambito = models.CharField(max_length=20, choices=EVENTO__AMBITO)
por_invitacion = models.BooleanField(default=False)
ponencia_magistral = models.BooleanField(default=False)
tags = models.ManyToManyField(Tag, related_name='participacion_evento_tags', blank=True)
def __str__(self):
return "{} : {}".format(self.titulo, self.evento)
class Meta:
verbose_name = 'Participación en evento académico'
verbose_name_plural= 'Participación en eventos académicos'
class MedioDivulgacion(models.Model):
nombre_medio = models.CharField(max_length=255, unique=True)
slug = AutoSlugField(populate_from='nombre_medio', unique=True)
descripcion = models.TextField(blank=True)
slug = AutoSlugField(populate_from='nombre_medio', unique=True)
canal = models.CharField(max_length=255)
ubicacion = models.ForeignKey(Ubicacion)
tags = models.ManyToManyField(Tag, related_name='medio_divulgacion_tags', blank=True)
def __str__(self):
return self.nombre_medio
class Meta:
unique_together = ['canal', 'nombre_medio']
ordering = ['nombre_medio']
verbose_name = "Medio de difusión para divulgación"
verbose_name_plural = "Medios de difusión para divulgación"
class ProgramaRadioTelevisionInternet(models.Model):
fecha = models.DateField()
tema = models.CharField(max_length=255)
descripcion = models.TextField(blank=True)
actividad = models.CharField(max_length=20, choices=(('PRODUCCION', 'Producciòn'), ('PARTICIPACION', 'Participaciòn'), ('ENTREVISTA', 'Entrevista'), ('OTRA', 'Otra')))
medio = models.CharField(max_length=20, choices=(('PERIODICO', 'Periódico'), ('RADIO', 'Radio'), ('TV', 'Televisión'), ('INTERNET', 'Internet'), ('OTRO', 'Otro')))
nombre_medio = models.ForeignKey(MedioDivulgacion)
partiticipantes = models.ManyToManyField(User, related_name='programa_radio_television_internet_participantes')
tags = models.ManyToManyField(Tag, related_name='programa_radio_television_internet_tags', blank=True)
def __str__(self):
return "{} : {} : {}".format(self.nombre_medio, self.tema, self.fecha)
class Meta:
ordering = ['fecha', 'tema']
verbose_name = 'Programa de radio, televisión o internet'
verbose_name_plural = 'Programas de radio, televisión o internet'
| {"/apoyo_institucional/models.py": ["/nucleo/models.py"], "/experiencia_laboral/serializers.py": ["/experiencia_laboral/models.py"], "/vinculacion/admin.py": ["/vinculacion/models.py"], "/nucleo/serializers.py": ["/nucleo/models.py", "/formacion_academica/models.py"], "/formacion_academica/serializers.py": ["/formacion_academica/models.py"], "/formacion_recursos_humanos/admin.py": ["/formacion_recursos_humanos/models.py"], "/movilidad_academica/models.py": ["/nucleo/models.py", "/vinculacion/models.py"], "/difusion_cientifica/models.py": ["/nucleo/models.py"], "/experiencia_laboral/views.py": ["/experiencia_laboral/serializers.py"], "/nucleo/views.py": ["/nucleo/models.py", "/nucleo/serializers.py"], "/desarrollo_tecnologico/models.py": ["/nucleo/models.py"], "/formacion_academica/admin.py": ["/formacion_academica/models.py"], "/investigacion/admin.py": ["/investigacion/models.py"], "/difusion_cientifica/admin.py": ["/difusion_cientifica/models.py"], "/investigacion/models.py": ["/nucleo/models.py"], "/formacion_academica/models.py": ["/nucleo/models.py"], "/movilidad_academica/admin.py": ["/movilidad_academica/models.py"], "/geom/envolvente.py": ["/geom/funciones.py"], "/nucleo/admin.py": ["/nucleo/models.py"], "/vinculacion/models.py": ["/nucleo/models.py", "/investigacion/models.py"], "/divulgacion_cientifica/admin.py": ["/divulgacion_cientifica/models.py"], "/experiencia_laboral/models.py": ["/nucleo/models.py"], "/docencia/models.py": ["/nucleo/models.py", "/vinculacion/models.py", "/formacion_academica/models.py"], "/experiencia_laboral/admin.py": ["/experiencia_laboral/models.py"], "/desarrollo_tecnologico/admin.py": ["/desarrollo_tecnologico/models.py"], "/divulgacion_cientifica/models.py": ["/nucleo/models.py"], "/formacion_academica/views.py": ["/formacion_academica/serializers.py"], "/apoyo_institucional/admin.py": ["/apoyo_institucional/models.py"], "/formacion_recursos_humanos/models.py": ["/nucleo/models.py"], "/distinciones/models.py": ["/nucleo/models.py"]} |
61,083 | CIGAUNAM/SIA | refs/heads/master | /formacion_academica/views.py | from django.shortcuts import render
from django.http.response import HttpResponse
from . permissions import IsOwnerOrReadOnly
from rest_framework import permissions
from formacion_academica.serializers import *
from rest_framework import generics
# Create your views here.
class CursoEspecializacionList(generics.ListCreateAPIView):
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly)
queryset = CursoEspecializacion.objects.all()
serializer_class = CursoEspecializacionSerializer
def perform_create(self, serializer):
serializer.save(usuario=self.request.user)
class CursoEspecializacionDetail(generics.RetrieveUpdateDestroyAPIView):
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly)
queryset = CursoEspecializacion.objects.all()
serializer_class = CursoEspecializacionSerializer
class LicenciaturaList(generics.ListCreateAPIView):
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly)
queryset = Licenciatura.objects.all()
serializer_class = LicenciaturaSerializer
def perform_create(self, serializer):
serializer.save(usuario=self.request.user)
class LicenciaturaDetail(generics.RetrieveUpdateDestroyAPIView):
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly)
queryset = Licenciatura.objects.all()
serializer_class = LicenciaturaSerializer
class MaestriaList(generics.ListCreateAPIView):
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly)
queryset = Maestria.objects.all()
serializer_class = MaestriaSerializer
def perform_create(self, serializer):
serializer.save(usuario=self.request.user)
class MaestriaDetail(generics.RetrieveUpdateDestroyAPIView):
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly)
queryset = Maestria.objects.all()
serializer_class = MaestriaSerializer
class DoctoradoList(generics.ListCreateAPIView):
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly)
queryset = Doctorado.objects.all()
serializer_class = DoctoradoSerializer
def perform_create(self, serializer):
serializer.save(usuario=self.request.user)
class DoctoradoDetail(generics.RetrieveUpdateDestroyAPIView):
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly)
queryset = Doctorado.objects.all()
serializer_class = DoctoradoSerializer
class PostDoctoradoList(generics.ListCreateAPIView):
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly)
queryset = PostDoctorado.objects.all()
serializer_class = PostDoctoradoSerializer
def perform_create(self, serializer):
serializer.save(usuario=self.request.user)
class PostDoctoradoDetail(generics.RetrieveUpdateDestroyAPIView):
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly)
queryset = PostDoctorado.objects.all()
serializer_class = PostDoctoradoSerializer | {"/apoyo_institucional/models.py": ["/nucleo/models.py"], "/experiencia_laboral/serializers.py": ["/experiencia_laboral/models.py"], "/vinculacion/admin.py": ["/vinculacion/models.py"], "/nucleo/serializers.py": ["/nucleo/models.py", "/formacion_academica/models.py"], "/formacion_academica/serializers.py": ["/formacion_academica/models.py"], "/formacion_recursos_humanos/admin.py": ["/formacion_recursos_humanos/models.py"], "/movilidad_academica/models.py": ["/nucleo/models.py", "/vinculacion/models.py"], "/difusion_cientifica/models.py": ["/nucleo/models.py"], "/experiencia_laboral/views.py": ["/experiencia_laboral/serializers.py"], "/nucleo/views.py": ["/nucleo/models.py", "/nucleo/serializers.py"], "/desarrollo_tecnologico/models.py": ["/nucleo/models.py"], "/formacion_academica/admin.py": ["/formacion_academica/models.py"], "/investigacion/admin.py": ["/investigacion/models.py"], "/difusion_cientifica/admin.py": ["/difusion_cientifica/models.py"], "/investigacion/models.py": ["/nucleo/models.py"], "/formacion_academica/models.py": ["/nucleo/models.py"], "/movilidad_academica/admin.py": ["/movilidad_academica/models.py"], "/geom/envolvente.py": ["/geom/funciones.py"], "/nucleo/admin.py": ["/nucleo/models.py"], "/vinculacion/models.py": ["/nucleo/models.py", "/investigacion/models.py"], "/divulgacion_cientifica/admin.py": ["/divulgacion_cientifica/models.py"], "/experiencia_laboral/models.py": ["/nucleo/models.py"], "/docencia/models.py": ["/nucleo/models.py", "/vinculacion/models.py", "/formacion_academica/models.py"], "/experiencia_laboral/admin.py": ["/experiencia_laboral/models.py"], "/desarrollo_tecnologico/admin.py": ["/desarrollo_tecnologico/models.py"], "/divulgacion_cientifica/models.py": ["/nucleo/models.py"], "/formacion_academica/views.py": ["/formacion_academica/serializers.py"], "/apoyo_institucional/admin.py": ["/apoyo_institucional/models.py"], "/formacion_recursos_humanos/models.py": ["/nucleo/models.py"], "/distinciones/models.py": ["/nucleo/models.py"]} |
61,084 | CIGAUNAM/SIA | refs/heads/master | /apoyo_institucional/admin.py | from django.contrib import admin
# Register your models here.
from . models import Actividad, Comision, Representacion, CargoAcademicoAdministrativo, \
RepresentanteAnteOrganoColegiado, ComisionAcademica, ApoyoTecnico, ApoyoOtraActividad
#OrganoColegiado, ComisionEvaluacion
admin.site.register(Actividad)
admin.site.register(Comision)
admin.site.register(Representacion)
#admin.site.register(OrganoColegiado)
admin.site.register(CargoAcademicoAdministrativo)
admin.site.register(RepresentanteAnteOrganoColegiado)
admin.site.register(ComisionAcademica)
#admin.site.register(ComisionEvaluacion)
admin.site.register(ApoyoTecnico)
admin.site.register(ApoyoOtraActividad)
| {"/apoyo_institucional/models.py": ["/nucleo/models.py"], "/experiencia_laboral/serializers.py": ["/experiencia_laboral/models.py"], "/vinculacion/admin.py": ["/vinculacion/models.py"], "/nucleo/serializers.py": ["/nucleo/models.py", "/formacion_academica/models.py"], "/formacion_academica/serializers.py": ["/formacion_academica/models.py"], "/formacion_recursos_humanos/admin.py": ["/formacion_recursos_humanos/models.py"], "/movilidad_academica/models.py": ["/nucleo/models.py", "/vinculacion/models.py"], "/difusion_cientifica/models.py": ["/nucleo/models.py"], "/experiencia_laboral/views.py": ["/experiencia_laboral/serializers.py"], "/nucleo/views.py": ["/nucleo/models.py", "/nucleo/serializers.py"], "/desarrollo_tecnologico/models.py": ["/nucleo/models.py"], "/formacion_academica/admin.py": ["/formacion_academica/models.py"], "/investigacion/admin.py": ["/investigacion/models.py"], "/difusion_cientifica/admin.py": ["/difusion_cientifica/models.py"], "/investigacion/models.py": ["/nucleo/models.py"], "/formacion_academica/models.py": ["/nucleo/models.py"], "/movilidad_academica/admin.py": ["/movilidad_academica/models.py"], "/geom/envolvente.py": ["/geom/funciones.py"], "/nucleo/admin.py": ["/nucleo/models.py"], "/vinculacion/models.py": ["/nucleo/models.py", "/investigacion/models.py"], "/divulgacion_cientifica/admin.py": ["/divulgacion_cientifica/models.py"], "/experiencia_laboral/models.py": ["/nucleo/models.py"], "/docencia/models.py": ["/nucleo/models.py", "/vinculacion/models.py", "/formacion_academica/models.py"], "/experiencia_laboral/admin.py": ["/experiencia_laboral/models.py"], "/desarrollo_tecnologico/admin.py": ["/desarrollo_tecnologico/models.py"], "/divulgacion_cientifica/models.py": ["/nucleo/models.py"], "/formacion_academica/views.py": ["/formacion_academica/serializers.py"], "/apoyo_institucional/admin.py": ["/apoyo_institucional/models.py"], "/formacion_recursos_humanos/models.py": ["/nucleo/models.py"], "/distinciones/models.py": ["/nucleo/models.py"]} |
61,085 | CIGAUNAM/SIA | refs/heads/master | /geom/funciones.py | from math import sqrt, pow, hypot, atan2, cos, sin, degrees, radians
from geom.geomcom import Punto2D
import sys
def dist(P, Q):
"""A math Point function to calculate the distance between 2 points."""
d = sqrt(pow(P.x - Q.x, 2) + pow(P.y - Q.y, 2))
return d
def mid_point(P, Q):
"""A math Point function to calculate the mid point between 2 points."""
R = (1. / 2.) * (P + Q)
return R
def translate2D(P, tx, ty):
"""A math Point function to calculate a tx, ty translation of a point
If you put translate((1,2), -2, 3), the function calculate a point with -2
x-coordinate and +3 y-coordinate, i.e., the point is (-1,5). The function
calculates for a 2D Point."""
R = Punto2D()
R.x = P.x + tx
R.y = P.y + ty
return R
def translate3D(P, tx, ty):
"""A math Point function to calculate a tx, ty, tz translation of a point
If you put translate((1,2), -2, 3, 4), the function calculate a point with
-2 x-coordinate, +3 y-coordinate and +4 z-coordinate, i.e., the point is
(-1,5). The function calculates for a 3D Point."""
R = Punto2D()
R.x = P.x + tx
R.y = P.y + ty
return R
def incenter(A, B, C):
"""A math Point function to calculate the Incenter Point in a triangle."""
I = Punto2D()
a = dist(B, C)
b = dist(A, C)
c = dist(A, B)
sumd=a + b + c
I = (a / sumd) * A + (b / sumd) * B + (c / sumd) * C
return I
def rect2pol(P):
"""A math point function to calculate the polar coordinates of a point in
rectangular points."""
R = Punto2D()
R.x = hypot(P.x, P.y)
R.y = atan2(P.y, P.x)
return (R)
def rect2poldeg(P):
"""A math point function to calculate the polar coordinates of a point in
rectangular points. In sexagesimal degrees."""
R = Punto2D()
R.x = hypot(P.x, P.y)
R.y = degrees(atan2(P.y, P.x))
return (R)
def pol2rect(P):
"""A math point function to calculate the rectangular coordinates of a
point in polar coordinates."""
R = Punto2D()
if P.x <= 0:
raise ValueError('The radius must be > 0')
R.x = P.x * cos(P.y)
R.y = P.x * sin(P.y)
return (R)
def pol2rectdeg(P):
"""A math point function to calculate the rectangular coordinates of a
point in polar coordinates. In sexagesimal degrees."""
R = Punto2D()
if P.x <= 0:
raise ValueError('The radius must be > 0')
R.x = P.x * cos(radians(P.y))
R.y = P.x * sin(radians(P.y))
return (R)
def rect2cyl(P):
"""A math point function to calculate the cilindrical coordinates of a
point in rectangular coordinates."""
R = Punto2D()
R.x = hypot(P.x, P.y)
R.y = atan2(P.y, P.x)
return (R)
def rect2cyldeg(P):
"""A math point function to calculate the cilindrical coordinates of a
point in rectangular coordinates. In sexagesimal degrees."""
R = Punto2D()
R.x = hypot(P.x, P.y)
R.y = degrees(atan2(P.y, P.x))
return (R)
def cyl2rect(P):
"""A math point function to calculate the rectangular coordinates of a
point in cilindrical coordinates."""
R = Punto2D()
if P.x <= 0:
raise ValueError('The radius must be > 0')
R.x = P.x * cos(P.y)
R.y = P.x * sin(P.y)
return (R)
def cyl2rectdeg(P):
"""A math point function to calculate the rectangular coordinates of a
point in cilindrical coordinates. In sexagesimal degrees."""
R = Punto2D()
if P.x <= 0:
raise ValueError('The radius must be > 0')
R.x = P.x * cos(radians(P.y))
R.y = P.x * sin(radians(P.y))
return (R)
def input_point(P):
"""A method when the user of a terminal can input a point with 2 or 3
coordinates. The user must write (1,2,3) or (1,2), for instance."""
print(('Enter a point (x,y):'))
point = sys.stdin.readline()
point = point.replace('(', '')
point = point.replace(')', '')
l1 = point.rsplit(',')
P.x = float(l1[0])
P.y = float(l1[1])
#if len(l1) == 3:
# P.z = float(l1[2])
l1 = []
def is_to_the_left_of_line(X, A, B):
C = B - A
P = X - A
if C.x * P.y > C.y * P.x:
return True
else:
return False
| {"/apoyo_institucional/models.py": ["/nucleo/models.py"], "/experiencia_laboral/serializers.py": ["/experiencia_laboral/models.py"], "/vinculacion/admin.py": ["/vinculacion/models.py"], "/nucleo/serializers.py": ["/nucleo/models.py", "/formacion_academica/models.py"], "/formacion_academica/serializers.py": ["/formacion_academica/models.py"], "/formacion_recursos_humanos/admin.py": ["/formacion_recursos_humanos/models.py"], "/movilidad_academica/models.py": ["/nucleo/models.py", "/vinculacion/models.py"], "/difusion_cientifica/models.py": ["/nucleo/models.py"], "/experiencia_laboral/views.py": ["/experiencia_laboral/serializers.py"], "/nucleo/views.py": ["/nucleo/models.py", "/nucleo/serializers.py"], "/desarrollo_tecnologico/models.py": ["/nucleo/models.py"], "/formacion_academica/admin.py": ["/formacion_academica/models.py"], "/investigacion/admin.py": ["/investigacion/models.py"], "/difusion_cientifica/admin.py": ["/difusion_cientifica/models.py"], "/investigacion/models.py": ["/nucleo/models.py"], "/formacion_academica/models.py": ["/nucleo/models.py"], "/movilidad_academica/admin.py": ["/movilidad_academica/models.py"], "/geom/envolvente.py": ["/geom/funciones.py"], "/nucleo/admin.py": ["/nucleo/models.py"], "/vinculacion/models.py": ["/nucleo/models.py", "/investigacion/models.py"], "/divulgacion_cientifica/admin.py": ["/divulgacion_cientifica/models.py"], "/experiencia_laboral/models.py": ["/nucleo/models.py"], "/docencia/models.py": ["/nucleo/models.py", "/vinculacion/models.py", "/formacion_academica/models.py"], "/experiencia_laboral/admin.py": ["/experiencia_laboral/models.py"], "/desarrollo_tecnologico/admin.py": ["/desarrollo_tecnologico/models.py"], "/divulgacion_cientifica/models.py": ["/nucleo/models.py"], "/formacion_academica/views.py": ["/formacion_academica/serializers.py"], "/apoyo_institucional/admin.py": ["/apoyo_institucional/models.py"], "/formacion_recursos_humanos/models.py": ["/nucleo/models.py"], "/distinciones/models.py": ["/nucleo/models.py"]} |
61,086 | CIGAUNAM/SIA | refs/heads/master | /formacion_recursos_humanos/models.py | from django.db import models
from django.conf import settings
from nucleo.models import User, Tag, Dependencia, Beca, Proyecto, Tesis, ProgramaLicenciatura, ProgramaMaestria, ProgramaDoctorado
GRADO_ACADEMICO = getattr(settings, 'GRADO_ACADEMICO', (('LICENCIATURA', 'licenciatura'), ('MAESTRIA', 'Maestría'), ('DOCTORADO', 'Doctorado')))
# Create your models here.
class AsesorEstancia(models.Model):
descripcion = models.TextField(blank=True)
asesor = models.ForeignKey(User, related_name='asesor_estancia_asesor')
tipo = models.CharField(max_length=30, choices=(('RESIDENCIA', 'Residencia'), ('PRACTICA', 'Práctica'), ('ESTANCIA', 'Estancia'), ('SERVICIO_SOCIAL', 'Servicio Social'), ('OTRO', 'Otro')))
asesorado = models.ForeignKey(User, related_name='asesor_estancia_asesorado')
grado_academico = models.CharField(max_length=20, choices=GRADO_ACADEMICO)
beca = models.ForeignKey(Beca)
proyecto = models.ForeignKey(Proyecto)
programa_licenciatura = models.ForeignKey(ProgramaLicenciatura)
programa_maestria = models.ForeignKey(ProgramaMaestria)
programa_doctorado = models.ForeignKey(ProgramaDoctorado)
dependencia = models.ForeignKey(Dependencia)
fecha_inicio = models.DateField()
fecha_fin = models.DateField()
def __str__(self):
return "{} : {} : {}".format(str(self.asesor), str(self.asesorado), self.fecha_inicio)
class Meta:
ordering = ['-fecha_inicio', '-fecha_fin']
verbose_name = 'Asesor en residencias / prácticas / estancias / servicio social'
verbose_name_plural = 'Asesores en residencias / prácticas / estancias / servicio social'
class DireccionTesis(models.Model):
asesor = models.ForeignKey(User, related_name='direccion_tesis_asesor')
fecha_inicio = models.DateField()
tesis = models.ForeignKey(Tesis)
def __str__(self):
return "{} : {} : {}".format(self.tesis, self.asesor, self.fecha_inicio)
class Meta:
ordering = ['-fecha_inicio']
verbose_name = 'Dirección de tesis'
verbose_name_plural = 'Direcciones de tesis'
class ComiteTutoral(models.Model):
grado_academico = models.CharField(max_length=20, choices=GRADO_ACADEMICO)
status = models.CharField(max_length=20, choices=(('EN_PROCESO', 'En proceso'), ('CONCLUIDO', 'Concluído')))
fecha_inicio = models.DateField()
fecha_fin = models.DateField()
alumno = models.ForeignKey(User, related_name='comite_tutoral_alumno')
asesor_principal = models.ForeignKey(User, related_name='comite_tutoral_asesor_principal')
otros_asesores = models.ManyToManyField(User, related_name='comite_tutoral_otros_asesores', blank=True)
sinodales = models.ManyToManyField(User, related_name='comite_tutoral_sinodales', blank=True)
proyecto = models.ForeignKey(Proyecto)
programa_maestria = models.ForeignKey(ProgramaMaestria)
programa_doctorado = models.ForeignKey(ProgramaDoctorado)
dependencia = models.ForeignKey(Dependencia)
def __str__(self):
return "{} : {} : {}".format(str(self.alumno), self.fecha_inicio, str(self.asesor_principal))
class Meta:
ordering = ['-fecha_inicio']
verbose_name = 'Comité tutoral'
verbose_name_plural = 'Comités tutorales'
class ComiteCandidaturaDoctoral(models.Model):
fecha_defensa = models.DateField()
alumno = models.ForeignKey(User, related_name='comite_candidatura_doctoral_alumno')
asesor_principal = models.ForeignKey(User, related_name='comite_candidatura_doctoral_asesor_principal')
otros_asesores = models.ManyToManyField(User, related_name='comite_candidatura_doctoral_otros_asesores', blank=True)
sinodales = models.ManyToManyField(User, related_name='comite_candidatura_doctoral_sinodales', blank=True)
proyecto = models.ForeignKey(Proyecto)
programa_doctorado = models.ForeignKey(ProgramaDoctorado)
dependencia = models.ForeignKey(Dependencia)
def __str__(self):
return "{} : {} : {}".format(str(self.alumno), self.fecha_defensa, str(self.asesor_principal))
class Meta:
ordering = ['-fecha_defensa']
verbose_name = 'Comité de examen de candidatura doctoral'
verbose_name_plural = 'Comités de exámenes de candidatura doctoral'
| {"/apoyo_institucional/models.py": ["/nucleo/models.py"], "/experiencia_laboral/serializers.py": ["/experiencia_laboral/models.py"], "/vinculacion/admin.py": ["/vinculacion/models.py"], "/nucleo/serializers.py": ["/nucleo/models.py", "/formacion_academica/models.py"], "/formacion_academica/serializers.py": ["/formacion_academica/models.py"], "/formacion_recursos_humanos/admin.py": ["/formacion_recursos_humanos/models.py"], "/movilidad_academica/models.py": ["/nucleo/models.py", "/vinculacion/models.py"], "/difusion_cientifica/models.py": ["/nucleo/models.py"], "/experiencia_laboral/views.py": ["/experiencia_laboral/serializers.py"], "/nucleo/views.py": ["/nucleo/models.py", "/nucleo/serializers.py"], "/desarrollo_tecnologico/models.py": ["/nucleo/models.py"], "/formacion_academica/admin.py": ["/formacion_academica/models.py"], "/investigacion/admin.py": ["/investigacion/models.py"], "/difusion_cientifica/admin.py": ["/difusion_cientifica/models.py"], "/investigacion/models.py": ["/nucleo/models.py"], "/formacion_academica/models.py": ["/nucleo/models.py"], "/movilidad_academica/admin.py": ["/movilidad_academica/models.py"], "/geom/envolvente.py": ["/geom/funciones.py"], "/nucleo/admin.py": ["/nucleo/models.py"], "/vinculacion/models.py": ["/nucleo/models.py", "/investigacion/models.py"], "/divulgacion_cientifica/admin.py": ["/divulgacion_cientifica/models.py"], "/experiencia_laboral/models.py": ["/nucleo/models.py"], "/docencia/models.py": ["/nucleo/models.py", "/vinculacion/models.py", "/formacion_academica/models.py"], "/experiencia_laboral/admin.py": ["/experiencia_laboral/models.py"], "/desarrollo_tecnologico/admin.py": ["/desarrollo_tecnologico/models.py"], "/divulgacion_cientifica/models.py": ["/nucleo/models.py"], "/formacion_academica/views.py": ["/formacion_academica/serializers.py"], "/apoyo_institucional/admin.py": ["/apoyo_institucional/models.py"], "/formacion_recursos_humanos/models.py": ["/nucleo/models.py"], "/distinciones/models.py": ["/nucleo/models.py"]} |
61,087 | CIGAUNAM/SIA | refs/heads/master | /distinciones/models.py | from django.db import models
from django.conf import settings
#from django.contrib.auth.models import User
from autoslug import AutoSlugField
from nucleo.models import User, Dependencia, Distincion
EVENTO__AMBITO = getattr(settings, 'EVENTO__AMBITO', (('INSTITUCIONAL', 'Institucional'), ('REGIONAL', 'Regional'), ('NACIONAL', 'Nacional'), ('INTERNACIONAL', 'Internacional'), ('OTRO', 'Otro')))
# Create your models here.
class DistincionObtenida(models.Model):
fecha = models.DateField()
distincion = models.ForeignKey(Distincion)
descripcion = models.TextField(blank=True)
condecorados = models.ManyToManyField(User, related_name='_condecorados')
otorga = models.ForeignKey(Dependencia)
ambito = models.CharField(max_length=20, choices=EVENTO__AMBITO)
def __str__(self):
return "{} : {}".format(self.distincion, self.fecha)
class Meta:
ordering = ['-fecha']
verbose_name = 'Distinción recibida'
verbose_name_plural = 'Distinciones recibidas'
from cms.models import permissionmodels | {"/apoyo_institucional/models.py": ["/nucleo/models.py"], "/experiencia_laboral/serializers.py": ["/experiencia_laboral/models.py"], "/vinculacion/admin.py": ["/vinculacion/models.py"], "/nucleo/serializers.py": ["/nucleo/models.py", "/formacion_academica/models.py"], "/formacion_academica/serializers.py": ["/formacion_academica/models.py"], "/formacion_recursos_humanos/admin.py": ["/formacion_recursos_humanos/models.py"], "/movilidad_academica/models.py": ["/nucleo/models.py", "/vinculacion/models.py"], "/difusion_cientifica/models.py": ["/nucleo/models.py"], "/experiencia_laboral/views.py": ["/experiencia_laboral/serializers.py"], "/nucleo/views.py": ["/nucleo/models.py", "/nucleo/serializers.py"], "/desarrollo_tecnologico/models.py": ["/nucleo/models.py"], "/formacion_academica/admin.py": ["/formacion_academica/models.py"], "/investigacion/admin.py": ["/investigacion/models.py"], "/difusion_cientifica/admin.py": ["/difusion_cientifica/models.py"], "/investigacion/models.py": ["/nucleo/models.py"], "/formacion_academica/models.py": ["/nucleo/models.py"], "/movilidad_academica/admin.py": ["/movilidad_academica/models.py"], "/geom/envolvente.py": ["/geom/funciones.py"], "/nucleo/admin.py": ["/nucleo/models.py"], "/vinculacion/models.py": ["/nucleo/models.py", "/investigacion/models.py"], "/divulgacion_cientifica/admin.py": ["/divulgacion_cientifica/models.py"], "/experiencia_laboral/models.py": ["/nucleo/models.py"], "/docencia/models.py": ["/nucleo/models.py", "/vinculacion/models.py", "/formacion_academica/models.py"], "/experiencia_laboral/admin.py": ["/experiencia_laboral/models.py"], "/desarrollo_tecnologico/admin.py": ["/desarrollo_tecnologico/models.py"], "/divulgacion_cientifica/models.py": ["/nucleo/models.py"], "/formacion_academica/views.py": ["/formacion_academica/serializers.py"], "/apoyo_institucional/admin.py": ["/apoyo_institucional/models.py"], "/formacion_recursos_humanos/models.py": ["/nucleo/models.py"], "/distinciones/models.py": ["/nucleo/models.py"]} |
61,088 | CIGAUNAM/SIA | refs/heads/master | /apoyo_institucional/apps.py | from django.apps import AppConfig
class ApoyoInstitucionalConfig(AppConfig):
name = 'apoyo_institucional'
| {"/apoyo_institucional/models.py": ["/nucleo/models.py"], "/experiencia_laboral/serializers.py": ["/experiencia_laboral/models.py"], "/vinculacion/admin.py": ["/vinculacion/models.py"], "/nucleo/serializers.py": ["/nucleo/models.py", "/formacion_academica/models.py"], "/formacion_academica/serializers.py": ["/formacion_academica/models.py"], "/formacion_recursos_humanos/admin.py": ["/formacion_recursos_humanos/models.py"], "/movilidad_academica/models.py": ["/nucleo/models.py", "/vinculacion/models.py"], "/difusion_cientifica/models.py": ["/nucleo/models.py"], "/experiencia_laboral/views.py": ["/experiencia_laboral/serializers.py"], "/nucleo/views.py": ["/nucleo/models.py", "/nucleo/serializers.py"], "/desarrollo_tecnologico/models.py": ["/nucleo/models.py"], "/formacion_academica/admin.py": ["/formacion_academica/models.py"], "/investigacion/admin.py": ["/investigacion/models.py"], "/difusion_cientifica/admin.py": ["/difusion_cientifica/models.py"], "/investigacion/models.py": ["/nucleo/models.py"], "/formacion_academica/models.py": ["/nucleo/models.py"], "/movilidad_academica/admin.py": ["/movilidad_academica/models.py"], "/geom/envolvente.py": ["/geom/funciones.py"], "/nucleo/admin.py": ["/nucleo/models.py"], "/vinculacion/models.py": ["/nucleo/models.py", "/investigacion/models.py"], "/divulgacion_cientifica/admin.py": ["/divulgacion_cientifica/models.py"], "/experiencia_laboral/models.py": ["/nucleo/models.py"], "/docencia/models.py": ["/nucleo/models.py", "/vinculacion/models.py", "/formacion_academica/models.py"], "/experiencia_laboral/admin.py": ["/experiencia_laboral/models.py"], "/desarrollo_tecnologico/admin.py": ["/desarrollo_tecnologico/models.py"], "/divulgacion_cientifica/models.py": ["/nucleo/models.py"], "/formacion_academica/views.py": ["/formacion_academica/serializers.py"], "/apoyo_institucional/admin.py": ["/apoyo_institucional/models.py"], "/formacion_recursos_humanos/models.py": ["/nucleo/models.py"], "/distinciones/models.py": ["/nucleo/models.py"]} |
61,089 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/sg/factory.py | """
Smartglass packet factory
"""
from construct import Container
from xbox.sg.enum import PacketType, MessageType, ClientType
from xbox.sg.packet import simple, message
CHANNEL_CORE = 0
def _message_header(msg_type, channel_id=0, target_participant_id=0,
source_participant_id=0, is_fragment=False,
need_ack=False):
"""
Helper method for creating a message header.
Args:
msg_type (int): The message type.
channel_id (int): The target channel of the message.
target_participant_id (int): The target participant Id.
source_participant_id (int): The source participant Id.
is_fragment (bool): Whether the message is a fragment.
need_ack (bool): Whether the message needs an acknowledge.
Returns:
:class:`XStructObj`: Instance of :class:`:class:`XStructObj``.
"""
return message.header(
sequence_number=0,
target_participant_id=target_participant_id,
source_participant_id=source_participant_id,
flags=Container(
need_ack=need_ack,
is_fragment=is_fragment,
msg_type=msg_type
),
channel_id=channel_id,
pkt_type=PacketType.Message
)
def power_on(liveid):
"""
Assemble PowerOn Request message.
Args:
liveid (str): The console LiveId (extracted from the
:class:`DiscoveryResponse` Certificate).
Returns:
:class:`XStructObj`: Instance of :class:`:class:`XStructObj``.
"""
return simple.struct(
header=simple.header(pkt_type=PacketType.PowerOnRequest, version=0),
unprotected_payload=simple.power_on_request(liveid=liveid)
)
def discovery(client_type=ClientType.Android):
"""
Assemble DiscoveryRequest SimpleMessage.
Args:
client_type (:class:`ClientType`): Member of :class:`ClientType`, defaults to
`ClientType.Android`.
Returns:
:class:`XStructObj`: Instance of :class:`:class:`XStructObj``.
"""
return simple.struct(
header=simple.header(pkt_type=PacketType.DiscoveryRequest, version=0),
unprotected_payload=simple.discovery_request(
flags=0, client_type=client_type,
minimum_version=0, maximum_version=2
)
)
def connect(sg_uuid, public_key_type, public_key, iv, userhash, jwt,
msg_num, num_start, num_end):
"""
Assemble ConnectRequest SimpleMessage.
Args:
sg_uuid (UUID): Client Uuid, randomly generated.
public_key_type (:class:`PublicKeyType`): Public Key Type.
public_key (bytes): Calculated Public Key, from :class:`Crypto`.
iv (bytes): Initialization Vector for this encrypted message.
userhash (str): Xbox Live Account userhash.
jwt (str): Xbox Live Account JWT / Auth-token.
msg_num (int): Current message number (important for fragmentation).
num_start (int): Base number start of ConnectRequest fragments.
num_end (int): Base number end of ConnectRequest fragments
(base number start + total fragments + 1).
Returns:
:class:`XStructObj`: Instance of :class:`:class:`XStructObj``.
"""
return simple.struct(
header=simple.header(pkt_type=PacketType.ConnectRequest),
unprotected_payload=simple.connect_request_unprotected(
sg_uuid=sg_uuid, public_key_type=public_key_type,
public_key=public_key, iv=iv
),
protected_payload=simple.connect_request_protected(
userhash=userhash, jwt=jwt, connect_request_num=msg_num,
connect_request_group_start=num_start,
connect_request_group_end=num_end
)
)
def message_fragment(msg_type, sequence_begin, sequence_end, data, **kwargs):
"""
Assemble fragmented message.
Args:
msg_type (int): Base Message Type.
sequence_begin (int): Sequence number with first fragment.
sequence_end (int): Last sequence number (+1) containing fragment.
data (bytes): Plaintext MessagePacket payload fragment.
Returns:
:class:`XStructObj`: Instance of :class:`:class:`XStructObj``.
"""
return message.struct(
header=_message_header(
msg_type, is_fragment=True, **kwargs
),
protected_payload=message.fragment(
sequence_begin=sequence_begin,
sequence_end=sequence_end,
data=data
)
)
def acknowledge(low_watermark, processed_list, rejected_list, **kwargs):
"""
Assemble acknowledgement message.
Args:
low_watermark (int): Low Watermark.
processed_list (list): List of processed message sequence numbers.
rejected_list (list): List of rejected message sequence numbers.
Returns:
:class:`XStructObj`: Instance of :class:`:class:`XStructObj``.
"""
return message.struct(
header=_message_header(
MessageType.Ack, **kwargs
),
protected_payload=message.acknowledge(
low_watermark=low_watermark,
processed_list=processed_list,
rejected_list=rejected_list
)
)
def json(text, **kwargs):
"""
Assemble JSON message.
Args:
text (str): Text string.
Returns:
:class:`XStructObj`: Instance of :class:`:class:`XStructObj``.
"""
return message.struct(
header=_message_header(
MessageType.Json,
need_ack=True, **kwargs
),
protected_payload=message.json(
text=text
)
)
def disconnect(reason, error_code, **kwargs):
"""
Assemble Disconnect message.
Args:
reason (:class:`xbox.sg.enum.DisconnectReason`): Disconnect reason.
error_code (int): Error code.
Returns:
:class:`XStructObj`: Instance of :class:`:class:`XStructObj``.
"""
return message.struct(
header=_message_header(
MessageType.Disconnect, CHANNEL_CORE, **kwargs
),
protected_payload=message.disconnect(
reason=reason,
error_code=error_code
)
)
def power_off(liveid, **kwargs):
"""
Assemble PowerOff message.
Args:
liveid (str): Live ID of console.
Returns:
:class:`XStructObj`: Instance of :class:`:class:`XStructObj``.
"""
return message.struct(
header=_message_header(
MessageType.PowerOff, CHANNEL_CORE, **kwargs
),
protected_payload=message.power_off(
liveid=liveid
)
)
def local_join(client_info, **kwargs):
"""
Assemble LocalJoin message.
Args:
client_info (object): Instance of :class:`WindowsClientInfo`
or :class:`AndroidClientInfo`.
Returns:
:class:`XStructObj`: Instance of :class:`:class:`XStructObj``.
"""
return message.struct(
header=_message_header(
MessageType.LocalJoin, CHANNEL_CORE, need_ack=True, **kwargs
),
protected_payload=message.local_join(
device_type=client_info.DeviceType,
native_width=client_info.NativeWidth,
native_height=client_info.NativeHeight,
dpi_x=client_info.DpiX, dpi_y=client_info.DpiY,
device_capabilities=client_info.DeviceCapabilities,
client_version=client_info.ClientVersion,
os_major_version=client_info.OSMajor,
os_minor_version=client_info.OSMinor,
display_name=client_info.DisplayName
)
)
def title_launch(location, uri, **kwargs):
"""
Assemble TitleLaunch message.
Args:
location (:class:`ActiveTitleLocation`): Location.
uri (str): Uri string for title to launch.
Returns:
:class:`XStructObj`: Instance of :class:`:class:`XStructObj``.
"""
return message.struct(
header=_message_header(
MessageType.TitleLaunch, CHANNEL_CORE, **kwargs
),
protected_payload=message.title_launch(
location=location,
uri=uri
)
)
def start_channel(channel_request_id, title_id, service, activity_id,
**kwargs):
"""
Assemble StartChannelRequest message.
Args:
channel_request_id (int): Incrementing Channel Request Id.
title_id (int): Title Id, usually 0.
service (:class:`MessageTarget`): Member of :class:`MessageTarget`.
activity_id (int): Activity Id, usually 0.
Returns:
:class:`XStructObj`: Instance of :class:`:class:`XStructObj``.
"""
return message.struct(
header=_message_header(
MessageType.StartChannelRequest, CHANNEL_CORE,
need_ack=True, **kwargs
),
protected_payload=message.start_channel_request(
channel_request_id=channel_request_id,
title_id=title_id,
service=service,
activity_id=activity_id
)
)
def stop_channel(channel_id, **kwargs):
"""
Assemble StopChannel message.
Args:
channel_id (int): Channel Id to stop.
Returns:
:class:`XStructObj`: Instance of :class:`:class:`XStructObj``.
"""
return message.struct(
header=_message_header(
MessageType.StopChannel, CHANNEL_CORE, **kwargs
),
protected_payload=message.stop_channel(
target_channel_id=channel_id
)
)
def gamepad(timestamp, buttons, l_trigger, r_trigger, l_thumb_x, l_thumb_y,
r_thumb_x, r_thumb_y, **kwargs):
"""
Assemble gamepad input message.
Args:
timestamp (longlong): Timestamp.
buttons (:class:`GamePadButton`): Bitmask of pressed gamepad buttons.
l_trigger (float): LT.
r_trigger (float): RT.
l_thumb_x (float): Position of left thumbstick, X-Axis.
l_thumb_y (float): Position of left thumbstick, Y-Axis.
r_thumb_x (float): Position of right thumbstick, X-Axis.
r_thumb_y (float): Position of right thumbstick, Y-Axis.
Returns:
:class:`XStructObj`: Instance of :class:`:class:`XStructObj``.
"""
return message.struct(
header=_message_header(
MessageType.Gamepad, **kwargs
),
protected_payload=message.gamepad(
timestamp=timestamp, buttons=buttons,
left_trigger=l_trigger, right_trigger=r_trigger,
left_thumbstick_x=l_thumb_x, left_thumbstick_y=l_thumb_y,
right_thumbstick_x=r_thumb_x, right_thumbstick_y=r_thumb_y
)
)
def unsnap(unknown, **kwargs):
"""
Assemble unsnap message.
Args:
unknown (int): Unknown value.
Returns:
:class:`XStructObj`: Instance of :class:`:class:`XStructObj``.
"""
return message.struct(
header=_message_header(
MessageType.Unsnap, CHANNEL_CORE, **kwargs
),
protected_payload=message.unsnap(
unk=unknown
)
)
def game_dvr_record(start_time_delta, end_time_delta, **kwargs):
"""
Assemble Game DVR record message.
Args:
start_time_delta (int): Start Time delta.
end_time_delta (int): End Time delta.
Returns:
:class:`XStructObj`: Instance of :class:`:class:`XStructObj``.
"""
return message.struct(
header=_message_header(
MessageType.GameDvrRecord, CHANNEL_CORE,
need_ack=True, **kwargs
),
protected_payload=message.game_dvr_record(
start_time_delta=start_time_delta,
end_time_delta=end_time_delta
)
)
def media_command(request_id, title_id, command, seek_position, **kwargs):
"""
Assemble Media Command message.
Args:
request_id (int): Request Id of MediaCommand.
title_id (int): Title Id of Application to control.
command (:class:`MediaControlCommand`): Media Command.
seek_position (ulonglong): Seek position.
Returns:
:class:`XStructObj`: Instance of :class:`:class:`XStructObj``.
"""
return message.struct(
header=_message_header(
MessageType.MediaCommand,
need_ack=True, **kwargs
),
protected_payload=message.media_command(
request_id=request_id,
title_id=title_id,
command=command,
seek_position=seek_position
)
)
def systemtext_input(session_id, base_version, submitted_version, total_text_len,
selection_start, selection_length, flags, text_chunk_byte_start,
text_chunk, delta=None, **kwargs):
"""
Assemble SystemText Input message
Args:
session_id (int): Textt session Id
base_version (int): Base version
submitted_version (int): Submitted Version
total_text_len (int): Total text length
selection_start (int): Selection start
selection_length (int): Selection length
flags (int): Input flags
text_chunk_byte_start (int): Start byte of text chunk
text_chunk (str): Actual text to send
delta (NoneType): Unknown
Returns:
:class:`XStructObj`: Instance of :class:`:class:`XStructObj``.
"""
return message.struct(
header=_message_header(
MessageType.SystemTextInput,
need_ack=True, **kwargs
),
protected_payload=message.system_text_input(
text_session_id=session_id,
base_version=base_version,
submitted_version=submitted_version,
total_text_byte_len=total_text_len,
selection_start=selection_start,
selection_length=selection_length,
flags=flags,
text_chunk_byte_start=text_chunk_byte_start,
text_chunk=text_chunk
# delta=delta
)
)
def systemtext_ack(session_id, text_version, **kwargs):
"""
Assemble SystemText Acknowledge message
Args:
session_id (int): Text session Id
text_version (int): Text version to acknowledge
Returns:
:class:`XStructObj`: Instance of :class:`:class:`XStructObj``.
"""
return message.struct(
header=_message_header(
MessageType.SystemTextAck,
need_ack=True, **kwargs
),
protected_payload=message.system_text_acknowledge(
text_session_id=session_id,
text_version_ack=text_version
)
)
def systemtext_done(session_id, text_version, flags, result, **kwargs):
"""
Assemble SystemText Done message
Args:
session_id (int): Text session Id
text_version (int): Text version
flags (int): Flags
result (:class:`TextResult`): Text result
Returns:
:class:`XStructObj`: Instance of :class:`:class:`XStructObj``.
"""
return message.struct(
header=_message_header(
MessageType.SystemTextDone,
need_ack=True, **kwargs
),
protected_payload=message.system_text_done(
text_session_id=session_id,
text_version=text_version,
flags=flags,
result=result
)
)
def title_auxiliary_stream(**kwargs):
"""
Assemble Auxiliary Stream message
Returns:
:class:`XStructObj`: Instance of :class:`XStructObj`
"""
return message.struct(
header=_message_header(
MessageType.AuxilaryStream,
need_ack=True, **kwargs
),
protected_payload=message.auxiliary_stream(
connection_info_flag=0
)
)
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,090 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/auxiliary/manager.py | import logging
from typing import Any
from xbox.sg import factory
from xbox.sg.manager import Manager
from xbox.sg.enum import ServiceChannel, MessageType
from xbox.sg.constants import MessageTarget
from xbox.sg.utils.events import Event
log = logging.getLogger(__name__)
class TitleManagerError(Exception):
"""
Exception thrown by TitleManager
"""
pass
class TitleManager(Manager):
__namespace__ = 'title'
def __init__(self, console):
"""
Title Manager (ServiceChannel.Title)
Args:
console (:class:`.Console`): Console object, internally passed
by `Console.add_manager`
"""
super(TitleManager, self).__init__(console, ServiceChannel.Title)
self._active_surface = None
self._connection_info = None
self.on_surface_change = Event()
self.on_connection_info = Event()
def _on_message(self, msg, channel):
"""
Internal handler method to receive messages from Title Channel
Args:
msg (:class:`XStructObj`): Message
channel (:class:`ServiceChannel`): Service channel
"""
msg_type = msg.header.flags.msg_type
payload = msg.protected_payload
if msg_type == MessageType.AuxilaryStream:
if payload.connection_info_flag == 0:
log.debug('Received AuxiliaryStream HELLO')
self._request_connection_info()
else:
log.debug('Received AuxiliaryStream CONNECTION INFO')
self.connection_info = payload.connection_info
elif msg_type == MessageType.ActiveSurfaceChange:
self.active_surface = payload
else:
raise TitleManagerError(
f'Unhandled Msg: {msg_type}, Payload: {payload}'
)
async def _request_connection_info(self) -> None:
msg = factory.title_auxiliary_stream()
return await self._send_message(msg)
async def start_title_channel(self, title_id: int) -> Any:
return await self.console.protocol.start_channel(
ServiceChannel.Title,
MessageTarget.TitleUUID,
title_id=title_id
)
@property
def active_surface(self):
"""
Get `Active Surface`.
Returns:
:class:`XStructObj`: Active Surface
"""
return self._active_surface
@active_surface.setter
def active_surface(self, value):
"""
Set `Active Surface`.
Args:
value (:class:`XStructObj`): Active Surface payload
Returns: None
"""
self._active_surface = value
self.on_surface_change(value)
@property
def connection_info(self):
"""
Get current `Connection info`
Returns:
:class:`XStructObj`: Connection info
"""
return self._connection_info
@connection_info.setter
def connection_info(self, value):
"""
Set `Connection info` and setup `Crypto`-context
Args:
value (:class:`XStructObj`): Connection info
Returns: None
"""
self._connection_info = value
self.on_connection_info(value)
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,091 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /tests/test_struct.py | import construct
from xbox.sg.utils import struct, adapters
def test_xstruct():
test_struct = struct.XStruct(
'a' / construct.Int32ub,
'b' / construct.Int16ub
)
obj = test_struct(a=1, b=2)
assert test_struct.a.subcon == construct.Int32ub
assert test_struct.b.subcon == construct.Int16ub
assert 'a' in test_struct
assert 'b' in test_struct
assert obj.container == construct.Container(a=1, b=2)
assert obj.a == 1
assert obj.b == 2
assert obj.build() == b'\x00\x00\x00\x01\x00\x02'
obj.parse(b'\x00\x00\x00\x02\x00\x03')
assert obj.container == construct.Container(a=2, b=3)
obj = test_struct.parse(b'\x00\x00\x00\x03\x00\x04')
assert obj.container == construct.Container(a=3, b=4)
def test_flatten():
test_sub = struct.XStruct(
'c' / construct.Int16ub
)
test_struct = struct.XStruct(
'a' / construct.Int32ub,
'b' / test_sub
)
obj = test_struct(a=1, b=test_sub(c=2))
flat = struct.flatten(obj.container)
assert flat == construct.Container(a=1, b=construct.Container(c=2))
def test_terminated_field():
test_struct = struct.XStruct(
'a' / adapters.TerminatedField(construct.Int32ub)
)
assert test_struct(a=1).build() == b'\x00\x00\x00\x01\x00'
assert test_struct.parse(b'\x00\x00\x00\x01\x00').container.a == 1
test_struct = struct.XStruct(
'a' / adapters.TerminatedField(
construct.Int32ub, length=4, pattern=b'\xff'
)
)
assert test_struct(a=1).build() == b'\x00\x00\x00\x01\xff\xff\xff\xff'
assert test_struct.parse(b'\x00\x00\x00\x01\xff\xff\xff\xff').container.a == 1
def test_sgstring():
test_struct = struct.XStruct(
'a' / adapters.SGString()
)
assert test_struct(a='test').build() == b'\x00\x04test\x00'
assert test_struct.parse(b'\x00\x04test\x00').container.a == 'test'
def test_fieldin():
test_struct = struct.XStruct(
'a' / construct.Int32ub,
'b' / construct.IfThenElse(
adapters.FieldIn('a', [1, 2, 3]),
construct.Int32ub, construct.Int16ub
)
)
assert test_struct(a=1, b=2).build() == b'\x00\x00\x00\x01\x00\x00\x00\x02'
assert test_struct(a=2, b=2).build() == b'\x00\x00\x00\x02\x00\x00\x00\x02'
assert test_struct(a=3, b=2).build() == b'\x00\x00\x00\x03\x00\x00\x00\x02'
assert test_struct(a=4, b=2).build() == b'\x00\x00\x00\x04\x00\x02'
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,092 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /tests/test_auxstream_packing.py | import io
from xbox.sg.crypto import PKCS7Padding
from xbox.auxiliary import packer
from xbox.auxiliary import packet
def _read_aux_packets(data):
with io.BytesIO(data) as stream:
while stream.tell() < len(data):
header_data = stream.read(4)
header = packet.aux_header_struct.parse(header_data)
if header.magic != packet.AUX_PACKET_MAGIC:
raise Exception('Invalid packet magic received from console')
padded_payload_sz = header.payload_size + PKCS7Padding.size(header.payload_size, 16)
payload_data = stream.read(padded_payload_sz)
hmac = stream.read(32)
yield header_data + payload_data + hmac
def test_client_unpack(aux_streams, aux_crypto):
data = aux_streams['fo4_client_to_console']
for msg in _read_aux_packets(data):
packer.unpack(msg, aux_crypto, client_data=True)
def test_server_unpack(aux_streams, aux_crypto):
data = aux_streams['fo4_console_to_client']
for msg in _read_aux_packets(data):
packer.unpack(msg, aux_crypto)
def test_decryption(aux_streams, aux_crypto):
data = aux_streams['fo4_console_to_client']
messages = list(_read_aux_packets(data))
# Need to unpack messages in order, starting with the first one
# -> Gets IV from previous decryption
packer.unpack(messages[0], aux_crypto)
json_msg = packer.unpack(messages[1], aux_crypto)
assert json_msg == b'{"lang":"de","version":"1.10.52.0"}\n'
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,093 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/rest/singletons.py | import aiohttp
from typing import Dict, Optional
from .schemas.auth import AuthSessionConfig
from .consolewrap import ConsoleWrap
from xbox.webapi.api.client import XboxLiveClient
from xbox.webapi.api.provider.titlehub import TitleHubResponse
from xbox.webapi.authentication.manager import AuthenticationManager
http_session: Optional[aiohttp.ClientSession] = None
authentication_manager: Optional[AuthenticationManager] = None
xbl_client: Optional[XboxLiveClient] = None
auth_session_configs: Dict[str, AuthSessionConfig] = dict()
console_cache: Dict[str, ConsoleWrap] = dict()
title_cache: Dict[str, TitleHubResponse] = dict()
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,094 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /tests/test_adapters.py | import pytest
import construct
from xbox.sg.utils import adapters
@pytest.mark.skip(reason="Not Implemented")
def test_cryptotunnel():
pass
def test_json():
import json
test_data = {"Z": "ABC", "A": "XYZ", "B": 23}
bytes_data = json.dumps(test_data,
separators=(',', ':'),
sort_keys=True).encode('utf-8')
adapter = adapters.JsonAdapter(construct.GreedyString("utf8"))
parsed = adapter.parse(bytes_data)
built = adapter.build(test_data)
with pytest.raises(json.JSONDecodeError):
adapter.parse(b'invalid data')
with pytest.raises(TypeError):
adapter.parse(234)
with pytest.raises(TypeError):
adapter.parse("string")
with pytest.raises(TypeError):
adapter.build(b'invalid data')
with pytest.raises(TypeError):
adapter.build(234)
with pytest.raises(TypeError):
adapter.build("string")
assert parsed == test_data
assert built == bytes_data
def test_uuid(uuid_dummy):
import struct
test_data = uuid_dummy
uuid_string = str(test_data).upper()
uuid_stringbytes = uuid_string.encode('utf-8')
uuid_sgstring = struct.pack('>H', len(uuid_stringbytes)) + uuid_stringbytes + b'\x00'
uuid_bytes = test_data.bytes
adapter_bytes = adapters.UUIDAdapter()
parsed_bytes = adapter_bytes.parse(uuid_bytes)
built_bytes = adapter_bytes.build(test_data)
adapter_string = adapters.UUIDAdapter("utf-8")
parsed_sgstring = adapter_string.parse(uuid_sgstring)
built_sgstring = adapter_string.build(test_data)
adapter_invalid = adapters.UUIDAdapter("utf-invalid")
with pytest.raises(LookupError):
adapter_invalid.parse(uuid_sgstring)
with pytest.raises(LookupError):
adapter_invalid.build(test_data)
with pytest.raises(construct.StreamError):
adapter_bytes.parse(uuid_bytes[:-2])
with pytest.raises(TypeError):
adapter_bytes.parse('string, not bytes object')
with pytest.raises(TypeError):
adapter_bytes.build('some-string, not UUID object')
with pytest.raises(construct.StreamError):
adapter_string.parse(uuid_sgstring[:-3])
with pytest.raises(TypeError):
adapter_string.parse('string, not sgstring-bytes')
with pytest.raises(TypeError):
adapter_string.build('some-string, not UUID object')
assert parsed_bytes == test_data
assert built_bytes == uuid_bytes
assert parsed_sgstring == test_data
assert built_sgstring == uuid_sgstring
def test_certificate(certificate_data):
import struct
prefixed_data = struct.pack('>H', len(certificate_data)) + certificate_data
certinfo = adapters.CertificateInfo(certificate_data)
adapter = adapters.CertificateAdapter()
parsed = adapter.parse(prefixed_data)
built = adapter.build(certinfo)
with pytest.raises(construct.core.StreamError):
adapter.parse(prefixed_data[:-6])
with pytest.raises(construct.core.StreamError):
adapter.parse(b'\xAB' * 10)
with pytest.raises(construct.core.StreamError):
adapter.parse(certificate_data)
with pytest.raises(TypeError):
adapter.parse('string, not bytes')
with pytest.raises(TypeError):
adapter.parse(123)
with pytest.raises(TypeError):
adapter.build(b'\xAB' * 10)
with pytest.raises(TypeError):
adapter.build(certificate_data)
with pytest.raises(TypeError):
adapter.build('string, not bytes')
with pytest.raises(TypeError):
adapter.build(123)
assert isinstance(parsed, adapters.CertificateInfo) is True
assert parsed == certinfo
assert built == prefixed_data
def test_certificateinfo(certificate_data):
certinfo = adapters.CertificateInfo(certificate_data)
with pytest.raises(ValueError):
adapters.CertificateInfo(certificate_data[:-1])
with pytest.raises(ValueError):
adapters.CertificateInfo(b'\x23' * 10)
with pytest.raises(TypeError):
adapters.CertificateInfo('some string')
with pytest.raises(TypeError):
adapters.CertificateInfo(123)
with pytest.raises(TypeError):
certinfo.dump(encoding='invalid param')
assert certinfo.dump() == certificate_data
assert certinfo.liveid == 'FFFFFFFFFFF'
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,095 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/rest/common.py |
import aiohttp
from xbox.webapi.authentication.manager import AuthenticationManager
from .schemas.auth import AuthenticationStatus, AuthSessionConfig
def generate_authentication_status(
manager: AuthenticationManager
) -> AuthenticationStatus:
return AuthenticationStatus(
oauth=manager.oauth,
xsts=manager.xsts_token,
session_config=AuthSessionConfig(
client_id=manager._client_id,
client_secret=manager._client_secret,
redirect_uri=manager._redirect_uri,
scopes=manager._scopes
)
)
def generate_authentication_manager(
session_config: AuthSessionConfig,
http_session: aiohttp.ClientSession = None
) -> AuthenticationManager:
return AuthenticationManager(
client_session=http_session,
client_id=session_config.client_id,
client_secret=session_config.client_secret,
redirect_uri=session_config.redirect_uri,
scopes=session_config.scopes
) | {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,096 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/rest/__init__.py | SMARTGLASS_PACKAGENAMES = [
'xbox-smartglass-core',
'xbox-smartglass-nano',
'xbox-webapi'
] | {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,097 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/auxiliary/__init__.py | """
Auxiliary stream support for smartglass
"""
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,098 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/stump/json_model.py | """
JSON models for deserializing Stump messages
"""
from typing import List, Dict, Union, Optional
from uuid import UUID
from pydantic import BaseModel
from xbox.stump.enum import Message
class StumpJsonError(Exception):
pass
# Root-level containers
class StumpRequest(BaseModel):
msgid: str
request: str
params: Optional[dict]
class StumpResponse(BaseModel):
msgid: str
response: str
class StumpError(BaseModel):
msgid: str
error: str
class StumpNotification(BaseModel):
notification: str
# Nested models
class _FoundChannel(BaseModel):
channelNumber: int
displayName: str
channelId: str
class _LineupProvider(BaseModel):
foundChannels: List[_FoundChannel]
cqsChannels: List[str]
headendId: UUID
class _EnsureStreamingStarted(BaseModel):
currentChannelId: str
source: str
streamingPort: int
tunerChannelType: str
userCanViewChannel: str
class _TunerLineups(BaseModel):
providers: List[_LineupProvider]
class _RecentChannel(BaseModel):
channelNum: str # Can be "NumberUnused" instead of int
providerId: UUID
channelId: str
class _PauseBufferInfo(BaseModel):
Enabled: bool
IsDvr: bool
MaxBufferSize: int
BufferCurrent: int
BufferStart: int
BufferEnd: int
CurrentTime: int
Epoch: int
class _LiveTvInfo(BaseModel):
streamingPort: Optional[int]
inHdmiMode: bool
tunerChannelType: Optional[str]
currentTunerChannelId: Optional[str]
currentHdmiChannelId: Optional[str]
pauseBufferInfo: Optional[_PauseBufferInfo]
class _HeadendProvider(BaseModel):
providerName: str
filterPreference: str
headendId: UUID
source: str
titleId: str
canStream: bool
class _HeadendInfo(BaseModel):
providerName: str
headendId: UUID
blockExplicitContentPerShow: bool
dvrEnabled: bool
headendLocale: str
streamingPort: Optional[int]
preferredProvider: Optional[str]
providers: List[_HeadendProvider]
class _DeviceConfiguration(BaseModel):
device_id: str
device_type: str
device_brand: Optional[str]
device_model: Optional[str]
device_name: Optional[str]
buttons: Dict[str, str]
class _AppChannel(BaseModel):
name: str
id: str
class _AppProvider(BaseModel):
id: str
providerName: str
titleId: str
primaryColor: str
secondaryColor: str
providerImageUrl: Optional[str]
channels: List[_AppChannel]
# Stump responses
class AppChannelLineups(StumpResponse):
params: List[_AppProvider]
class EnsureStreamingStarted(StumpResponse):
params: _EnsureStreamingStarted
class TunerLineups(StumpResponse):
params: _TunerLineups
class SendKey(StumpResponse):
params: bool
class RecentChannels(StumpResponse):
params: List[_RecentChannel]
class Configuration(StumpResponse):
params: List[_DeviceConfiguration]
class LiveTvInfo(StumpResponse):
params: _LiveTvInfo
class HeadendInfo(StumpResponse):
params: _HeadendInfo
response_map = {
Message.CONFIGURATION: Configuration,
Message.ENSURE_STREAMING_STARTED: EnsureStreamingStarted,
Message.SEND_KEY: SendKey,
Message.RECENT_CHANNELS: RecentChannels,
Message.SET_CHANNEL: None,
Message.APPCHANNEL_PROGRAM_DATA: None,
Message.APPCHANNEL_DATA: None,
Message.APPCHANNEL_LINEUPS: AppChannelLineups,
Message.TUNER_LINEUPS: TunerLineups,
Message.PROGRAMM_INFO: None,
Message.LIVETV_INFO: LiveTvInfo,
Message.HEADEND_INFO: HeadendInfo,
Message.ERROR: None
}
def deserialize_stump_message(data: dict) -> Union[StumpError, StumpNotification, StumpResponse]:
"""
Helper for deserializing JSON stump messages
Args:
data (dict): Stump message
Returns:
Model: Parsed JSON object
"""
response = data.get('response')
notification = data.get('notification')
error = data.get('error')
if response:
response = Message(response)
model = response_map.get(response)
if not issubclass(model, StumpResponse):
raise StumpJsonError('Model not of subclass StumpResponse')
return model.parse_obj(data)
elif notification:
return StumpNotification.load(data)
elif error:
return StumpError.load(data)
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,099 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /tests/test_stump_json_models.py | import pytest
from xbox.stump import json_model
from xbox.stump.enum import Message
def test_stump_response(stump_json):
data = stump_json['response_recent_channels']
msg = json_model.deserialize_stump_message(data)
assert msg.msgid == 'xV5X1YCB.16'
assert Message(msg.response) == Message.RECENT_CHANNELS
assert isinstance(msg.params, list)
def test_tuner_lineups(stump_json):
data = stump_json['response_tuner_lineups']
msg = json_model.deserialize_stump_message(data)
assert len(msg.params.providers) == 1
provider = msg.params.providers[0]
assert len(provider.foundChannels) == 19
found_channel = provider.foundChannels[0]
assert found_channel.channelNumber == 0
assert found_channel.displayName == 'Das Erste HD'
assert found_channel.channelId == '000021146A000301'
assert len(provider.cqsChannels) == 7
assert provider.cqsChannels[0] == '178442d3-2b13-e02b-9747-a3d4ebebcf62_PHOENIHD_23'
assert str(provider.headendId) == '0a7fb88a-960b-c2e3-9975-7c86c5fa6c49'
def test_recent_channels(stump_json):
data = stump_json['response_recent_channels']
msg = json_model.deserialize_stump_message(data)
assert len(msg.params) == 0
# assert msg.params[0].channelNum == ''
# assert msg.params[0].providerId == ''
# assert msg.params[0].channelId == ''
def test_livetv_info(stump_json):
data = stump_json['response_livetv_info']
msg = json_model.deserialize_stump_message(data)
assert msg.params.streamingPort == 10242
assert msg.params.inHdmiMode is False
assert msg.params.tunerChannelType == 'televisionChannel'
assert msg.params.currentTunerChannelId == 'bb1ca492-232b-adfe-1f39-d010eabf179e_MSAHD_16'
assert msg.params.currentHdmiChannelId == '731cd976-c1e9-6b95-4799-e6757d02cab1_3SATHD_1'
assert msg.params.pauseBufferInfo is not None
assert msg.params.pauseBufferInfo.Enabled is True
assert msg.params.pauseBufferInfo.IsDvr is False
assert msg.params.pauseBufferInfo.MaxBufferSize == 18000000000
assert msg.params.pauseBufferInfo.BufferCurrent == 131688132168080320
assert msg.params.pauseBufferInfo.BufferStart == 131688132168080320
assert msg.params.pauseBufferInfo.BufferEnd == 131688151636700238
assert msg.params.pauseBufferInfo.CurrentTime == 131688151636836518
assert msg.params.pauseBufferInfo.Epoch == 0
def test_headend_info(stump_json):
data = stump_json['response_headend_info']
msg = json_model.deserialize_stump_message(data)
assert msg.params.providerName == 'Sky Deutschland'
assert str(msg.params.headendId) == '516b9ea7-5292-97ec-e7d4-f843fab6d392'
assert msg.params.blockExplicitContentPerShow is False
assert msg.params.dvrEnabled is False
assert msg.params.headendLocale == 'de-DE'
assert msg.params.streamingPort == 10242
assert msg.params.preferredProvider == '29045393'
assert len(msg.params.providers) == 2
provider = msg.params.providers[0]
assert provider.providerName == 'Sky Deutschland'
assert provider.filterPreference == 'ALL'
assert str(provider.headendId) == '516b9ea7-5292-97ec-e7d4-f843fab6d392'
assert provider.source == 'hdmi'
assert provider.titleId == '162615AD'
assert provider.canStream is False
def test_configuration(stump_json):
data = stump_json['response_configuration']
msg = json_model.deserialize_stump_message(data)
assert len(msg.params) == 4
device_config = msg.params[0]
assert device_config.device_brand == 'Samsung'
assert device_config.device_id == '0'
assert device_config.device_type == 'tv'
assert isinstance(device_config.buttons, dict) is True
@pytest.mark.skip
def test_ensure_streaming_started(stump_json):
data = stump_json['response_ensure_streaming_started']
msg = json_model.deserialize_stump_message(data)
assert msg.params.currentChannelId == ''
assert msg.params.source == ''
assert msg.params.streamingPort == 0
assert msg.params.tunerChannelType == ''
assert msg.params.userCanViewChannel == ''
def test_app_channel_lineups(stump_json):
data = stump_json['response_appchannel_lineups']
msg = json_model.deserialize_stump_message(data)
assert len(msg.params) == 4
provider = msg.params[0]
assert provider.id == 'LiveTvHdmiProvider'
assert provider.providerName == 'OneGuide'
assert provider.titleId == '00000000'
assert provider.primaryColor == 'ff107c10'
assert provider.secondaryColor == 'ffebebeb'
assert len(provider.channels) == 0
# channel = provider.channels[0]
# assert channel.name == ''
# assert channel.id == ''
def test_send_key(stump_json):
data = stump_json['response_sendkey']
msg = json_model.deserialize_stump_message(data)
assert msg.params is True
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,100 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /tests/test_factory.py | import uuid
from binascii import unhexlify
from xbox.sg import enum, constants
from xbox.sg import packer
from xbox.sg import factory
def _pack(msg, crypto):
return packer.pack(msg, crypto)
def test_message_header():
msg = factory._message_header(
msg_type=enum.MessageType.Ack,
target_participant_id=2,
source_participant_id=3,
need_ack=False,
is_fragment=False,
channel_id=0xFFFF
)
packed = msg.build()
assert msg.flags.msg_type == enum.MessageType.Ack
assert msg.sequence_number == 0
assert msg.target_participant_id == 2
assert msg.source_participant_id == 3
assert msg.channel_id == 0xFFFF
assert msg.flags.need_ack is False
assert msg.flags.is_fragment is False
assert len(packed) == 26
assert packed == unhexlify(
b'd00d00000000000000000002000000038001000000000000ffff'
)
def test_power_on(packets, crypto):
bin_name = 'poweron_request'
msg = factory.power_on(liveid='FD00112233FFEE66')
packed = _pack(msg, crypto)
assert msg.header.pkt_type == enum.PacketType.PowerOnRequest
assert msg.header.version == 0
assert msg.unprotected_payload.liveid == 'FD00112233FFEE66'
assert len(packed) == len(packets[bin_name])
assert packed == packets[bin_name]
def test_discovery_request(packets, crypto):
bin_name = 'discovery_request'
msg = factory.discovery(client_type=enum.ClientType.Android)
packed = _pack(msg, crypto)
assert msg.header.pkt_type == enum.PacketType.DiscoveryRequest
assert msg.header.version == 0
assert msg.unprotected_payload.flags == 0
assert msg.unprotected_payload.client_type == enum.ClientType.Android
assert msg.unprotected_payload.minimum_version == 0
assert msg.unprotected_payload.maximum_version == 2
assert len(packed) == len(packets[bin_name])
assert packed == packets[bin_name]
def test_connect_request(packets, crypto):
bin_name = 'connect_request'
msg = factory.connect(
sg_uuid=uuid.UUID('{de305d54-75b4-431b-adb2-eb6b9e546014}'),
public_key_type=enum.PublicKeyType.EC_DH_P256,
public_key=b'\xFF' * 64,
iv=unhexlify('2979d25ea03d97f58f46930a288bf5d2'),
userhash='deadbeefdeadbeefde',
jwt='dummy_token',
msg_num=0,
num_start=0,
num_end=2
)
packed = _pack(msg, crypto)
assert msg.header.pkt_type == enum.PacketType.ConnectRequest
assert str(msg.unprotected_payload.sg_uuid) == 'de305d54-75b4-431b-adb2-eb6b9e546014'
assert msg.unprotected_payload.public_key_type == enum.PublicKeyType.EC_DH_P256
assert msg.unprotected_payload.public_key == b'\xFF' * 64
assert msg.unprotected_payload.iv == unhexlify(
'2979d25ea03d97f58f46930a288bf5d2'
)
assert msg.protected_payload.userhash == 'deadbeefdeadbeefde'
assert msg.protected_payload.jwt == 'dummy_token'
assert msg.protected_payload.connect_request_num == 0
assert msg.protected_payload.connect_request_group_start == 0
assert msg.protected_payload.connect_request_group_end == 2
assert len(packed) == len(packets[bin_name])
assert packed == packets[bin_name]
def test_connect_request_anonymous(packets, crypto):
bin_name = 'connect_request_anonymous'
msg = factory.connect(
sg_uuid=uuid.UUID('{de305d54-75b4-431b-adb2-eb6b9e546014}'),
public_key_type=enum.PublicKeyType.EC_DH_P256,
public_key=b'\xFF' * 64,
iv=unhexlify('2979d25ea03d97f58f46930a288bf5d2'),
userhash='',
jwt='',
msg_num=0,
num_start=0,
num_end=1
)
packed = _pack(msg, crypto)
assert msg.header.pkt_type == enum.PacketType.ConnectRequest
assert str(msg.unprotected_payload.sg_uuid) == 'de305d54-75b4-431b-adb2-eb6b9e546014'
assert msg.unprotected_payload.public_key_type == enum.PublicKeyType.EC_DH_P256
assert msg.unprotected_payload.public_key == b'\xFF' * 64
assert msg.unprotected_payload.iv == unhexlify(
'2979d25ea03d97f58f46930a288bf5d2'
)
assert msg.protected_payload.userhash == ''
assert msg.protected_payload.jwt == ''
assert msg.protected_payload.connect_request_num == 0
assert msg.protected_payload.connect_request_group_start == 0
assert msg.protected_payload.connect_request_group_end == 1
import binascii
print(binascii.hexlify(packed))
assert len(packed) == len(packets[bin_name])
assert packed == packets[bin_name]
def test_message_fragment(packets, crypto):
data = unhexlify(
b'6a5297cd00424d6963726f736f66742e426c75726179506c617965725f3877656b79623364386262'
b'77652158626f782e426c75726179506c617965722e4170706c69636174696f6e0008883438303036'
b'31303036433030364630303230303035343030363830303635303032303030343630303631303036'
b'43303036433030323030303646303036363030323030303532303036353030363130303633303036'
b'38303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'303030303030303030303030303030303030303030303030'
)
msg = factory.message_fragment(
msg_type=enum.MessageType.MediaState,
sequence_begin=22,
sequence_end=25,
data=data,
need_ack=True,
source_participant_id=0,
target_participant_id=31,
channel_id=148
)
msg.header(sequence_number=22)
packed = _pack(msg, crypto)
assert msg.header.pkt_type == enum.PacketType.Message
assert msg.header.flags.msg_type == enum.MessageType.MediaState
assert msg.protected_payload.sequence_begin == 22
assert msg.protected_payload.sequence_end == 25
assert msg.protected_payload.data == data
assert isinstance(packed, bytes) is True
assert len(packed) == 1098
assert packed == packets['fragment_media_state_0']
def test_acknowledge(packets, crypto):
bin_name = 'acknowledge'
msg = factory.acknowledge(
low_watermark=0,
processed_list=[1],
rejected_list=[]
)
msg.header(
sequence_number=1,
target_participant_id=31,
channel_id=1152921504606846976
)
msg.header.flags(version=2, need_ack=False)
packed = _pack(msg, crypto)
assert msg.header.pkt_type == enum.PacketType.Message
assert msg.header.flags.msg_type == enum.MessageType.Ack
assert msg.protected_payload.low_watermark == 0
assert msg.protected_payload.processed_list == [1]
assert msg.protected_payload.rejected_list == []
assert len(packed) == len(packets[bin_name])
assert packed == packets[bin_name]
def test_json(packets, crypto):
bin_name = 'json'
msg = factory.json(
text={'request': 'GetConfiguration', 'msgid': '2ed6c0fd.2'}
)
msg.header(
sequence_number=11,
source_participant_id=31,
channel_id=151
)
msg.header.flags(need_ack=True)
packed = _pack(msg, crypto)
assert msg.header.pkt_type == enum.PacketType.Message
assert msg.header.flags.msg_type == enum.MessageType.Json
assert msg.protected_payload.text == {
'request': 'GetConfiguration', 'msgid': '2ed6c0fd.2'
}
assert len(packed) == len(packets[bin_name])
assert packed == packets[bin_name]
def test_disconnect(packets, crypto):
bin_name = 'disconnect'
msg = factory.disconnect(
reason=enum.DisconnectReason.Unspecified,
error_code=0
)
msg.header(
sequence_number=57,
source_participant_id=31
)
msg.header.flags(need_ack=False)
packed = _pack(msg, crypto)
assert msg.header.pkt_type == enum.PacketType.Message
assert msg.header.flags.msg_type == enum.MessageType.Disconnect
assert msg.protected_payload.reason == enum.DisconnectReason.Unspecified
assert msg.protected_payload.error_code == 0
assert len(packed) == len(packets[bin_name])
assert packed == packets[bin_name]
def test_power_off(packets, crypto):
bin_name = 'power_off'
msg = factory.power_off(liveid='FD00112233FFEE66')
msg.header(
sequence_number=1882,
source_participant_id=2
)
msg.header.flags(need_ack=True)
packed = _pack(msg, crypto)
assert msg.header.pkt_type == enum.PacketType.Message
assert msg.header.flags.msg_type == enum.MessageType.PowerOff
assert msg.protected_payload.liveid == 'FD00112233FFEE66'
assert len(packed) == len(packets[bin_name])
assert packed == packets[bin_name]
def test_local_join(packets, crypto):
class TestClientInfo(object):
DeviceType = enum.ClientType.Android
NativeWidth = 600
NativeHeight = 1024
DpiX = 160
DpiY = 160
DeviceCapabilities = constants.DeviceCapabilities.All
ClientVersion = 133713371
OSMajor = 42
OSMinor = 0
DisplayName = 'package.name.here'
bin_name = 'local_join'
msg = factory.local_join(client_info=TestClientInfo)
msg.header(
sequence_number=1,
source_participant_id=31
)
msg.header.flags(version=0)
packed = _pack(msg, crypto)
assert msg.header.pkt_type == enum.PacketType.Message
assert msg.header.flags.msg_type == enum.MessageType.LocalJoin
assert msg.protected_payload.device_type == enum.ClientType.Android
assert msg.protected_payload.native_width == 600
assert msg.protected_payload.native_height == 1024
assert msg.protected_payload.dpi_x == 160
assert msg.protected_payload.dpi_y == 160
assert msg.protected_payload.device_capabilities == constants.DeviceCapabilities.All
assert msg.protected_payload.client_version == 133713371
assert msg.protected_payload.os_major_version == 42
assert msg.protected_payload.os_minor_version == 0
assert msg.protected_payload.display_name == 'package.name.here'
assert len(packed) == len(packets[bin_name])
assert packed == packets[bin_name]
def test_title_launch(packets, crypto):
bin_name = 'title_launch'
msg = factory.title_launch(
location=enum.ActiveTitleLocation.Fill,
uri='ms-xbl-0D174C79://default/'
)
msg.header(
sequence_number=685,
source_participant_id=32
)
msg.header.flags(need_ack=True)
packed = _pack(msg, crypto)
assert msg.header.pkt_type == enum.PacketType.Message
assert msg.header.flags.msg_type == enum.MessageType.TitleLaunch
assert msg.protected_payload.location == enum.ActiveTitleLocation.Fill
assert msg.protected_payload.uri == 'ms-xbl-0D174C79://default/'
assert len(packed) == len(packets[bin_name])
assert packed == packets[bin_name]
def test_start_channel(packets, crypto):
bin_name = 'start_channel_request'
msg = factory.start_channel(
channel_request_id=1,
title_id=0,
service=constants.MessageTarget.SystemInputUUID,
activity_id=0
)
msg.header(
sequence_number=2,
source_participant_id=31
)
msg.header.flags(need_ack=True)
packed = _pack(msg, crypto)
assert msg.header.pkt_type == enum.PacketType.Message
assert msg.header.flags.msg_type == enum.MessageType.StartChannelRequest
assert msg.protected_payload.channel_request_id == 1
assert msg.protected_payload.title_id == 0
assert msg.protected_payload.service == constants.MessageTarget.SystemInputUUID
assert msg.protected_payload.activity_id == 0
assert len(packed) == len(packets[bin_name])
assert packed == packets[bin_name]
def test_stop_channel(packets, crypto):
msg = factory.stop_channel(channel_id=2)
packed = _pack(msg, crypto)
assert msg.header.pkt_type == enum.PacketType.Message
assert msg.header.flags.msg_type == enum.MessageType.StopChannel
assert msg.protected_payload.target_channel_id == 2
assert len(packed) == 74
assert packed == unhexlify(
b'd00d0008000000000000000000000000802800000000000000001b0783367a4426'
b'c2e0775916685c072df0380ee320925842716d595ced4b68f8a9bad01a5301be7e'
b'd7d3b4e25a03b728'
)
def test_gamepad(packets, crypto):
bin_name = 'gamepad'
msg = factory.gamepad(
timestamp=0,
buttons=enum.GamePadButton.PadB,
l_trigger=0.0,
r_trigger=0.0,
l_thumb_x=0.0,
r_thumb_x=0.0,
l_thumb_y=0.0,
r_thumb_y=0.0
)
msg.header(
sequence_number=79,
source_participant_id=41,
channel_id=180
)
msg.header.flags(need_ack=False)
packed = _pack(msg, crypto)
assert msg.header.pkt_type == enum.PacketType.Message
assert msg.header.flags.msg_type == enum.MessageType.Gamepad
assert msg.protected_payload.timestamp == 0
assert msg.protected_payload.buttons == enum.GamePadButton.PadB
assert msg.protected_payload.left_trigger == 0.0
assert msg.protected_payload.right_trigger == 0.0
assert msg.protected_payload.left_thumbstick_x == 0.0
assert msg.protected_payload.right_thumbstick_x == 0.0
assert msg.protected_payload.left_thumbstick_y == 0.0
assert msg.protected_payload.right_thumbstick_y == 0.0
assert len(packed) == len(packets[bin_name])
assert packed == packets[bin_name]
def test_unsnap(packets, crypto):
msg = factory.unsnap(unknown=1)
packed = _pack(msg, crypto)
assert msg.header.pkt_type == enum.PacketType.Message
assert msg.header.flags.msg_type == enum.MessageType.Unsnap
assert msg.protected_payload.unk == 1
assert len(packed) == 74
assert packed == unhexlify(
b'd00d000100000000000000000000000080370000000000000000738d3b76a69a34'
b'bbf732755035fe77672e5ea1432f3e278189d7756f62254ebe790dfe084ba43067'
b'bf3f4b2546c1f882'
)
def test_gamedvr_record(packets, crypto):
bin_name = 'gamedvr_record'
msg = factory.game_dvr_record(
start_time_delta=-60,
end_time_delta=0
)
msg.header(
sequence_number=70,
source_participant_id=1
)
msg.header.flags(need_ack=True)
packed = _pack(msg, crypto)
assert msg.header.pkt_type == enum.PacketType.Message
assert msg.header.flags.msg_type == enum.MessageType.GameDvrRecord
assert msg.protected_payload.start_time_delta == -60
assert msg.protected_payload.end_time_delta == 0
assert len(packed) == len(packets[bin_name])
assert packed == packets[bin_name]
def test_media_command(packets, crypto):
bin_name = 'media_command'
msg = factory.media_command(
request_id=0,
title_id=274278798,
command=enum.MediaControlCommand.FastForward,
seek_position=0
)
msg.header(
sequence_number=597,
source_participant_id=32,
channel_id=153
)
msg.header.flags(need_ack=True)
packed = _pack(msg, crypto)
assert msg.header.pkt_type == enum.PacketType.Message
assert msg.header.flags.msg_type == enum.MessageType.MediaCommand
assert msg.protected_payload.request_id == 0
assert msg.protected_payload.title_id == 274278798
assert msg.protected_payload.command == enum.MediaControlCommand.FastForward
assert len(packed) == len(packets[bin_name])
assert packed == packets[bin_name]
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,101 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/rest/schemas/root.py | from typing import Dict, Optional
from pydantic import BaseModel
class IndexResponse(BaseModel):
versions: Dict[str, Optional[str]]
doc_path: str
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,102 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/rest/app.py | from fastapi import FastAPI
import uvicorn
import aiohttp
from . import singletons
from .api import api_router
app = FastAPI(title='SmartGlass REST server')
@app.on_event("startup")
async def startup_event():
singletons.http_session = aiohttp.ClientSession()
@app.on_event("shutdown")
async def shutdown_event():
await singletons.http_session.close()
app.include_router(api_router)
if __name__ == '__main__':
uvicorn.run(app, host="0.0.0.0", port=5557)
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,103 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/sg/__init__.py | """
Meta package for xbox-smartglass-core-python.
Version and author information.
"""
__author__ = """OpenXbox"""
__version__ = '1.3.0'
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,104 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /tests/test_padding.py | from xbox.sg.crypto import Padding, PKCS7Padding, ANSIX923Padding
def test_calculate_padding():
align_16 = Padding.size(12, alignment=16)
align_12 = Padding.size(12, alignment=12)
align_10 = Padding.size(12, alignment=10)
assert align_16 == 4
assert align_12 == 0
assert align_10 == 8
def test_remove_padding():
payload = 8 * b'\x88' + b'\x00\x00\x00\x04'
unpadded = Padding.remove(payload)
assert len(unpadded) == 8
assert unpadded == 8 * b'\x88'
def test_x923_add_padding():
payload = 7 * b'\x69'
padded_12 = ANSIX923Padding.pad(payload, alignment=12)
padded_7 = ANSIX923Padding.pad(payload, alignment=7)
padded_3 = ANSIX923Padding.pad(payload, alignment=3)
assert len(padded_12) == 12
assert len(padded_7) == 7
assert len(padded_3) == 9
assert padded_12 == payload + b'\x00\x00\x00\x00\x05'
assert padded_7 == payload
assert padded_3 == payload + b'\x00\x02'
def test_pkcs7_add_padding():
payload = 7 * b'\x69'
padded_12 = PKCS7Padding.pad(payload, alignment=12)
padded_7 = PKCS7Padding.pad(payload, alignment=7)
padded_3 = PKCS7Padding.pad(payload, alignment=3)
assert len(padded_12) == 12
assert len(padded_7) == 7
assert len(padded_3) == 9
assert padded_12 == payload + b'\x05\x05\x05\x05\x05'
assert padded_7 == payload
assert padded_3 == payload + b'\x02\x02'
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,105 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/rest/deps.py | from typing import Tuple, Optional
import aiohttp
from fastapi import Query, Header, HTTPException, status
from xbox.webapi.api.language import DefaultXboxLiveLanguages, XboxLiveLanguage
from . import singletons
from .common import generate_authentication_status
from .schemas.auth import AuthenticationStatus
from xbox.webapi.api.client import XboxLiveClient
def console_connected(liveid: str):
console = singletons.console_cache.get(liveid)
if not console:
raise HTTPException(status_code=400, detail=f'Console {liveid} is not alive')
elif not console.connected:
raise HTTPException(status_code=400, detail=f'Console {liveid} is not connected')
return console
def console_exists(liveid: str):
console = singletons.console_cache.get(liveid)
if not console:
raise HTTPException(status_code=400, detail=f'Console info for {liveid} is not available')
return console
async def get_xbl_client() -> Optional[XboxLiveClient]:
return singletons.xbl_client
def get_authorization(
anonymous: Optional[bool] = Query(default=True)
) -> Optional[AuthenticationStatus]:
if anonymous:
return None
elif not singletons.authentication_manager:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Authorization data not available'
)
return generate_authentication_status(singletons.authentication_manager)
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,106 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/sg/packer.py | """
Smartglass message un-/packing
Also handles de/encryption internally, this means:
You feed plaintext data (wrapped in :class:`.XStruct`) and you get plaintext data
**Note on encryption**
Depending on the packet-type, acquiring the `Initialization Vector` and
encrypting the `protected payload` happens differently:
* ConnectRequest: The `IV` is randomly chosen from calculated
Elliptic Curve (which happens in :class:`Crypto`) and is delivered
inside the `unprotected payload` section of the ConnectRequest message.
* Messages: The `IV` is generated by encrypting the first 16 bytes of
the `unencrypted` header.
**Note on padding**
If message has `protected payload` it might need padding according
to PKCS#7 (e.g. padding is in whole bytes, the value of each added byte is
the number of bytes that are added, i.e. N bytes, each of value N are
added. thx wikipedia).
"""
from construct import Int16ub
from xbox.sg.enum import PacketType
from xbox.sg.crypto import PKCS7Padding
from xbox.sg.packet import simple, message
from xbox.sg.utils.struct import flatten
class PackerError(Exception):
"""
Custom exceptions for usage in packer module
"""
pass
def unpack(buf, crypto=None):
"""
Unpacks messages from Smartglass CoreProtocol.
For messages that require decryption, a Crypto instance needs to be passed
as well.
The decryption happens in :class:`CryptoTunnel`.
Args:
buf (bytes): A byte string to be deserialized into a message.
crypto (Crypto): Instance of :class:`Crypto`.
Raises:
PackerError: On various errors, instance of :class:`PackerError`.
Returns:
Container: The deserialized message, instance of :class:`Container`.
"""
msg_struct = None
pkt_type = PacketType(Int16ub.parse(buf[:2]))
if pkt_type not in PacketType:
raise PackerError("Invalid packet type")
if pkt_type in simple.pkt_types:
msg_struct = simple.struct
elif pkt_type == PacketType.Message:
msg_struct = message.struct
return msg_struct.parse(buf, _crypto=crypto)
def pack(msg, crypto=None):
"""
Packs messages for Smartglass CoreProtocol.
For messages that require encryption, a Crypto instance needs to be passed
as well.
Args:
msg (XStructObj): A serializable message, instance of
:class:`XStructObj`.
crypto (Crypto): Instance of :class:`Crypto`.
Returns:
bytes: The serialized bytes.
"""
container = flatten(msg.container)
packed_unprotected = b''
packed_protected = b''
if container.get('unprotected_payload', None):
packed_unprotected = msg.subcon.unprotected_payload.build(
container.unprotected_payload, **container
)
if container.get('protected_payload', None):
packed_protected = msg.subcon.protected_payload.build(
container.protected_payload, **container
)
container.header.unprotected_payload_length = len(packed_unprotected)
container.header.protected_payload_length = len(packed_protected)
packed_header = msg.subcon.header.build(
container.header, **container
)
if container.get('protected_payload', None) and packed_protected:
connect_types = [PacketType.ConnectRequest, PacketType.ConnectResponse]
if container.header.pkt_type in connect_types:
iv = container.unprotected_payload.iv
elif container.header.pkt_type == PacketType.Message:
iv = crypto.generate_iv(packed_header[:16])
else:
raise PackerError("Incompatible packet type for encryption")
if PKCS7Padding.size(len(packed_protected), 16) > 0:
packed_protected = PKCS7Padding.pad(packed_protected, 16)
packed_protected = crypto.encrypt(iv, packed_protected)
buffer = packed_header + packed_unprotected + packed_protected
return buffer + crypto.hash(buffer)
else:
return packed_header + packed_unprotected
def payload_length(msg):
"""
Calculates the packed length in bytes of the given message.
Args:
msg (XStructObj): A serializable message, instance of
:class:`XStructObj`.
Returns:
int: The packed message length in bytes.
"""
container = flatten(msg.container)
packed_unprotected = b''
packed_protected = b''
if container.get('unprotected_payload', None):
packed_unprotected = msg.subcon.unprotected_payload.build(
container.unprotected_payload, **container
)
if container.get('protected_payload', None):
packed_protected = msg.subcon.protected_payload.build(
container.protected_payload, **container
)
return len(packed_unprotected + packed_protected)
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,107 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/handlers/text_input.py | """
Text smartglass client
"""
import logging
import asyncio
import aioconsole
LOGGER = logging.getLogger(__name__)
async def userinput_callback(console, prompt):
print('WAITING FOR TEXT INPUT...')
text = await aioconsole.ainput(prompt)
await console.send_systemtext_input(text)
await console.finish_text_input()
def on_text_config(payload):
pass
def on_text_input(console, payload):
asyncio.create_task(userinput_callback(console, console.text.text_prompt))
def on_text_done(payload):
pass
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,108 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/sg/utils/struct.py | """
Custom construct fields and utilities
"""
import construct
COMPILED = True
class XStruct(construct.Subconstruct):
def __init__(self, *args, **kwargs):
struct = construct.Struct(*args, **kwargs)
super(XStruct, self).__init__(struct)
self.compiled = self.compile() if COMPILED else None
def parse(self, data, **contextkw):
res = super(XStruct, self).parse(data, **contextkw)
return XStructObj(self, res)
def _parse(self, stream, context, path):
if self.compiled:
res = self.compiled._parse(stream, context, path)
else:
res = self.subcon._parse(stream, context, path)
return res
def _emitparse(self, code):
return self.subcon._emitparse(code)
def _find(self, item):
sub = next(
(s for s in self.subcon.subcons if s.name == item), None
)
if sub:
return sub
return None
def __call__(self, **kwargs):
return XStructObj(self)(**kwargs)
def __contains__(self, item):
return self._find(item) is not None
def __getattr__(self, item):
subcon = self._find(item)
if subcon:
return subcon
return super(XStruct, self).__getattribute__(item)
class XStructObj(construct.Subconstruct):
__slots__ = ['_obj']
def __init__(self, struct, container=None):
super(XStructObj, self).__init__(struct)
self._obj = container if container else construct.Container({
sc.name: None for sc in self.subcon.subcon.subcons
})
@property
def container(self):
return self._obj
def __call__(self, **kwargs):
self._obj.update(kwargs)
return self
def _parse(self, stream, context, path):
self._obj = self.subcon._parse(stream, context, path)
return self
def build(self, **contextkw):
return self.subcon.build(self._obj, **contextkw)
def _build(self, stream, context, path):
return self.subcon._build(self._obj, stream, context, path)
def __getattr__(self, item):
if item in self._obj:
return getattr(self._obj, item)
return super(XStructObj, self).__getattribute__(item)
def __repr__(self):
return '<XStructObj: %s>(%s)' % (
self.subcon.name, self._obj
)
def flatten(container):
"""
Flattens `StructWrap` objects into just `Container`'s.
Recursively walks down each value of the `Container`, flattening
possible `StructWrap` objects.
Args:
container (Container): The container to flatten.
Returns:
`Container`: A flattened container.
"""
obj = container.copy()
for k, v in obj.items():
if isinstance(v, XStructObj):
obj[k] = flatten(v.container)
return obj
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,109 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/scripts/recrypt.py | """
Encrypt smartglass messages (type 0xD00D) with a new key
Example:
usage: xbox_recrypt [-h] src_path src_secret dst_path dst_secret
Re-Encrypt raw smartglass packets from a given filepath
positional arguments:
src_path Path to sourcefiles
src_secret Source shared secret in hex-format
dst_path Path to destination
dst_secret Target shared secret in hex-format
optional arguments:
-h, --help show this help message and exit
"""
import os
import sys
import argparse
from binascii import unhexlify
from construct import Int16ub
from xbox.sg.crypto import Crypto
from xbox.sg.enum import PacketType
def main():
parser = argparse.ArgumentParser(
description='Re-Encrypt raw smartglass packets from a given filepath'
)
parser.add_argument('src_path', type=str, help='Path to sourcefiles')
parser.add_argument('src_secret', type=str, help='Source shared secret in hex-format')
parser.add_argument('dst_path', type=str, help='Path to destination')
parser.add_argument('dst_secret', type=str, help='Target shared secret in hex-format')
args = parser.parse_args()
src_secret = unhexlify(args.src_secret)
dst_secret = unhexlify(args.dst_secret)
src_path = args.src_path
dst_path = args.dst_path
if len(src_secret) != 64:
print('Source key of invalid length supplied!')
sys.exit(1)
elif len(dst_secret) != 64:
print('Destination key of invalid length supplied!')
sys.exit(1)
source_crypto = Crypto.from_shared_secret(src_secret)
dest_crypto = Crypto.from_shared_secret(dst_secret)
source_path = os.path.dirname(src_path)
dest_path = os.path.dirname(dst_path)
for f in os.listdir(source_path):
src_filepath = os.path.join(source_path, f)
with open(src_filepath, 'rb') as sfh:
encrypted = sfh.read()
if Int16ub.parse(encrypted[:2]) != PacketType.Message.value:
print('Invalid magic, %s not a smartglass message, ignoring'
% src_filepath)
continue
# Slice the encrypted data manually
header = encrypted[:26]
payload = encrypted[26:-32]
hash = encrypted[-32:]
if not source_crypto.verify(encrypted[:-32], hash):
print('Hash mismatch, ignoring')
continue
# Decrypt with source shared secret
iv = source_crypto.generate_iv(header[:16])
decrypted_payload = source_crypto.decrypt(iv, payload)
# Encrypt with destination parameters
new_iv = dest_crypto.generate_iv(header[:16])
recrypted = dest_crypto.encrypt(new_iv, decrypted_payload)
new_hash = dest_crypto.hash(header + recrypted)
new_packet = header + recrypted + new_hash
with open(os.path.join(dest_path, f), 'wb') as dfh:
dfh.write(new_packet)
if __name__ == '__main__':
main()
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,110 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /tests/test_managers.py | import pytest
@pytest.mark.skip(reason="Not Implemented")
def test_x1():
pass
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,111 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /tests/test_console.py | from xbox.sg import console
from xbox.sg import enum
from xbox.sg import packer
def test_init(public_key, uuid_dummy):
c = console.Console(
'10.0.0.23', 'XboxOne', uuid_dummy, 'FFFFFFFFFFF',
enum.PrimaryDeviceFlag.AllowConsoleUsers, 0, public_key
)
assert c.address == '10.0.0.23'
assert c.flags == enum.PrimaryDeviceFlag.AllowConsoleUsers
assert c.name == 'XboxOne'
assert c.uuid == uuid_dummy
assert c.liveid == 'FFFFFFFFFFF'
assert c._public_key is not None
assert c._crypto is not None
assert c.device_status == enum.DeviceStatus.Unavailable
assert c.connection_state == enum.ConnectionState.Disconnected
assert c.pairing_state == enum.PairedIdentityState.NotPaired
assert c.paired is False
assert c.available is False
assert c.connected is False
assert c.authenticated_users_allowed is False
assert c.anonymous_connection_allowed is False
assert c.console_users_allowed is True
assert c.is_certificate_pending is False
def test_init_from_message(packets, crypto, uuid_dummy):
msg = packer.unpack(packets['discovery_response'], crypto)
c = console.Console.from_message('10.0.0.23', msg)
assert c.address == '10.0.0.23'
assert c.flags == enum.PrimaryDeviceFlag.AllowAuthenticatedUsers
assert c.name == 'XboxOne'
assert c.uuid == uuid_dummy
assert c.liveid == 'FFFFFFFFFFF'
assert c._public_key is not None
assert c._crypto is not None
assert c.device_status == enum.DeviceStatus.Available
assert c.connection_state == enum.ConnectionState.Disconnected
assert c.pairing_state == enum.PairedIdentityState.NotPaired
assert c.paired is False
assert c.available is True
assert c.connected is False
assert c.authenticated_users_allowed is True
assert c.anonymous_connection_allowed is False
assert c.console_users_allowed is False
assert c.is_certificate_pending is False
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,112 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/stump/manager.py | """
StumpManager - Handling TV Streaming / IR control commands
"""
import random
import logging
import requests
from typing import Union
from xbox.sg.utils.events import Event
from xbox.sg.enum import ServiceChannel
from xbox.sg.manager import Manager
from xbox.stump.enum import Message, Notification, Source, SourceHttpQuery, Quality
from xbox.stump import json_model
log = logging.getLogger(__name__)
class StumpException(Exception):
"""
Exception thrown by StumpManager
"""
pass
class StumpManager(Manager):
__namespace__ = 'stump'
def __init__(self, console):
"""
Title Manager (ServiceChannel.SystemInputTVRemote)
Args:
console: Console object
"""
super(StumpManager, self).__init__(
console, ServiceChannel.SystemInputTVRemote
)
self._msg_id_idx = 0
self._msg_id_prefix = random.randint(0, 0x7FFFFFFF)
self._appchannel_lineups = None
self._appchannel_data = None
self._appchannel_program_data = None
self._stump_config = None
self._stump_headend_info = None
self._stump_livetv_info = None
self._stump_program_info = None
self._stump_recent_channels = None
self._stump_tuner_lineups = None
self.on_response = Event()
self.on_notification = Event()
self.on_error = Event()
@property
def msg_id(self):
"""
Internal method for generating message IDs.
Returns:
str: A new message ID.
"""
self._msg_id_idx += 1
return '{:08x}.{:d}'.format(self._msg_id_prefix, self._msg_id_idx)
def generate_stream_url(self, source: Source, xuid: str = None, quality: Quality = Quality.BEST) -> str:
"""
Generate TV Streaming URL (Dvb-USB tuner, not hdmi-in)
Args:
source: Streaming source
xuid: optional, XUID
quality: Streaming quality
Returns: HTTP URL
"""
src_map = {
Source.HDMI: SourceHttpQuery.HDMI,
Source.TUNER: SourceHttpQuery.TUNER
}
if isinstance(quality, str):
quality = Quality(quality)
if isinstance(source, str):
source = Source(source)
if not self.streaming_port:
raise StumpException('No streaming port available to generate URL')
elif source not in (Source.TUNER, Source.HDMI):
raise StumpException('Invalid source parameter to generate URL')
url = 'http://{address}:{port}/{url_src}'.format(
address=self.console.address,
port=self.streaming_port,
url_src=src_map.get(source).value
)
params = {
'xuid': xuid,
'quality': quality.value
}
r = requests.Request(method='GET', url=url, params=params).prepare()
return r.url
def _on_json(self, data: dict, channel: int) -> None:
"""
Internal handler for JSON messages received by the core protocol.
Args:
data: The JSON object that was received.
channel: The channel this message was received on.
Returns:
None.
"""
msg = json_model.deserialize_stump_message(data)
if msg.msgid:
self.console.protocol._set_result(msg.msgid, msg)
if isinstance(msg, json_model.StumpError):
log.debug("Error msg: {}".format(msg))
self._on_error(msg)
elif isinstance(msg, json_model.StumpResponse):
log.debug("Response msg: {}".format(msg))
self._on_response(msg.response, msg)
elif isinstance(msg, json_model.StumpNotification):
log.debug("Notification msg: {}".format(msg))
self._on_notification(msg.notification, msg)
else:
log.warning("Unknown stump message: {}".format(data))
def _on_response(self, message_type: Union[Message, str], data: json_model.StumpResponse) -> None:
"""
Internal response handler. For logging purposes.
Args:
message_type: The message type.
data: The raw message.
"""
if isinstance(message_type, str):
message_type = Message(message_type)
params = data.params
if Message.CONFIGURATION == message_type:
self._stump_config = params
elif Message.HEADEND_INFO == message_type:
self._stump_headend_info = params
elif Message.LIVETV_INFO == message_type:
self._stump_livetv_info = params
elif Message.TUNER_LINEUPS == message_type:
self._stump_tuner_lineups = params
elif Message.RECENT_CHANNELS:
self._stump_recent_channels = params
elif Message.PROGRAMM_INFO:
self._stump_program_info = params
elif Message.APPCHANNEL_LINEUPS:
self._appchannel_lineups = params
elif Message.APPCHANNEL_DATA:
self._appchannel_data = params
elif Message.APPCHANNEL_PROGRAM_DATA:
self._appchannel_program_data = params
elif Message.SEND_KEY or \
Message.ENSURE_STREAMING_STARTED or \
Message.SET_CHANNEL:
# Refer to returned data from request_* methods
pass
log.info("Received {} response".format(message_type))
self.on_response(message_type, data)
def _on_notification(self, notification: Union[Notification, str], data: json_model.StumpNotification) -> None:
"""
Internal notification handler. For logging purposes.
Args:
notification: The notification type.
data: The raw message.
"""
if isinstance(notification, str):
notification = Notification(notification)
log.info("Received {} notification: {}".format(notification, data))
self.on_notification(notification, data)
def _on_error(self, data: json_model.StumpError) -> None:
"""
Internal error handler.
Args:
data: The error dictionary from the Message.
"""
log.error("Error: {}".format(data))
self.on_error(data)
async def _send_stump_message(self, name, params=None, msgid=None, timeout=3):
"""
Internal method for sending JSON messages over the core protocol.
Handles message IDs as well as waiting for results.
Args:
name (Enum): Request name
params (dict): The message parameters to send.
msgid (str): Message identifier
timeout (int): Timeout in seconds
Returns:
dict: The received result.
"""
if not msgid:
msgid = self.msg_id
msg = json_model.StumpRequest(msgid=msgid, request=name.value, params=params)
await self._send_json(msg.dict())
result = await self.console.protocol._await_ack(msgid, timeout)
if not result:
raise StumpException("Message \'{}\': \'{}\' got no response!".format(msgid, name))
return result
async def request_stump_configuration(self) -> dict:
"""
Request device configuration from console.
The configuration holds info about configured, by Xbox controlable \
devices (TV, AV, STB).
Returns:
dict: The received result.
"""
return await self._send_stump_message(Message.CONFIGURATION)
async def request_headend_info(self) -> dict:
"""
Request available headend information from console.
Returns: The received result.
"""
return await self._send_stump_message(Message.HEADEND_INFO)
async def request_live_tv_info(self) -> dict:
"""
Request LiveTV information from console.
Holds information about currently tuned channel, streaming-port etc.
Returns: The received result.
"""
return await self._send_stump_message(Message.LIVETV_INFO)
async def request_program_info(self) -> dict:
"""
Request program information.
NOTE: Not working?!
Returns: The received result.
"""
return await self._send_stump_message(Message.PROGRAMM_INFO)
async def request_tuner_lineups(self) -> dict:
"""
Request Tuner Lineups from console.
Tuner lineups hold information about scanned / found channels.
Returns: The received result.
"""
return await self._send_stump_message(Message.TUNER_LINEUPS)
async def request_app_channel_lineups(self) -> dict:
"""
Request AppChannel Lineups.
Returns: The received result.
"""
return await self._send_stump_message(Message.APPCHANNEL_LINEUPS)
async def request_app_channel_data(self, provider_id: str, channel_id: str) -> dict:
"""
Request AppChannel Data.
Args:
provider_id: Provider ID.
channel_id: Channel ID.
Returns: The received result.
"""
return self._send_stump_message(
Message.APPCHANNEL_DATA,
params={
'providerId': provider_id,
'channelId': channel_id,
'id': channel_id
}
)
async def request_app_channel_program_data(self, provider_id: str, program_id: str) -> dict:
"""
Request AppChannel Program Data.
Args:
provider_id: Provider ID.
program_id: Program Id.
Returns: The received result.
"""
return await self._send_stump_message(
Message.APPCHANNEL_PROGRAM_DATA,
params={
'providerId': provider_id,
'programId': program_id
}
)
async def set_stump_channel_by_id(self, channel_id: str, lineup_id: str) -> dict:
"""
Switch to channel by providing channel ID and lineup ID.
Args:
channel_id: Channel ID.
lineup_id: Lineup ID.
Returns: The received result.
"""
return await self._send_stump_message(
Message.SET_CHANNEL,
params={
'channelId': channel_id,
'lineupInstanceId': lineup_id
}
)
async def set_stump_channel_by_name(self, channel_name: str) -> dict:
"""
Switch to channel by providing channel name.
Args:
channel_name: Channel name to switch to.
Returns: The received result.
"""
return await self._send_stump_message(
Message.SET_CHANNEL,
params={
'channel_name': channel_name
}
)
async def request_recent_channels(self, first: int, count: int) -> dict:
"""
Request a list of recently watched channels.
Args:
first: Where to start enumeration.
count: Number of channels to request.
Returns: The received result.
"""
return await self._send_stump_message(
Message.RECENT_CHANNELS,
params={
'startindex': first,
'count': count
}
)
async def send_stump_key(self, button: str, device_id: str = None, **kwargs) -> dict:
"""
Send a remote control button to configured device via \
Xbox's IR Blaster / Kinect / whatev.
Args:
button: Button to send.
device_id: Device ID of device to control.
Returns: The received result.
"""
params = dict(button_id=button)
if device_id:
params['device_id'] = device_id
if kwargs:
params.update(**kwargs)
return await self._send_stump_message(
Message.SEND_KEY,
params=params
)
async def request_ensure_stump_streaming_started(self, source: Source) -> dict:
"""
Ensure that streaming started on desired tuner type
Args:
source: Tuner Source to check for.
Returns: The received result.
"""
return await self._send_stump_message(
Message.ENSURE_STREAMING_STARTED,
params={
'source': source.value
}
)
@property
def headend_locale(self):
if self._stump_headend_info:
return self._stump_headend_info.headendLocale
@property
def streaming_port(self):
if self._stump_livetv_info:
return self._stump_livetv_info.streamingPort
@property
def is_hdmi_mode(self):
if self._stump_livetv_info:
return self._stump_livetv_info.inHdmiMode
@property
def current_tunerchannel_type(self):
if self._stump_livetv_info:
return self._stump_livetv_info.tunerChannelType
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,113 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/scripts/pcap.py | """
Parse a pcap packet capture and show decrypted
packets in a human-readable ways.
Requires the shared secret for that smartglass-session.
"""
import os
import shutil
import string
import textwrap
import argparse
from binascii import unhexlify
import dpkt
from xbox.sg import packer
from xbox.sg.crypto import Crypto
from xbox.sg.enum import PacketType
from construct.lib import containers
containers.setGlobalPrintFullStrings(True)
def packet_filter(filepath):
with open(filepath, 'rb') as fh:
for ts, buf in dpkt.pcap.Reader(fh):
eth = dpkt.ethernet.Ethernet(buf)
# Make sure the Ethernet data contains an IP packet
if not isinstance(eth.data, dpkt.ip.IP):
continue
ip = eth.data
if not isinstance(ip.data, dpkt.udp.UDP):
continue
udp = ip.data
if udp.sport != 5050 and udp.dport != 5050:
continue
is_client = udp.dport == 5050
yield(udp.data, is_client, ts)
def parse(pcap_filepath, crypto):
width = shutil.get_terminal_size().columns
col_width = width // 2 - 3
wrapper = textwrap.TextWrapper(col_width, replace_whitespace=False)
for packet, is_client, ts in packet_filter(pcap_filepath):
try:
msg = packer.unpack(packet, crypto)
except Exception as e:
print("Error: {}".format(e))
continue
msg_type = msg.header.pkt_type
type_str = msg_type.name
if msg_type == PacketType.Message:
type_str = msg.header.flags.msg_type.name
direction = '>' if is_client else '<'
print(' {} '.format(type_str).center(width, direction))
lines = str(msg).split('\n')
for line in lines:
line = wrapper.wrap(line)
for i in line:
if is_client:
print('{0: <{1}}'.format(i, col_width), '│')
else:
print(' ' * col_width, '│', '{0}'.format(i, col_width))
def main():
parser = argparse.ArgumentParser(
description='Parse PCAP files and show SG sessions'
)
parser.add_argument('file', help='Path to PCAP')
parser.add_argument('secret', help='Expanded secret for this session.')
args = parser.parse_args()
secret = args.secret
if os.path.exists(secret):
# Assume a file containing the secret
with open(secret, 'rb') as fh:
secret = fh.read()
if all(chr(c) in string.hexdigits for c in secret):
secret = unhexlify(secret)
else:
secret = unhexlify(secret)
crypto = Crypto.from_shared_secret(secret)
parse(args.file, crypto)
if __name__ == '__main__':
main()
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,114 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/handlers/fallout4_relay.py | """
Fallout 4 AuxiliaryStream Relay client
Tunnels packets via TCP/27000 - compatible with regular PipBoy-clients
"""
import logging
import asyncio
from xbox.auxiliary.relay import AuxiliaryRelayService
from xbox.sg.utils.struct import XStructObj
LOGGER = logging.getLogger(__name__)
FALLOUT_TITLE_ID = 0x4ae8f9b2
LOCAL_PIPBOY_PORT = 27000
def on_connection_info(info: XStructObj):
loop = asyncio.get_running_loop()
print('Setting up relay on TCP/{0}...\n'.format(LOCAL_PIPBOY_PORT))
service = AuxiliaryRelayService(loop, info, listen_port=LOCAL_PIPBOY_PORT)
service.run()
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,115 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/sg/utils/adapters.py | """
Adapters and other Construct utility classes
"""
import json
import construct
from io import BytesIO
from enum import Enum
from uuid import UUID
from cryptography import x509
from cryptography.x509.oid import NameOID
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.serialization import Encoding
from xbox.sg.enum import PacketType
class CryptoTunnel(construct.Subconstruct):
"""
Adapter/Tunnel for inline decryption of protected payloads.
Depending on the packet-type, acquiring the `Initialization Vector` and
decrypting the `protected payload` happens differently:
* ConnectResponse: The `IV` is delivered in the `unprotected payload`
section of the packet and can be used directly
* Messages: The `IV` is generated by encrypting the first 16 bytes of
the packet header using the IV key.
Inline encryption using this Tunnel is not (yet) possible due to
limitations in Construct. As explained above, the `IV` for Messages is
generated by encrypting the first 16 bytes of the header. However, there's
currently no method of determining the length of the payload without
building it first. Therefor, the `IV` wouldn't be correct.
"""
def _parse(self, stream, context, path):
return self.subcon._parse(self.decrypt(stream, context), context, path)
@staticmethod
def decrypt(stream, context):
# To simplify message definition, we allow Switch to be a subcon
# of CryptoAdapter
# However, as a side effect, this function will also be called when the
# stream is EOF (has no protected payload)
# To compensate for this, we check if there's at least a hash + 1 block
# left in the stream
pos = stream.tell()
if len(stream.read(48)) != 48:
return None
crypto = context.get('_crypto', None) or context._.get('_crypto', None)
if not crypto:
raise ValueError("Crypto instance not passed in context")
stream.seek(0)
buf = stream.read()
if not crypto.verify(buf[:-32], buf[-32:]):
raise ValueError("Checksum doesn't match")
connect_types = [PacketType.ConnectRequest, PacketType.ConnectResponse]
if context.header.pkt_type in connect_types:
iv = context.unprotected_payload.iv
elif context.header.pkt_type == PacketType.Message:
iv = crypto.generate_iv(buf[:16])
else:
raise ValueError("Incompatible packet type")
buf = buf[pos:]
decrypted = crypto.decrypt(iv, buf)
decrypted = decrypted[:context.header.protected_payload_length]
return BytesIO(decrypted)
def _emitparse(self, code):
# Hack
code.append('from xbox.sg.utils.adapters import CryptoTunnel')
subcode = self.subcon._emitparse(code)
return subcode.replace('(io', '(CryptoTunnel.decrypt(io, this)')
class JsonAdapter(construct.Adapter):
"""
Construct-Adapter for JSON field.
Parses and dumps JSON.
"""
def _encode(self, obj, context, path):
if not isinstance(obj, dict):
raise TypeError('Object not of type dict')
return json.dumps(obj, separators=(',', ':'), sort_keys=True)
def _decode(self, obj, context, path):
return json.loads(obj)
def _emitparse(self, code):
code.append('import json')
return 'json.loads({})'.format(self.subcon._emitparse(code))
class UUIDAdapter(construct.Adapter):
def __init__(self, encoding=None):
"""
Construct-Adapter for UUID field.
Parses either `utf8` encoded or raw byte strings into :class:`UUID`
instances.
Args:
encoding (str): The encoding to use.
"""
if encoding:
super(self.__class__, self).__init__(SGString(encoding))
else:
super(self.__class__, self).__init__(construct.Bytes(0x10))
def _encode(self, obj, context, path):
if not isinstance(obj, UUID):
raise TypeError('Object not of type UUID')
if isinstance(self.subcon, construct.Bytes):
return obj.bytes
else:
return str(obj).upper()
def _decode(self, obj, context, path):
if isinstance(self.subcon, construct.Bytes):
return UUID(bytes=obj)
else:
return UUID(obj)
def _emitparse(self, code):
code.append('from uuid import UUID')
subcon_code = self.subcon._emitparse(code)
if isinstance(self.subcon, construct.Bytes):
return 'UUID(bytes={})'.format(subcon_code)
return 'UUID({})'.format(subcon_code)
class CertificateAdapter(construct.Adapter):
def __init__(self):
"""
Construct-Adapter for Certificate field.
Parses and dumps the DER certificate as used in the discovery response
messages.
"""
super(self.__class__, self).__init__(PrefixedBytes(construct.Int16ub))
def _encode(self, obj, context, path):
if not isinstance(obj, CertificateInfo):
raise TypeError('Object not of type CertificateInfo')
return obj.dump()
def _decode(self, obj, context, path):
return CertificateInfo(obj)
def _emitparse(self, code):
code.append('from xbox.sg.utils.adapters import CertificateInfo')
return 'CertificateInfo({})'.format(self.subcon._emitparse(code))
class CertificateInfo(object):
def __init__(self, raw_cert):
"""
Helper class for parsing a x509 certificate.
Extracts `common_name` and `public_key` from the certificate.
Args:
raw_cert (bytes): The DER certificate to parse.
"""
self.cert = x509.load_der_x509_certificate(raw_cert, default_backend())
self.liveid = self.cert.subject.get_attributes_for_oid(
NameOID.COMMON_NAME)[0].value
self.pubkey = self.cert.public_key()
def dump(self, encoding=Encoding.DER):
return self.cert.public_bytes(encoding)
def __repr__(self):
return '<%s: liveid=%s, pubkey=%s>' % (
self.__class__.__name__, self.liveid, self.pubkey
)
def __eq__(self, other):
return self.cert == other.cert
class XSwitch(construct.Switch):
def _emitparse(self, code):
if not any([isinstance(k, Enum) for k in self.cases.keys()]):
return super(XSwitch, self)._emitparse(code)
fname = "factory_%s" % code.allocateId()
code.append("%s = {%s}" % (fname, ", ".join("%r : lambda io,this: %s" % (key.value, sc._compileparse(code))
for key, sc in self.cases.items()), ))
defaultfname = "compiled_%s" % code.allocateId()
code.append("%s = lambda io,this: %s" % (defaultfname, self.default._compileparse(code), ))
return "%s.get(%s.value, %s)(io, this)" % (fname, self.keyfunc, defaultfname)
class XEnum(construct.Adapter):
def __init__(self, subcon, enum=None):
"""
Construct-Adapter for Enum field.
Parses numeric fields into `XEnumInt`'s, which display the Enum name and value.
Args:
subcon (Construct): The subcon to adapt.
enum (Enum): The enum to parse into.
"""
super(XEnum, self).__init__(subcon)
self.enum = enum
def _encode(self, obj, context, path):
if isinstance(obj, int):
return obj
return obj.value
def _decode(self, obj, context, path):
if not self.enum:
return obj
return self.enum(obj)
def _emitparse(self, code):
if not self.enum:
return self.subcon._emitparse(code)
code.append('from {} import {}'.format(self.enum.__module__, self.enum.__name__))
return '{}({})'.format(self.enum.__name__, self.subcon._emitparse(code))
class XInject(construct.Construct):
def __init__(self, code):
super(XInject, self).__init__()
self.flagbuildnone = True
self.name = '__inject'
self.code = code
def _parse(self, stream, context, path):
pass
def _build(self, obj, stream, context, path):
pass
def _sizeof(self, context, path):
return 0
def _emitparse(self, code):
code.append(self.code)
class TerminatedField(construct.Subconstruct):
def __init__(self, subcon, length=1, pattern=b'\x00'):
"""
A custom :class:`Subconstruct` that adds a termination character at
the end of the child struct.
Args:
subcon (Construct): The subcon to add the terminated character to.
length (int): The amount of termination characters to add.
pattern (bytes): The termination pattern to use.
"""
super(self.__class__, self).__init__(subcon)
self.padding = construct.Padding(length, pattern)
def _parse(self, stream, context, path):
obj = self.subcon._parse(stream, context, path)
self.padding._parse(stream, context, path)
return obj
def _build(self, obj, stream, context, path):
subobj = self.subcon._build(obj, stream, context, path)
self.padding._build(obj, stream, context, path)
return subobj
def _sizeof(self, context, path):
return self.subcon._sizeof(context, path) + 1
def _emitparse(self, code):
return '({}, {})[0]'.format(
self.subcon._emitparse(code), self.padding._emitparse(code)
)
def SGString(encoding='utf8'):
"""
Defines a null terminated `PascalString`.
The Smartglass protocol seems to always add a termination character
behind a length prefixed string.
This utility function combines a `PascalString` with a `TerminatedField`.
Args:
encoding (str): The string encoding to use for the `PascalString`.
Returns:
SGString: A null byte terminated `PascalString`.
"""
return TerminatedField(construct.PascalString(construct.Int16ub, encoding))
def PrefixedBytes(lengthfield):
"""
Defines a length prefixed bytearray.
Args:
lengthfield (:class:`Subconstruct`): The length subcon.
Returns:
PrefixedBytes: A length prefixed bytesarray
"""
return construct.Prefixed(lengthfield, construct.GreedyBytes)
class FieldIn(object):
"""
Helper class for creating an `in` conditional.
Operates like `field in options`.
Args:
field: The struct field to use.
options (list): A list with options to execute the `in` conditional on.
Returns:
bool: Whether or not the field value was in the options.
"""
def __init__(self, field, options):
self.field = field
self.options = options
def __call__(self, context):
return context.get(self.field, None) in self.options
def __repr__(self):
if any([isinstance(e, Enum) for e in self.options]):
return 'this.{}.value in {}'.format(self.field, [e.value for e in self.options])
return 'this.{} in {}'.format(self.field, self.options)
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,116 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /tests/test_cli_scripts.py | import pytest
@pytest.mark.script_launch_mode('subprocess')
def test_cli_rest_server(script_runner):
"""
Needs to be done in subprocess due to monkey-patching
"""
ret = script_runner.run('xbox-rest-server', '--help')
assert ret.success
def test_cli_maincli(script_runner):
ret = script_runner.run('xbox-cli', '--help')
assert ret.success
def test_cli_discover(script_runner):
ret = script_runner.run('xbox-discover', '--help')
assert ret.success
def test_cli_poweron(script_runner):
ret = script_runner.run('xbox-poweron', '--help')
assert ret.success
def test_cli_poweroff(script_runner):
ret = script_runner.run('xbox-poweroff', '--help')
assert ret.success
def test_cli_repl(script_runner):
ret = script_runner.run('xbox-repl', '--help')
assert ret.success
def test_cli_replserver(script_runner):
ret = script_runner.run('xbox-replserver', '--help')
assert ret.success
def test_cli_textinput(script_runner):
ret = script_runner.run('xbox-textinput', '--help')
assert ret.success
def test_cli_gamepadinput(script_runner):
ret = script_runner.run('xbox-gamepadinput', '--help')
assert ret.success
def test_cli_tui(script_runner):
ret = script_runner.run('xbox-tui', '--help')
assert ret.success
def test_cli_falloutrelay(script_runner):
ret = script_runner.run('xbox-fo4-relay', '--help')
assert ret.success
def test_cli_pcap(script_runner):
ret = script_runner.run('xbox-pcap', '--help')
assert ret.success
def test_cli_recrypt(script_runner):
ret = script_runner.run('xbox-recrypt', '--help')
assert ret.success
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,117 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/scripts/main_cli.py | """
Main smartglass client
Common script that handles several subcommands
See `Commands`
"""
import os
import sys
import logging
import argparse
import functools
import asyncio
import aioconsole
import aiohttp
from typing import List
from logging.handlers import RotatingFileHandler
from xbox.webapi.authentication.models import OAuth2TokenResponse
from xbox.scripts import TOKENS_FILE, CONSOLES_FILE, LOG_FMT, \
LOG_LEVEL_DEBUG_INCL_PACKETS, VerboseFormatter, ExitCodes
from xbox.handlers import tui, gamepad_input, text_input, fallout4_relay
from xbox.auxiliary.manager import TitleManager
from xbox.webapi.scripts import CLIENT_ID, CLIENT_SECRET, REDIRECT_URI
from xbox.webapi.authentication.manager import AuthenticationManager
from xbox.webapi.common.exceptions import AuthenticationException
from xbox.sg import manager
from xbox.sg.console import Console
from xbox.sg.enum import ConnectionState
LOGGER = logging.getLogger(__name__)
REPL_DEFAULT_SERVER_PORT = 5558
class Commands(object):
"""
Available commands for CLI
"""
Discover = 'discover'
PowerOn = 'poweron'
PowerOff = 'poweroff'
REPL = 'repl'
REPLServer = 'replserver'
FalloutRelay = 'forelay'
GamepadInput = 'gamepadinput'
TextInput = 'textinput'
TUI = 'tui'
def parse_arguments(args: List[str] = None):
"""
Parse arguments with argparse.ArgumentParser
Args:
args: List of arguments from cmdline
Returns: Parsed arguments
Raises:
Exception: On generic failure
"""
parser = argparse.ArgumentParser(description='Xbox SmartGlass client')
"""Common arguments for logging"""
logging_args = argparse.ArgumentParser(add_help=False)
logging_args.add_argument(
'--logfile',
help="Path for logfile")
logging_args.add_argument(
'-v', '--verbose', action='count', default=0,
help='Set logging level\n'
'( -v: INFO,\n'
' -vv: DEBUG,\n'
'-vvv: DEBUG_INCL_PACKETS)')
"""Common arguments for authenticated console connection"""
xbl_token_args = argparse.ArgumentParser(add_help=False)
xbl_token_args.add_argument(
'--tokens', '-t', type=str, default=TOKENS_FILE,
help='Tokenfile to load')
xbl_token_args.add_argument(
"--client-id",
"-cid",
default=os.environ.get("CLIENT_ID", CLIENT_ID),
help="OAuth2 Client ID",
)
xbl_token_args.add_argument(
"--client-secret",
"-cs",
default=os.environ.get("CLIENT_SECRET", CLIENT_SECRET),
help="OAuth2 Client Secret",
)
xbl_token_args.add_argument(
"--redirect-uri",
"-ru",
default=os.environ.get("REDIRECT_URI", REDIRECT_URI),
help="OAuth2 Redirect URI",
)
xbl_token_args.add_argument(
'--refresh', '-r', action='store_true',
help="Refresh xbox live tokens in provided token file")
"""Common argument for console connection"""
connection_arg = argparse.ArgumentParser(add_help=False)
connection_arg.add_argument(
'--address', '-a', type=str, default=None,
help="IP address of console")
connection_arg.add_argument(
'--liveid', '-l',
help='LiveID to poweron')
"""Common argument for interactively choosing console to handle"""
interactive_arg = argparse.ArgumentParser(add_help=False)
interactive_arg.add_argument(
'--interactive', '-i', action='store_true',
help="Interactively choose console to connect to")
"""
Define commands
"""
subparsers = parser.add_subparsers(help='Available commands')
# NOTE: Setting dest and required here for py3.6 compat
subparsers.dest = 'command'
subparsers.required = True
"""Discover"""
subparsers.add_parser(Commands.Discover,
help='Discover console',
parents=[logging_args,
connection_arg])
"""Power on"""
subparsers.add_parser(
Commands.PowerOn,
help='Power on console',
parents=[logging_args, connection_arg])
"""Power off"""
poweroff_cmd = subparsers.add_parser(
Commands.PowerOff,
help='Power off console',
parents=[logging_args, xbl_token_args,
interactive_arg, connection_arg])
poweroff_cmd.add_argument(
'--all', action='store_true',
help="Power off all consoles")
"""Local REPL"""
subparsers.add_parser(
Commands.REPL,
help='Local REPL (interactive console)',
parents=[logging_args, xbl_token_args,
interactive_arg, connection_arg])
"""REPL server"""
repl_server_cmd = subparsers.add_parser(
Commands.REPLServer,
help='REPL server (interactive console)',
parents=[logging_args, xbl_token_args,
interactive_arg, connection_arg])
repl_server_cmd.add_argument(
'--bind', '-b', default='127.0.0.1',
help='Interface address to bind the server')
repl_server_cmd.add_argument(
'--port', '-p', type=int, default=REPL_DEFAULT_SERVER_PORT,
help=f'Port to bind to, default: {REPL_DEFAULT_SERVER_PORT}')
"""Fallout relay"""
subparsers.add_parser(
Commands.FalloutRelay,
help='Fallout 4 Pip boy relay',
parents=[logging_args, xbl_token_args,
interactive_arg, connection_arg])
"""Controller input"""
subparsers.add_parser(
Commands.GamepadInput,
help='Send controller input to dashboard / apps',
parents=[logging_args, xbl_token_args,
interactive_arg, connection_arg])
"""Text input"""
subparsers.add_parser(
Commands.TextInput,
help='Client to use Text input functionality',
parents=[logging_args, xbl_token_args,
interactive_arg, connection_arg])
tui_cmd = subparsers.add_parser(
Commands.TUI,
help='TUI client - fancy :)',
parents=[logging_args, xbl_token_args,
connection_arg])
tui_cmd.add_argument(
'--consoles', '-c', default=CONSOLES_FILE,
help="Previously discovered consoles (json)")
return parser.parse_args(args)
def handle_logging_setup(args: argparse.Namespace) -> None:
"""
Determine log level, logfile and special DEBUG_INCL_PACKETS
via cmdline arguments.
Args:
args: ArgumentParser `Namespace`
Returns:
None
"""
levels = [logging.WARNING, logging.INFO, logging.DEBUG, LOG_LEVEL_DEBUG_INCL_PACKETS]
# Output level capped to number of levels
log_level = levels[min(len(levels) - 1, args.verbose)]
logging.basicConfig(level=log_level, format=LOG_FMT)
logging.root.info('Set Loglevel: {0}'
.format(logging.getLevelName(log_level)))
if log_level == LOG_LEVEL_DEBUG_INCL_PACKETS:
logging.root.info('Removing previous logging StreamHandlers')
while len(logging.root.handlers):
del logging.root.handlers[0]
logging.root.info('Using DEBUG_INCL_PACKETS logging')
debugext_handler = logging.StreamHandler()
debugext_handler.setFormatter(VerboseFormatter(LOG_FMT))
logging.root.addHandler(debugext_handler)
if args.logfile:
logging.root.info('Set Logfile path: {0}'.format(args.logfile))
file_handler = RotatingFileHandler(args.logfile, backupCount=2)
file_handler.setLevel(log_level)
file_handler.setFormatter(logging.Formatter(LOG_FMT))
logging.root.addHandler(file_handler)
async def do_authentication(args: argparse.Namespace) -> AuthenticationManager:
"""
Shortcut for doing xbox live authentication (uses xbox-webapi-python lib).
Args:
args: Parsed arguments
Returns: An authenticated instance of AuthenticationManager
Raises:
AuthenticationException: If authentication failed
"""
async with aiohttp.ClientSession() as session:
auth_mgr = AuthenticationManager(
session, args.client_id, args.client_secret, args.redirect_uri
)
# Refresh tokens if we have them
if os.path.exists(args.tokens):
with open(args.tokens, mode="r") as f:
tokens = f.read()
auth_mgr.oauth = OAuth2TokenResponse.parse_raw(tokens)
await auth_mgr.refresh_tokens()
# Request new ones if they are not valid
if not (auth_mgr.xsts_token and auth_mgr.xsts_token.is_valid()):
auth_url = auth_mgr.generate_authorization_url()
print(f'Authorize with following URL: {auth_url}\n')
code = input('Enter received authorization code: ')
await auth_mgr.request_tokens(code)
with open(args.tokens, mode="w") as f:
f.write(auth_mgr.oauth.json())
return auth_mgr
def choose_console_interactively(console_list: List[Console]):
"""
Choose a console to use via user-input
Args:
console_list (list): List of consoles to choose from
Returns:
None if choice was aborted, a desired console object otherwise
"""
entry_count = len(console_list)
LOGGER.debug('Offering console choices: {0}'.format(entry_count))
print('Discovered consoles:')
for idx, console in enumerate(console_list):
print(' {0}: {1} {2} {3}'
.format(idx, console.name, console.liveid, console.address))
print('Enter \'x\' to abort')
choices = [str(i) for i in range(entry_count)]
choices.append('e')
response = ''
while response not in choices:
response = input('Make your choice: ')
if response == 'e':
return None
return console_list[int(response)]
async def cli_discover_consoles(args: argparse.Namespace) -> List[Console]:
"""
Discover consoles
"""
LOGGER.info(f'Sending discovery packets to IP: {args.address}')
discovered = await Console.discover(addr=args.address, timeout=1)
if not len(discovered):
LOGGER.error('No consoles discovered')
sys.exit(ExitCodes.DiscoveryError)
LOGGER.info('Discovered consoles ({0}): {1}'
.format(len(discovered), ', '.join([str(c) for c in discovered])))
if args.liveid:
LOGGER.info('Filtering discovered consoles for LIVEID: {0}'
.format(args.liveid))
discovered = [c for c in discovered if c.liveid == args.liveid]
if args.address:
LOGGER.info('Filtering discovered consoles for IP address: {0}'
.format(args.address))
discovered = [c for c in discovered if c.address == args.address]
return discovered
async def main_async(loop: asyncio.AbstractEventLoop, command: Commands = None) -> ExitCodes:
"""
Async Main entrypoint
Args:
command (Commands):
Returns:
None
"""
auth_manager: AuthenticationManager = None
if command:
# Take passed command and append actual cmdline
cmdline_arguments = sys.argv[1:]
cmdline_arguments.insert(0, command)
else:
cmdline_arguments = None
args = parse_arguments(cmdline_arguments)
handle_logging_setup(args)
LOGGER.debug('Parsed arguments: {0}'.format(args))
command = args.command
LOGGER.debug('Chosen command: {0}'.format(command))
if 'interactive' in args and args.interactive and \
(args.address or args.liveid):
LOGGER.error('Flag \'--interactive\' is incompatible with'
' providing an IP address (--address) or LiveID (--liveid) explicitly')
sys.exit(ExitCodes.ArgParsingError)
elif args.liveid and args.address:
LOGGER.warning('You passed --address AND --liveid: Will only use that specific'
'combination!')
elif command == Commands.PowerOff and args.all and (args.liveid or args.address):
LOGGER.error('Poweroff with --all flag + explicitly provided LiveID / IP address makes no sense')
sys.exit(ExitCodes.ArgParsingError)
elif command == Commands.PowerOff and args.interactive and args.all:
LOGGER.error('Combining args --all and --interactive not supported')
sys.exit(ExitCodes.ArgParsingError)
print('Xbox SmartGlass main client started')
if 'tokens' in args:
"""
Do Xbox live authentication
"""
LOGGER.debug('Command {0} supports authenticated connection'.format(command))
print('Authenticating...')
try:
auth_manager = await do_authentication(args)
except AuthenticationException:
LOGGER.exception('Authentication failed!')
LOGGER.error("Please re-run xbox-authenticate to get a fresh set")
sys.exit(ExitCodes.AuthenticationError)
print('Authentication done')
if command == Commands.TUI:
"""
Text user interface (powered by urwid)
"""
# Removing stream handlers to not pollute TUI
for h in [sh for sh in logging.root.handlers
if isinstance(sh, logging.StreamHandler)]:
LOGGER.debug('Removing StreamHandler {0} from root logger'.format(h))
logging.root.removeHandler(h)
await tui.run_tui(loop, args.consoles, auth_manager)
return ExitCodes.OK
elif command == Commands.PowerOn:
"""
Powering up console
"""
if not args.liveid:
LOGGER.error('No LiveID (--liveid) provided for power on!')
sys.exit(ExitCodes.ArgParsingError)
LOGGER.info('Sending poweron packet for LiveId: {0} to {1}'
.format(args.liveid,
'IP: ' + args.address if args.address else 'MULTICAST'))
await Console.power_on(args.liveid, args.address, tries=10)
sys.exit(0)
"""
Discovery
"""
discovered = await cli_discover_consoles(args)
if command == Commands.Discover:
"""
Simply print discovered consoles
"""
print("Discovered %d consoles: " % len(discovered))
for console in discovered:
print(" %s" % console)
sys.exit(ExitCodes.OK)
elif command == Commands.PowerOff and args.all:
"""
Early call for poweroff --all
"""
"""Powering off all discovered consoles"""
for c in discovered:
print('Powering off console {0}'.format(c))
await c.power_off()
sys.exit(ExitCodes.OK)
"""
Choosing/filtering a console from the discovered ones
"""
console = None
if args.interactive:
LOGGER.debug('Starting interactive console choice')
console = choose_console_interactively(discovered)
elif len(discovered) == 1:
LOGGER.debug('Choosing sole console, no user interaction required')
console = discovered[0]
elif len(discovered) > 1:
LOGGER.error(
'More than one console was discovered and no exact'
' connection parameters were provided')
if not console:
LOGGER.error('Choosing a console failed!')
sys.exit(ExitCodes.ConsoleChoice)
LOGGER.info('Choosen target console: {0}'.format(console))
LOGGER.debug('Setting console callbacks')
console.on_device_status += \
lambda x: LOGGER.info('Device status: {0}'.format(x))
console.on_connection_state += \
lambda x: LOGGER.info('Connection state: {0}'.format(x))
console.on_pairing_state += \
lambda x: LOGGER.info('Pairing state: {0}'.format(x))
console.on_console_status += \
lambda x: LOGGER.info('Console status: {0}'.format(x))
console.on_timeout += \
lambda x: LOGGER.error('Timeout occured!') or sys.exit(1)
userhash = ''
xsts_token = ''
if auth_manager:
userhash = auth_manager.xsts_token.userhash
xsts_token = auth_manager.xsts_token.token
LOGGER.debug('Authentication info:')
LOGGER.debug('Userhash: {0}'.format(userhash))
LOGGER.debug('XToken: {0}'.format(xsts_token))
else:
LOGGER.info('Running in anonymous mode')
LOGGER.info('Attempting connection...')
state = await console.connect(userhash, xsts_token)
if state != ConnectionState.Connected:
LOGGER.error('Connection failed! Console: {0}'.format(console))
sys.exit(1)
# FIXME: Waiting explicitly
LOGGER.info('Connected to console: {0}'.format(console))
LOGGER.debug('Waiting a second before proceeding...')
await console.wait(1)
if command == Commands.PowerOff:
"""
Power off (single console)
"""
print('Powering off console {0}'.format(console))
await console.power_off()
sys.exit(ExitCodes.OK)
elif command == Commands.REPL or command == Commands.REPLServer:
banner = 'You are connected to the console @ {0}\n'\
.format(console.address)
banner += 'Type in \'console\' to acccess the object\n'
banner += 'Type in \'exit()\' to quit the application'
scope_vars = {'console': console}
if command == Commands.REPL:
LOGGER.info('Starting up local REPL console')
console = aioconsole.AsynchronousConsole(locals=scope_vars, loop=loop)
await console.interact(banner)
else:
startinfo = 'Starting up REPL server @ {0}:{1}'.format(args.bind, args.port)
print(startinfo)
LOGGER.info(startinfo)
server = await aioconsole.start_interactive_server(
host=args.bind, port=args.port, loop=loop)
await server
elif command == Commands.FalloutRelay:
"""
Fallout 4 relay
"""
print('Starting Fallout 4 relay service...')
console.add_manager(TitleManager)
console.title.on_connection_info += fallout4_relay.on_connection_info
await console.start_title_channel(
title_id=fallout4_relay.FALLOUT_TITLE_ID
)
print('Fallout 4 relay started')
elif command == Commands.GamepadInput:
"""
Gamepad input
"""
print('Starting gamepad input handler...')
console.add_manager(manager.InputManager)
await gamepad_input.input_loop(console)
elif command == Commands.TextInput:
"""
Text input
"""
print('Starting text input handler...')
console.add_manager(manager.TextManager)
console.text.on_systemtext_configuration += text_input.on_text_config
console.text.on_systemtext_input += functools.partial(text_input.on_text_input, console)
console.text.on_systemtext_done += text_input.on_text_done
while True:
try:
await asyncio.sleep(1)
except KeyboardInterrupt:
print('Quitting text input handler')
return ExitCodes.OK
def main(command: Commands = None):
LOGGER.debug('Entering main_async')
try:
loop = asyncio.get_event_loop()
loop.run_until_complete(main_async(loop, command))
except KeyboardInterrupt:
pass
def main_discover():
"""Entrypoint for discover script"""
main(Commands.Discover)
def main_poweron():
"""Entrypoint for poweron script"""
main(Commands.PowerOn)
def main_poweroff():
"""Entrypoint for poweroff script"""
main(Commands.PowerOff)
def main_repl():
"""Entrypoint for REPL script"""
main(Commands.REPL)
def main_replserver():
"""Entrypoint for REPL server script"""
main(Commands.REPLServer)
def main_falloutrelay():
"""Entrypoint for Fallout 4 relay script"""
main(Commands.FalloutRelay)
def main_textinput():
"""Entrypoint for Text input script"""
main(Commands.TextInput)
def main_gamepadinput():
"""Entrypoint for Gamepad input script"""
main(Commands.GamepadInput)
def main_tui():
"""Entrypoint for TUI script"""
main(Commands.TUI)
if __name__ == '__main__':
main()
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,118 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_namespace_packages
setup(
name="xbox-smartglass-core",
version="1.3.0",
author="OpenXbox",
author_email="noreply@openxbox.org",
description="A library to interact with the Xbox One gaming console via the SmartGlass protocol.",
long_description=open('README.md').read() + '\n\n' + open('CHANGELOG.md').read(),
long_description_content_type="text/markdown",
license="MIT",
keywords="xbox one smartglass auxiliary fallout title stump tv streaming livetv rest api",
url="https://github.com/OpenXbox/xbox-smartglass-core-python",
python_requires=">=3.7",
packages=find_namespace_packages(include=['xbox.*']),
zip_safe=False,
include_package_data=True,
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Topic :: Software Development :: Libraries :: Python Modules",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9"
],
test_suite="tests",
install_requires=[
'xbox-webapi==2.0.9',
'construct==2.10.56',
'cryptography==3.3.2',
'dpkt==1.9.4',
'pydantic==1.7.4',
'aioconsole==0.3.0',
'fastapi==0.65.2',
'uvicorn==0.12.2',
'urwid==2.1.2'
],
setup_requires=['pytest-runner'],
tests_require=['pytest', 'pytest-console-scripts', 'pytest-asyncio'],
extras_require={
"dev": [
"pip",
"bump2version",
"wheel",
"watchdog",
"flake8",
"coverage",
"Sphinx",
"sphinx_rtd_theme",
"recommonmark",
"twine",
"pytest",
"pytest-asyncio",
"pytest-console-scripts",
"pytest-runner",
],
},
entry_points={
'console_scripts': [
'xbox-cli=xbox.scripts.main_cli:main',
'xbox-discover=xbox.scripts.main_cli:main_discover',
'xbox-poweron=xbox.scripts.main_cli:main_poweron',
'xbox-poweroff=xbox.scripts.main_cli:main_poweroff',
'xbox-repl=xbox.scripts.main_cli:main_repl',
'xbox-replserver=xbox.scripts.main_cli:main_replserver',
'xbox-textinput=xbox.scripts.main_cli:main_textinput',
'xbox-gamepadinput=xbox.scripts.main_cli:main_gamepadinput',
'xbox-tui=xbox.scripts.main_cli:main_tui',
'xbox-fo4-relay=xbox.scripts.main_cli:main_falloutrelay',
'xbox-pcap=xbox.scripts.pcap:main',
'xbox-recrypt=xbox.scripts.recrypt:main',
'xbox-rest-server=xbox.scripts.rest_server:main'
]
}
)
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,119 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/rest/schemas/general.py | from typing import Dict, Optional
from pydantic import BaseModel
class GeneralResponse(BaseModel):
success: bool
details: Optional[Dict[str, str]]
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,120 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/rest/routes/root.py | from fastapi import APIRouter
from .. import schemas, SMARTGLASS_PACKAGENAMES
router = APIRouter()
@router.get('/', response_model=schemas.IndexResponse)
def get_index():
import pkg_resources
versions = {}
for name in SMARTGLASS_PACKAGENAMES:
try:
versions[name] = pkg_resources.get_distribution(name).version
except Exception:
versions[name] = None
return schemas.IndexResponse(
versions=versions,
doc_path='/docs'
)
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,121 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/rest/consolewrap.py | from typing import Dict, Optional
import logging
from xbox.sg import enum
from xbox.sg.console import Console
from xbox.sg.manager import InputManager, TextManager, MediaManager
from xbox.stump.manager import StumpManager
from xbox.stump import json_model as stump_schemas
from . import schemas
log = logging.getLogger()
class ConsoleWrap(object):
def __init__(self, console: Console):
self.console = console
if 'input' not in self.console.managers:
self.console.add_manager(InputManager)
if 'text' not in self.console.managers:
self.console.add_manager(TextManager)
if 'media' not in self.console.managers:
self.console.add_manager(MediaManager)
if 'stump' not in self.console.managers:
self.console.add_manager(StumpManager)
@staticmethod
async def discover(*args, **kwargs):
return await Console.discover(*args, **kwargs)
@staticmethod
async def power_on(
liveid: str, addr: str = None, iterations: int = 3, tries: int = 10
) -> None:
for i in range(iterations):
await Console.power_on(liveid, addr=addr, tries=tries)
await Console.wait(1)
@property
def media_commands(self) -> Dict[str, enum.MediaControlCommand]:
return {
'play': enum.MediaControlCommand.Play,
'pause': enum.MediaControlCommand.Pause,
'play_pause': enum.MediaControlCommand.PlayPauseToggle,
'stop': enum.MediaControlCommand.Stop,
'record': enum.MediaControlCommand.Record,
'next_track': enum.MediaControlCommand.NextTrack,
'prev_track': enum.MediaControlCommand.PreviousTrack,
'fast_forward': enum.MediaControlCommand.FastForward,
'rewind': enum.MediaControlCommand.Rewind,
'channel_up': enum.MediaControlCommand.ChannelUp,
'channel_down': enum.MediaControlCommand.ChannelDown,
'back': enum.MediaControlCommand.Back,
'view': enum.MediaControlCommand.View,
'menu': enum.MediaControlCommand.Menu,
'seek': enum.MediaControlCommand.Seek
}
@property
def input_keys(self) -> Dict[str, enum.GamePadButton]:
return {
'clear': enum.GamePadButton.Clear,
'enroll': enum.GamePadButton.Enroll,
'nexus': enum.GamePadButton.Nexu,
'menu': enum.GamePadButton.Menu,
'view': enum.GamePadButton.View,
'a': enum.GamePadButton.PadA,
'b': enum.GamePadButton.PadB,
'x': enum.GamePadButton.PadX,
'y': enum.GamePadButton.PadY,
'dpad_up': enum.GamePadButton.DPadUp,
'dpad_down': enum.GamePadButton.DPadDown,
'dpad_left': enum.GamePadButton.DPadLeft,
'dpad_right': enum.GamePadButton.DPadRight,
'left_shoulder': enum.GamePadButton.LeftShoulder,
'right_shoulder': enum.GamePadButton.RightShoulder,
'left_thumbstick': enum.GamePadButton.LeftThumbStick,
'right_thumbstick': enum.GamePadButton.RightThumbStick
}
@property
def liveid(self) -> str:
return self.console.liveid
@property
def last_error(self) -> int:
return self.console.last_error
@property
def available(self) -> bool:
return bool(self.console and self.console.available)
@property
def connected(self) -> bool:
return bool(self.console and self.console.connected)
@property
def usable(self) -> bool:
return bool(self.console and self.connected)
@property
def connection_state(self) -> enum.ConnectionState:
if not self.console:
return enum.ConnectionState.Disconnected
return self.console.connection_state
@property
def pairing_state(self) -> enum.PairedIdentityState:
if not self.console:
return enum.PairedIdentityState.NotPaired
return self.console.pairing_state
@property
def device_status(self) -> enum.DeviceStatus:
if not self.console:
return enum.DeviceStatus.Unavailable
return self.console.device_status
@property
def authenticated_users_allowed(self) -> bool:
return bool(self.console and self.console.authenticated_users_allowed)
@property
def console_users_allowed(self) -> bool:
return bool(self.console and self.console.console_users_allowed)
@property
def anonymous_connection_allowed(self) -> bool:
return bool(self.console and self.console.anonymous_connection_allowed)
@property
def is_certificate_pending(self) -> bool:
return bool(self.console and self.console.is_certificate_pending)
@property
def console_status(self) -> Optional[schemas.ConsoleStatusResponse]:
status_json = {}
if not self.console or not self.console.console_status:
return None
status = self.console.console_status
kernel_version = '{0}.{1}.{2}'.format(status.major_version, status.minor_version, status.build_number)
status_json.update({
'live_tv_provider': status.live_tv_provider,
'kernel_version': kernel_version,
'locale': status.locale
})
active_titles = []
for at in status.active_titles:
title = {
'title_id': at.title_id,
'aum': at.aum,
'name': at.aum,
'image': None,
'type': None,
'has_focus': at.disposition.has_focus,
'title_location': at.disposition.title_location.name,
'product_id': str(at.product_id),
'sandbox_id': str(at.sandbox_id)
}
active_titles.append(title)
status_json.update({'active_titles': active_titles})
return schemas.ConsoleStatusResponse(**status_json)
@property
def media_status(self) -> Optional[schemas.MediaStateResponse]:
if not self.usable or not self.console.media or not self.console.media.media_state:
return None
media_state = self.console.media.media_state
# Ensure we are in the same app, otherwise this is useless
if media_state.aum_id not in [t.aum for t in self.console.console_status.active_titles]:
return None
media_state_json = {
'title_id': media_state.title_id,
'aum_id': media_state.aum_id,
'asset_id': media_state.asset_id,
'media_type': media_state.media_type.name,
'sound_level': media_state.sound_level.name,
'enabled_commands': media_state.enabled_commands.value,
'playback_status': media_state.playback_status.name,
'rate': media_state.rate,
'position': media_state.position,
'media_start': media_state.media_start,
'media_end': media_state.media_end,
'min_seek': media_state.min_seek,
'max_seek': media_state.max_seek,
'metadata': None
}
metadata = {}
for meta in media_state.metadata:
metadata[meta.name] = meta.value
media_state_json['metadata'] = metadata
return schemas.MediaStateResponse(**media_state_json)
@property
def status(self) -> schemas.DeviceStatusResponse:
data = self.console.to_dict()
data.update({
'liveid': self.console.liveid,
'ip_address': self.console.address,
'connection_state': self.connection_state.name,
'pairing_state': self.pairing_state.name,
'device_status': self.device_status.name,
'last_error': self.last_error,
'authenticated_users_allowed': self.authenticated_users_allowed,
'console_users_allowed': self.console_users_allowed,
'anonymous_connection_allowed': self.anonymous_connection_allowed,
'is_certificate_pending': self.is_certificate_pending
})
return schemas.DeviceStatusResponse(**data)
@property
def text_active(self) -> bool:
if self.usable:
return self.console.text.got_active_session
async def get_stump_config(self) -> stump_schemas.Configuration:
if self.usable:
return await self.console.stump.request_stump_configuration()
async def get_headend_info(self) -> stump_schemas.HeadendInfo:
if self.usable:
return await self.console.stump.request_headend_info()
async def get_livetv_info(self) -> stump_schemas.LiveTvInfo:
if self.usable:
return await self.console.stump.request_live_tv_info()
async def get_tuner_lineups(self) -> stump_schemas.TunerLineups:
if self.usable:
return await self.console.stump.request_tuner_lineups()
async def connect(
self,
userhash: Optional[str] = None,
xtoken: Optional[str] = None
) -> enum.ConnectionState:
if not self.console:
return enum.ConnectionState.Disconnected
elif self.console.connected:
return enum.ConnectionState.Connected
elif not self.anonymous_connection_allowed and (not userhash or not xtoken):
raise Exception('Requested anonymous connection is not allowed by console')
state = await self.console.connect(userhash=userhash,
xsts_token=xtoken)
if state == enum.ConnectionState.Connected:
await self.console.wait(0.5)
await self.console.stump.request_stump_configuration()
return state
async def disconnect(self) -> bool:
await self.console.disconnect()
return True
async def power_off(self) -> bool:
await self.console.power_off()
return True
async def launch_title(self, app_id: str) -> None:
return await self.console.launch_title(app_id)
async def send_stump_key(self, device_id: str, button: str) -> bool:
result = await self.console.send_stump_key(button, device_id)
print(result)
return True
async def send_media_command(self, command: enum.MediaControlCommand, seek_position: Optional[int] = None) -> bool:
title_id = 0
request_id = 0
await self.console.media_command(title_id, command, request_id, seek_position)
return True
async def send_gamepad_button(self, btn: enum.GamePadButton) -> bool:
await self.console.gamepad_input(btn)
# Its important to clear button-press afterwards
await self.console.wait(0.1)
await self.console.gamepad_input(enum.GamePadButton.Clear)
return True
async def send_text(self, text: str) -> bool:
if not self.text_active:
return False
await self.console.send_systemtext_input(text)
await self.console.finish_text_input()
return True
async def dvr_record(self, start_delta, end_delta) -> bool:
await self.console.game_dvr_record(start_delta, end_delta)
return True
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,122 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/sg/console.py | """
Console
Console class is a wrapper around the protocol, can be used to
`discover`, `poweron` and `connect`.
Also stores various device status informations.
It can be either created manually or instantiated via `DiscoveryResponse`
message. However, calling static method `discover` does all that for you
automatically.
Example:
Discovery and connecting::
import sys
from xbox.sg.console import Console
from xbox.sg.enum import ConnectionState
discovered = await Console.discover(timeout=1)
if len(discovered):
console = discovered[0]
await console.connect()
if console.connection_state != ConnectionState.Connected:
print("Connection failed")
sys.exit(1)
await console.wait(1)
else:
print("No consoles discovered")
sys.exit(1)
... do stuff ...
"""
import asyncio
import socket
import logging
from uuid import UUID
from typing import Optional, List, Union, Dict, Type
from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicKey
from xbox.sg.crypto import Crypto
from xbox.sg.manager import Manager
from xbox.sg.enum import PairedIdentityState, DeviceStatus, ConnectionState, \
MessageType, PrimaryDeviceFlag, ActiveTitleLocation, AckStatus, \
ServiceChannel, MediaControlCommand, GamePadButton
from xbox.sg.protocol import SmartglassProtocol, ProtocolError
from xbox.sg.utils.events import Event
from xbox.sg.utils.struct import XStruct
from xbox.stump.manager import StumpManager
LOGGER = logging.getLogger(__name__)
class Console(object):
__protocol__: SmartglassProtocol = None
def __init__(
self,
address: str,
name: str,
uuid: UUID,
liveid: str,
flags: PrimaryDeviceFlag = PrimaryDeviceFlag.Null,
last_error: int = 0,
public_key: EllipticCurvePublicKey = None
):
"""
Initialize an instance of Console
Args:
address: IP address of console.
flags: Primary device flags
name: Name of console.
uuid: UUID of console.
liveid: Live ID of console.
public_key: Console's Public Key.
"""
self.address = address
self.name = name
self.uuid = uuid
self.liveid = liveid
self.flags = flags
self.last_error = last_error
self._public_key = None
self._crypto = None
if public_key:
# This sets up the crypto context
self.public_key = public_key
self._device_status = DeviceStatus.Unavailable
self._connection_state = ConnectionState.Disconnected
self._pairing_state = PairedIdentityState.NotPaired
self._console_status = None
self._active_surface = None
self.on_device_status = Event()
self.on_connection_state = Event()
self.on_pairing_state = Event()
self.on_console_status = Event()
self.on_active_surface = Event()
self.on_timeout = Event()
self.managers: Dict[str, Manager] = {}
self._functions = {}
self.on_message = Event()
self.on_json = Event()
self.power_on = self._power_on # Dirty hack
self.protocol: Optional[SmartglassProtocol] = None
def __repr__(self) -> str:
return f'<Console addr={self.address} name={self.name} ' \
f'uuid={self.uuid}liveid={self.liveid} flags={self.flags} ' \
f'last_error={self.last_error}>'
async def __aenter__(self):
return self
async def __aexit__(self) -> None:
await self.disconnect()
@staticmethod
async def wait(seconds: int) -> None:
"""
Wrapper around `asyncio.sleep`
Args:
seconds: Seconds to wait.
Returns: None
"""
await asyncio.sleep(seconds)
async def _ensure_protocol_started(self) -> None:
"""
Regular protocol instance, setup with crypto and destination address.
Targeted at communication with a specific console.
Returns:
None
"""
if not self.protocol:
loop = asyncio.get_running_loop()
_, self.protocol = await loop.create_datagram_endpoint(
lambda: SmartglassProtocol(self.address, self._crypto),
family=socket.AF_INET,
remote_addr=(self.address, 5050),
allow_broadcast=True
)
self.protocol.on_timeout += self._handle_timeout
self.protocol.on_message += self._handle_message
self.protocol.on_json += self._handle_json
@classmethod
async def _ensure_global_protocol_started(cls) -> None:
"""
Global protocol instance, used for network wide discovery and poweron.
"""
if not cls.__protocol__:
loop = asyncio.get_running_loop()
_, cls.__protocol__ = await loop.create_datagram_endpoint(
lambda: SmartglassProtocol(),
family=socket.AF_INET,
allow_broadcast=True
)
@classmethod
def from_message(cls, address: str, msg: XStruct):
"""
Initialize the class with a `DiscoveryResponse`.
Args:
address: IP address of the console
msg: Discovery Response struct
Returns: Console instance
"""
payload = msg.unprotected_payload
console = cls(
address, payload.name, payload.uuid, payload.cert.liveid,
payload.flags, payload.last_error, payload.cert.pubkey
)
console.device_status = DeviceStatus.Available
return console
@classmethod
def from_dict(cls, d: dict):
return cls(d['address'], d['name'], UUID(d['uuid']), d['liveid'])
def to_dict(self) -> dict:
return dict(
address=self.address,
name=self.name,
uuid=str(self.uuid),
liveid=self.liveid
)
def add_manager(self, manager: Type[Manager], *args, **kwargs):
"""
Add a manager to the console instance.
This will inherit all public methods of the manager class.
Args:
manager: Manager to add
*args: Arguments
**kwargs: KwArguments
Returns:
None
"""
if not issubclass(manager, Manager):
raise ValueError("Manager needs to subclass {}.{}".format(
Manager.__module__, Manager.__name__)
)
namespace = getattr(manager, '__namespace__', manager.__name__.lower())
manager_inst = manager(self, *args, **kwargs)
self.managers[namespace] = manager_inst
for item in dir(manager):
if item.startswith('_'):
continue
if item in self.__dict__:
raise ValueError("Attribute already exists: %s" % item)
self._functions[item] = getattr(manager_inst, item)
def __getattr__(self, k: str):
"""
Accessor to manager functions
Args:
k: Parameter name / key
Returns: Object requested by k
"""
if k in self.managers:
return self.managers[k]
elif k in self._functions:
return self._functions[k]
return object.__getattribute__(self, k)
@classmethod
async def discover(cls, *args, **kwargs) -> List:
"""
Discover consoles on the network.
Args:
*args:
**kwargs:
Returns:
list: List of discovered consoles.
"""
await cls._ensure_global_protocol_started()
discovered = await cls.__protocol__.discover(*args, **kwargs)
return [cls.from_message(a, m) for a, m in discovered.items()]
@classmethod
def discovered(cls) -> List:
"""
Get list of already discovered consoles.
Returns:
list: List of discovered consoles.
"""
discovered = cls.__protocol__.discovered
return [cls.from_message(a, m) for a, m in discovered.items()]
@classmethod
async def power_on(
cls,
liveid: str,
addr: Optional[str] = None,
tries=2
) -> None:
"""
Power On console with given Live ID.
Optionally the IP address of the console can be supplied,
this is useful if the console is stubborn and does not react
to broadcast / multicast packets (due to routing issues).
Args:
liveid (str): Live ID of console.
addr (str): IP address of console.
tries (int): Poweron attempts, default: 2.
Returns: None
"""
await cls._ensure_global_protocol_started()
await cls.__protocol__.power_on(liveid, addr, tries)
async def send_message(
self,
msg: XStruct,
channel: ServiceChannel = ServiceChannel.Core,
addr: Optional[str] = None,
blocking: bool = True,
timeout: int = 5,
retries: int = 3
) -> Optional[XStruct]:
"""
Send message to console.
Args:
msg: Unassembled message to send
channel: Channel to send the message on,
Enum member of `ServiceChannel`
addr: IP address of target console
blocking: If set and `msg` is `Message`-packet, wait for ack
timeout: Seconds to wait for ack, only useful if `blocking`
is `True`
retries: Max retry count.
Returns: None
"""
if not self.protocol:
LOGGER.error('send_message: Protocol not ready')
return
return await self.protocol.send_message(
msg, channel, addr, blocking, timeout, retries
)
async def json(
self,
data: str,
channel: ServiceChannel
) -> None:
"""
Send json message
Args:
data: JSON dict
channel: Channel to send the message to
Returns: None
"""
if not self.protocol:
LOGGER.error('json: Protocol not ready')
return
return await self.protocol.json(data, channel=channel)
async def _power_on(self, tries: int = 2) -> None:
await Console.power_on(self.liveid, self.address, tries)
async def connect(
self,
userhash: Optional[str] = None,
xsts_token: Optional[str] = None
) -> ConnectionState:
"""
Connect to the console
If the connection fails, error will be stored in
`self.connection_state`
Raises:
ConnectionException: If no authentication data is supplied and
console disallows anonymous connection.
Returns: Connection state
"""
if self.connected:
raise ConnectionError("Already connected")
auth_data_available = bool(userhash and xsts_token)
if not self.anonymous_connection_allowed and not auth_data_available:
raise ConnectionError("Anonymous connection not allowed, please"
" supply userhash and auth-token")
await self._ensure_protocol_started()
self.pairing_state = PairedIdentityState.NotPaired
self.connection_state = ConnectionState.Connecting
try:
self.pairing_state = await self.protocol.connect(
userhash=userhash,
xsts_token=xsts_token
)
except ProtocolError as e:
self.connection_state = ConnectionState.Error
raise e
self.connection_state = ConnectionState.Connected
return self.connection_state
async def launch_title(
self,
uri: str,
location: ActiveTitleLocation = ActiveTitleLocation.Full
) -> AckStatus:
"""
Launch a title by URI
Args:
uri: Launch uri
location: Target title location
Returns: Ack status
"""
return await self.protocol.launch_title(uri, location)
async def game_dvr_record(
self,
start_delta: int,
end_delta: int
) -> AckStatus:
"""
Start Game DVR recording
Args:
start_delta: Start time
end_delta: End time
Returns: Ack status
"""
return await self.protocol.game_dvr_record(start_delta, end_delta)
async def disconnect(self) -> None:
"""
Disconnect from console.
This will reset connection-, pairing-state,
ActiveSurface and ConsoleStatus.
Returns: None
"""
if self.connection_state == ConnectionState.Connected:
self.connection_state = ConnectionState.Disconnecting
await self._reset_state()
async def power_off(self) -> None:
"""
Power off the console.
No need to disconnect after.
Returns: None
"""
await self.protocol.power_off(self.liveid)
await self._reset_state()
self.device_status = DeviceStatus.Unavailable
def _handle_message(self, msg: XStruct, channel: ServiceChannel) -> None:
"""
Internal handler for console specific messages aka.
`PairedIdentityStateChange`, `ConsoleStatus` and
`ActiveSurfaceChange`.
Args:
msg: Message data
channel: Service channel
Returns:
None
"""
msg_type = msg.header.flags.msg_type
if msg_type == MessageType.PairedIdentityStateChanged:
self.pairing_state = msg.protected_payload.state
elif msg_type == MessageType.ConsoleStatus:
self.console_status = msg.protected_payload
elif msg_type == MessageType.ActiveSurfaceChange:
self.active_surface = msg.protected_payload
self.on_message(msg, channel)
def _handle_json(self, msg: XStruct, channel: ServiceChannel) -> None:
"""
Internal handler for JSON messages
Args:
msg: JSON message instance
channel: Service channel originating from
Returns: None
"""
self.on_json(msg, channel)
def _handle_timeout(self) -> None:
"""
Internal handler for console connection timeout.
Returns: None
"""
asyncio.create_task(self._reset_state())
self.device_status = DeviceStatus.Unavailable
self.on_timeout()
async def _reset_state(self) -> None:
"""
Internal handler to reset the inital state of the console instance.
Returns: None
"""
if self.protocol and self.protocol.started:
await self.protocol.stop()
await self._ensure_protocol_started()
self.connection_state = ConnectionState.Disconnected
self.pairing_state = PairedIdentityState.NotPaired
self.active_surface = None
self.console_status = None
@property
def public_key(self) -> EllipticCurvePublicKey:
"""
Console's public key.
Returns: Foreign public key
"""
return self._public_key
@public_key.setter
def public_key(self, key: Union[EllipticCurvePublicKey, bytes]) -> None:
if isinstance(key, bytes):
self._crypto = Crypto.from_bytes(key)
else:
self._crypto = Crypto(key)
self._public_key = self._crypto.foreign_pubkey
@property
def device_status(self) -> DeviceStatus:
"""
Current availability status
Returns:
:obj:`DeviceStatus`
"""
return self._device_status
@device_status.setter
def device_status(self, status: DeviceStatus) -> None:
self._device_status = status
self.on_device_status(status)
@property
def connection_state(self) -> ConnectionState:
"""
Current connection state
Returns: Connection state
"""
return self._connection_state
@connection_state.setter
def connection_state(self, state: ConnectionState) -> None:
self._connection_state = state
self.on_connection_state(state)
@property
def pairing_state(self) -> PairedIdentityState:
"""
Current pairing state
Returns:
:obj:`PairedIdentityState`
"""
return self._pairing_state
@pairing_state.setter
def pairing_state(self, state: PairedIdentityState) -> None:
self._pairing_state = state
self.on_pairing_state(state)
@property
def console_status(self):
"""
Console status aka. kernel version, active titles etc.
Returns:
:obj:`XStruct`
"""
return self._console_status
@console_status.setter
def console_status(self, status):
self._console_status = status
self.on_console_status(status)
@property
def active_surface(self):
"""
Currently active surface
Returns:
:obj:`XStruct`
"""
return self._active_surface
@active_surface.setter
def active_surface(self, active_surface) -> None:
self._active_surface = active_surface
self.on_active_surface(active_surface)
@property
def available(self) -> bool:
"""
Check whether console is available aka. discoverable
Returns: `True` if console is available, `False` otherwise
"""
return self.device_status == DeviceStatus.Available
@property
def paired(self) -> bool:
"""
Check whether client is paired to console
Returns: `True` if console is paired, `False` otherwise
"""
return self.pairing_state == PairedIdentityState.Paired
@property
def connected(self) -> bool:
"""
Check whether client is successfully connected to console
Returns: `True` if connected, `False` otherwise
"""
return self.connection_state == ConnectionState.Connected
@property
def authenticated_users_allowed(self) -> bool:
"""
Check whether authenticated users are allowed to connect
Returns: `True` if authenticated users are allowed, `False` otherwise
"""
return bool(self.flags & PrimaryDeviceFlag.AllowAuthenticatedUsers)
@property
def console_users_allowed(self) -> bool:
"""
Check whether console users are allowed to connect
Returns: `True` if console users are allowed, `False` otherwise
"""
return bool(self.flags & PrimaryDeviceFlag.AllowConsoleUsers)
@property
def anonymous_connection_allowed(self) -> bool:
"""
Check whether anonymous connection is allowed
Returns: `True` if anonymous connection is allowed, `False` otherwise
"""
return bool(self.flags & PrimaryDeviceFlag.AllowAnonymousUsers)
@property
def is_certificate_pending(self) -> bool:
"""
Check whether certificate is pending
Returns: `True` if certificate is pending, `False` otherwise
"""
return bool(self.flags & PrimaryDeviceFlag.CertificatePending)
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,123 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/sg/constants.py | """
Constant values used by SmartGlass
"""
from uuid import UUID
from xbox.sg.enum import ClientType, DeviceCapabilities
class AndroidClientInfo(object):
"""
Client Info for Android device (tablet). Used for LocalJoin messages
"""
DeviceType = ClientType.Android
# Resolution is portrait mode
NativeWidth = 720
NativeHeight = 1280
DpiX = 160
DpiY = 160
DeviceCapabilities = DeviceCapabilities.All
ClientVersion = 151117100 # v2.4.1511.17100-Beta
OSMajor = 22 # Android 5.1.1 - API Version 22
OSMinor = 0
DisplayName = "com.microsoft.xboxone.smartglass.beta"
class WindowsClientInfo(object):
"""
Client Info for Windows device, used for LocalJoin messages
"""
DeviceType = ClientType.WindowsStore
NativeWidth = 1080
NativeHeight = 1920
DpiX = 96
DpiY = 96
DeviceCapabilities = DeviceCapabilities.All
ClientVersion = 39
OSMajor = 6
OSMinor = 2
DisplayName = "SmartGlass-PC"
class MessageTarget(object):
"""
UUIDs for all ServiceChannels
"""
SystemInputUUID = UUID("fa20b8ca-66fb-46e0-adb60b978a59d35f")
SystemInputTVRemoteUUID = UUID("d451e3b3-60bb-4c71-b3dbf994b1aca3a7")
SystemMediaUUID = UUID("48a9ca24-eb6d-4e12-8c43d57469edd3cd")
SystemTextUUID = UUID("7af3e6a2-488b-40cb-a93179c04b7da3a0")
SystemBroadcastUUID = UUID("b6a117d8-f5e2-45d7-862e8fd8e3156476")
TitleUUID = UUID('00000000-0000-0000-0000-000000000000')
class XboxOneGuid(object):
"""
System level GUIDs
"""
BROWSER = "9c7e0f20-78fb-4ea7-a8bd-cf9d78059a08"
MUSIC = "6D96DEDC-F3C9-43F8-89E3-0C95BF76AD2A"
VIDEO = "a489d977-8a87-4983-8df6-facea1ad6d93"
class TitleId(object):
"""
System level Title Ids
"""
AVATAR_EDITOR_TITLE_ID = 1481443281
BROWSER_TITLE_ID = 1481115776
DASH_TITLE_ID = 4294838225
BLUERAY_TITLE_ID = 1783797709
CONSOLE_UPDATE_APP_TITLE_ID = -1
HOME_TITLE_ID = 714681658
IE_TITLE_ID = 1032557327
LIVETV_TITLE_ID = 371594669
MUSIC_TITLE_ID = 419416564
ONEGUIDE_TITLE_ID = 2055214557
OOBE_APP_TITLE_ID = 951105730
SNAP_AN_APP_TITLE_ID = 1783889234
STORE_APP_TITLE_ID = 1407783715
VIDEO_TITLE_ID = 1030770725
ZUNE_TITLE_ID = 1481115739
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,124 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/sg/manager.py | """
Managers for handling different ServiceChannels.
If a manager for a specific :class:`ServiceChannel` is attached,
incoming messages get forwarded there, otherways they are discarded.
Managers can be attached by calling `add_manager()` on the :class:`Console`
object (see example)
Methods of manager are available through console-context.
Example:
How to add a manager::
discovered = await Console.discover(timeout=1)
if len(discovered):
console = discovered[0]
# Add manager, optionally passing initialization parameter
some_arg_for_manager_init = 'example'
console.add_manager(
MediaManager,
additional_arg=some_arg_for_manager_init
)
await console.connect()
if console.connection_state != ConnectionState.Connected:
print("Connection failed")
sys.exit(1)
console.wait(1)
# Call manager method
console.media_command(0x54321, MediaControlCommand.PlayPauseToggle, 0)
else:
print("No consoles discovered")
sys.exit(1)
"""
import asyncio
import time
import logging
from typing import Optional
from construct import Container
from xbox.sg import factory
from xbox.sg.enum import MessageType, ServiceChannel, AckStatus, TextResult, \
SoundLevel, MediaControlCommand, MediaPlaybackStatus, TextInputScope, \
MediaType, GamePadButton
from xbox.sg.utils.events import Event
from xbox.sg.utils.struct import XStruct
log = logging.getLogger(__name__)
class Manager(object):
__namespace__ = ''
def __init__(self, console, channel: ServiceChannel):
"""
Don't use directly!
INTERNALLY called by the parent :class:`Console`!
Args:
console: Console object, internally passed by `Console.add_manager
channel: Service channel
"""
self.console = console
self.console.on_message += self._pre_on_message
self.console.on_json += self._pre_on_json
self._channel = channel
def _pre_on_message(self, msg, channel):
if channel == self._channel:
self._on_message(msg, channel)
def _pre_on_json(self, data, channel):
if channel == self._channel:
self._on_json(data, channel)
def _on_message(self, msg, channel):
"""
Managers must implement this
"""
pass
def _on_json(self, data, channel):
"""
Managers must implement this
"""
pass
async def _send_message(self, msg: XStruct):
"""
Internal method to send messages to initialized Service Channel
Args:
msg (:class:`XStructObj`): Message
"""
return await self.console.send_message(msg, channel=self._channel)
async def _send_json(self, data: str) -> None:
"""
Internal method to send JSON messages to initialized Service Channel
Args:
data: JSON message
"""
return await self.console.json(data, channel=self._channel)
class InputManagerError(Exception):
"""
Exception thrown by InputManager
"""
pass
class InputManager(Manager):
__namespace__ = 'input'
def __init__(self, console):
"""
Input Manager (ServiceChannel.SystemInput)
Args:
console: Console object, internally passed by `Console.add_manager
"""
super(InputManager, self).__init__(console, ServiceChannel.SystemInput)
def _on_message(self, msg: XStruct, channel: ServiceChannel) -> None:
"""
Internal handler method to receive messages from SystemInput Channel
Args:
msg: Message
channel: Service channel
"""
raise InputManagerError("Unexpected message received on InputManager")
async def gamepad_input(
self,
buttons: GamePadButton,
l_trigger: int = 0,
r_trigger: int = 0,
l_thumb_x: int = 0,
l_thumb_y: int = 0,
r_thumb_x: int = 0,
r_thumb_y: int = 0
) -> None:
"""
Send gamepad input
Args:
buttons: Gamepad buttons bits
l_trigger: Left trigger value
r_trigger: Right trigger value
l_thumb_x: Left thumbstick X-axis value
l_thumb_y: Left thumbstick Y-axis value
r_thumb_x: Right thumbstick X-axis value
r_thumb_y: Right thumbstick Y-axis value
Returns: None
"""
ts = int(time.time())
msg = factory.gamepad(
ts, buttons, l_trigger, r_trigger, l_thumb_x, l_thumb_y,
r_thumb_x, r_thumb_y
)
return await self._send_message(msg)
class MediaManagerError(Exception):
"""
Exception thrown by MediaManager
"""
pass
class MediaManager(Manager):
__namespace__ = 'media'
def __init__(self, console):
"""
Media Manager (ServiceChannel.SystemMedia)
Args: Console object, internally passed by `Console.add_manager
"""
super(MediaManager, self).__init__(console, ServiceChannel.SystemMedia)
self._media_state = None
self.on_media_state = Event()
self.on_media_command_result = Event()
self.on_media_controller_removed = Event()
def _on_message(self, msg: XStruct, channel: ServiceChannel) -> None:
"""
Internal handler method to receive messages from SystemMedia Channel
Args:
msg: Message
channel: Service channel
"""
msg_type = msg.header.flags.msg_type
payload = msg.protected_payload
if msg_type == MessageType.MediaState:
log.debug('Received MediaState message')
self._media_state = payload
self.on_media_state(self.media_state)
elif msg_type == MessageType.MediaCommandResult:
log.debug('Received MediaCommandResult message')
self.on_media_command_result(payload)
elif msg_type == MessageType.MediaControllerRemoved:
title_id = payload.title_id
log.debug('Received MediaControllerRemoved message, title id: 0x%x', title_id)
if self.title_id == title_id:
log.debug('Clearing MediaState')
self._media_state = None
self.on_media_controller_removed(payload)
else:
raise MediaManagerError(
"Unexpected message received on MediaManager"
)
@property
def media_state(self) -> Optional[Container]:
"""
Media state payload
Returns: Media state payload
"""
return self._media_state
@property
def active_media(self) -> Optional[bool]:
"""
Check whether console has active media
Returns: `True` if media is active, `False` if not
"""
return self.media_state is not None
@property
def title_id(self) -> Optional[int]:
"""
Title Id of active media
Returns: Title Id
"""
if self.media_state:
return self.media_state.title_id
@property
def aum_id(self) -> Optional[str]:
"""
Application user model Id of active media
Returns: Aum Id
"""
if self.media_state:
return self.media_state.aum_id
@property
def asset_id(self) -> Optional[str]:
"""
Asset Id of active media
Returns: Asset Id
"""
if self.media_state:
return self.media_state.asset_id
@property
def media_type(self) -> Optional[MediaType]:
"""
Media type of active media
Returns: Media type
"""
if self.media_state:
return self.media_state.media_type
@property
def sound_level(self) -> Optional[SoundLevel]:
"""
Sound level of active media
Returns: Sound level
"""
if self.media_state:
return self.media_state.sound_level
@property
def enabled_commands(self) -> Optional[MediaControlCommand]:
"""
Enabled MediaCommands bitmask
Returns: Bitmask of enabled commands
"""
if self.media_state:
return self.media_state.enabled_commands
@property
def playback_status(self) -> Optional[MediaPlaybackStatus]:
"""
Playback status of active media
Returns: Playback status
"""
if self.media_state:
return self.media_state.playback_status
@property
def rate(self) -> Optional[float]:
"""
Playback rate of active media
Returns: Playback rate
"""
if self.media_state:
return self.media_state.rate
@property
def position(self) -> Optional[int]:
"""
Playback position of active media
Returns: Playback position in microseconds
"""
if self.media_state:
return self.media_state.position
@property
def media_start(self) -> Optional[int]:
"""
Media start position of active media
Returns: Media start position in microseconds
"""
if self.media_state:
return self.media_state.media_start
@property
def media_end(self) -> Optional[int]:
"""
Media end position of active media
Returns: Media end position in microseconds
"""
if self.media_state:
return self.media_state.media_end
@property
def min_seek(self) -> Optional[int]:
"""
Minimum seek position of active media
Returns: Minimum position in microseconds
"""
if self.media_state:
return self.media_state.min_seek
@property
def max_seek(self) -> Optional[int]:
"""
Maximum seek position of active media
Returns: Maximum position in microseconds
"""
if self.media_state:
return self.media_state.max_seek
@property
def metadata(self) -> Container:
"""
Media metadata of active media
Returns: Media metadata
"""
if self.media_state:
return self.media_state.metadata
async def media_command(
self,
title_id: int,
command: MediaControlCommand,
request_id: int = 0,
seek_position: Optional[int] = None
) -> None:
"""
Send media command
Args:
title_id: Title Id
command: Media Command
request_id: Incrementing Request Id
seek_position: Seek position
Returns: None
"""
msg = factory.media_command(
request_id, title_id, command, seek_position
)
return await self._send_message(msg)
class TextManagerError(Exception):
"""
Exception thrown by TextManager
"""
pass
class TextManager(Manager):
__namespace__ = 'text'
def __init__(self, console):
"""
Text Manager (ServiceChannel.SystemText)
Args:
console: Console object, internally passed by `Console.add_manager
"""
super(TextManager, self).__init__(console, ServiceChannel.SystemText)
self.session_config = None
self.current_session_input = None
self.last_session_ack = None
self._current_text_version = 0
self.on_systemtext_configuration = Event()
self.on_systemtext_input = Event()
self.on_systemtext_done = Event()
def _on_message(self, msg: XStruct, channel: ServiceChannel):
"""
Internal handler method to receive messages from SystemText Channel
Args:
msg (:class:`XStructObj`): Message
channel (:class:`ServiceChannel`): Service channel
"""
msg_type = msg.header.flags.msg_type
payload = msg.protected_payload
session_id = payload.text_session_id
if msg_type == MessageType.SystemTextConfiguration:
self.reset_session()
self.session_config = payload
self.on_systemtext_configuration(payload)
elif msg_type == MessageType.SystemTextInput:
# Assign console input msg
self.current_session_input = payload
self.current_text_version = payload.submitted_version
asyncio.create_task(
self.send_systemtext_ack(
self.text_session_id,
self.current_text_version
)
)
self.on_systemtext_input(payload)
elif msg_type == MessageType.SystemTextAck:
self.current_text_version = payload.text_version_ack
elif msg_type == MessageType.SystemTextDone:
if session_id == self.text_session_id:
self.reset_session()
elif session_id == 0:
# SystemTextDone for session 0 is sent by console
# No clue what it means, if anything
pass
else:
pass
# log.debug('Received DONE msg for inactive session %i' % session_id)
self.on_systemtext_done(payload)
elif msg_type in [MessageType.TitleTextConfiguration,
MessageType.TitleTextInput,
MessageType.TitleTextSelection]:
raise TextManagerError('Received TitleTextConfiguration, unhandled')
else:
raise TextManagerError(
"Unexpected message received on TextManager"
)
@property
def got_active_session(self):
"""
Check whether a text session is active
Returns:
bool: Returns `True` if any text session is active, `False` otherwise
"""
return self.session_config is not None
@property
def current_text_version(self):
"""
Current Text version
Returns:
int: Current Text Version
"""
return self._current_text_version
@current_text_version.setter
def current_text_version(self, value):
if value > self.current_text_version:
self._current_text_version = value
@property
def text_session_id(self):
"""
Current Text session id
Returns:
int: Text session id if existing, `None` otherwise
"""
if self.session_config:
return self.session_config.text_session_id
@property
def text_options(self):
"""
Current Text options
Returns:
:class:`TextOption`: Text options if existing, `None` otherwise
"""
if self.session_config:
return self.session_config.text_options
@property
def text_input_scope(self) -> Optional[TextInputScope]:
"""
Current Text input scope
Returns: Text input scope if existing, `None` otherwise
"""
if self.session_config:
return self.session_config.input_scope
@property
def max_text_length(self) -> Optional[int]:
"""
Maximum Text length
Returns: Max text length if existing, `None` otherwise
"""
if self.session_config:
return self.session_config.max_text_length
@property
def text_locale(self) -> Optional[str]:
"""
Test
Returns: Text locale if existing, `None` otherwise
"""
if self.session_config:
return self.session_config.locale
@property
def text_prompt(self) -> Optional[str]:
"""
Test
Returns: Text prompt if existing, `None` otherwise
"""
if self.session_config:
return self.session_config.prompt
def reset_session(self) -> None:
"""
Delete cached text-session config, -input and -ack messages
Returns: None
"""
self.session_config = None
self.current_session_input = None
self.last_session_ack = None
self.current_text_version = 0
async def finish_text_input(self) -> None:
"""
Finishes current text session.
Returns:
None
"""
await self.send_systemtext_done(
session_id=self.text_session_id,
version=self.current_session_input.submitted_version,
flags=0,
result=TextResult.Accept
)
async def send_systemtext_input(self, text: str) -> Optional[AckStatus]:
"""
Sends text input
Args:
text: Text string to send
Raises:
TextManagerError: If message was not acknowledged via
AckMsg or SystemTextAck
Returns: Ack status
"""
new_version = self.current_text_version + 1
msg = factory.systemtext_input(
session_id=self.text_session_id,
base_version=self.current_text_version,
submitted_version=new_version,
total_text_len=len(text),
selection_start=-1,
selection_length=-1,
flags=0,
text_chunk_byte_start=0,
text_chunk=text,
delta=None
)
ack_status = await self._send_message(msg)
if ack_status != AckStatus.Processed:
raise TextManagerError('InputMsg was not acknowledged: %s' % msg)
# Assign client system input msg
self.current_session_input = msg.protected_payload
return ack_status
async def send_systemtext_ack(
self,
session_id: int,
version: int
) -> Optional[AckStatus]:
"""
Acknowledges a SystemText message sent from the console
Args:
session_id: Current text session id
version: Text version to ack
Returns: Ack status
"""
msg = factory.systemtext_ack(session_id, version)
return await self._send_message(msg)
async def send_systemtext_done(
self,
session_id: int,
version: int,
flags: int,
result: TextResult
) -> Optional[AckStatus]:
"""
Informs the console that a text session is done.
Result field tells wether text input should be
accepted or cancelled.
Args:
session_id: Current text session id
version: Last acknowledged text version
flags: Flags
result: Text result to send
Returns: Ack status
"""
msg = factory.systemtext_done(session_id, version, flags, result)
ack_status = await self._send_message(msg)
if ack_status != AckStatus.Processed:
raise TextManagerError('DoneMsg was not acknowledged: %s' % msg)
return ack_status
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,125 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/stump/enum.py | """
Stump enumerations
"""
from uuid import UUID
from enum import Enum
class Message(str, Enum):
"""
Message types
"""
ERROR = "Error"
ENSURE_STREAMING_STARTED = "EnsureStreamingStarted"
CONFIGURATION = "GetConfiguration"
HEADEND_INFO = "GetHeadendInfo"
LIVETV_INFO = "GetLiveTVInfo"
PROGRAMM_INFO = "GetProgrammInfo"
RECENT_CHANNELS = "GetRecentChannels"
TUNER_LINEUPS = "GetTunerLineups"
APPCHANNEL_DATA = "GetAppChannelData"
APPCHANNEL_LINEUPS = "GetAppChannelLineups"
APPCHANNEL_PROGRAM_DATA = "GetAppChannelProgramData"
SEND_KEY = "SendKey"
SET_CHANNEL = "SetChannel"
class Notification(str, Enum):
"""
Notification types
"""
STREAMING_ERROR = "StreamingError"
CHANNEL_CHANGED = "ChannelChanged"
CHANNELTYPE_CHANGED = "ChannelTypeChanged"
CONFIGURATION_CHANGED = "ConfigurationChanged"
DEVICE_UI_CHANGED = "DeviceUIChanged"
HEADEND_CHANGED = "HeadendChanged"
VIDEOFORMAT_CHANGED = "VideoFormatChanged"
PROGRAM_CHANGED = "ProgrammChanged"
TUNERSTATE_CHANGED = "TunerStateChanged"
class Source(str, Enum):
"""
Streamingsources
"""
HDMI = "hdmi"
TUNER = "tuner"
class DeviceType(str, Enum):
"""
Devicetypes
"""
TV = "tv"
TUNER = "tuner"
SET_TOP_BOX = "stb"
AV_RECEIVER = "avr"
class SourceHttpQuery(str, Enum):
"""
Source strings used in HTTP query
"""
HDMI = "hdmi-in"
TUNER = "zurich"
class Input(object):
HDMI = UUID("BA5EBA11-DEA1-4BAD-BA11-FEDDEADFAB1E")
class Quality(str, Enum):
"""
Quality values
"""
LOW = "low"
MEDIUM = "medium"
HIGH = "high"
BEST = "best"
class FilterType(str, Enum):
"""
Channel-filter types
"""
ALL = "ALL" # No filter / Show all
HDSD = "HDSD" # Dont show double SD-channels
HD = "HD" # Only show HD Channels
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,126 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/scripts/__init__.py | import os
import logging
from enum import IntEnum
from appdirs import user_data_dir
DATA_DIR = user_data_dir('xbox', 'OpenXbox')
TOKENS_FILE = os.path.join(DATA_DIR, 'tokens.json')
CONSOLES_FILE = os.path.join(DATA_DIR, 'consoles.json')
if not os.path.exists(DATA_DIR):
os.makedirs(DATA_DIR)
LOG_FMT = '[%(asctime)s] %(levelname)s: %(message)s'
LOG_LEVEL_DEBUG_INCL_PACKETS = logging.DEBUG - 1
logging.addLevelName(LOG_LEVEL_DEBUG_INCL_PACKETS, 'DEBUG_INCL_PACKETS')
class ExitCodes(IntEnum):
"""
Common CLI exit codes
"""
OK = 0
ArgParsingError = 1
AuthenticationError = 2
DiscoveryError = 3
ConsoleChoice = 4
class VerboseFormatter(logging.Formatter):
def __init__(self, *args, **kwargs):
super(VerboseFormatter, self).__init__(*args, **kwargs)
self._verbosefmt = self._fmt + '\n%(_msg)s'
def formatMessage(self, record):
if '_msg' in record.__dict__:
return self._verbosefmt % record.__dict__
return self._style.format(record)
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,127 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/auxiliary/crypto.py | """
Cryptography portion used for Title Channel aka Auxiliary Stream
"""
import hmac
import hashlib
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
class AuxiliaryStreamCrypto(object):
_backend = default_backend()
def __init__(self, crypto_key, hash_key, server_iv, client_iv):
"""
Initialize Auxiliary Stream Crypto-context.
"""
self._encrypt_key = crypto_key
self._hash_key = hash_key
self._server_iv = server_iv
self._client_iv = client_iv
self._server_cipher = Cipher(
algorithms.AES(self._encrypt_key),
modes.CBC(self._server_iv),
backend=AuxiliaryStreamCrypto._backend
)
self._server_encryptor = self._server_cipher.encryptor()
self._server_decryptor = self._server_cipher.decryptor()
self._client_cipher = Cipher(
algorithms.AES(self._encrypt_key),
modes.CBC(self._client_iv),
backend=AuxiliaryStreamCrypto._backend
)
self._client_encryptor = self._client_cipher.encryptor()
self._client_decryptor = self._client_cipher.decryptor()
@classmethod
def from_connection_info(cls, connection_info):
"""
Initialize Crypto context via AuxiliaryStream-message
connection info.
"""
return cls(
connection_info.crypto_key,
connection_info.sign_hash,
connection_info.server_iv,
connection_info.client_iv
)
def encrypt(self, plaintext):
"""
Encrypts plaintext with AES-128-CBC
No padding is added here, data has to be aligned to
block size (16 bytes).
Args:
plaintext (bytes): The plaintext to encrypt.
Returns:
bytes: Encrypted Data
"""
return AuxiliaryStreamCrypto._crypt(self._client_encryptor, plaintext)
def encrypt_server(self, plaintext):
return AuxiliaryStreamCrypto._crypt(self._server_encryptor, plaintext)
def decrypt(self, ciphertext):
"""
Decrypts ciphertext
No padding is removed here.
Args:
ciphertext (bytes): Ciphertext to be decrypted
Returns:
bytes: Decrypted data
"""
return AuxiliaryStreamCrypto._crypt(self._server_decryptor, ciphertext)
def decrypt_client(self, ciphertext):
return AuxiliaryStreamCrypto._crypt(self._client_decryptor, ciphertext)
def hash(self, data):
"""
Securely hashes data with HMAC SHA-256
Args:
data (bytes): The data to securely hash.
Returns:
bytes: Hashed data
"""
return AuxiliaryStreamCrypto._secure_hash(self._hash_key, data)
def verify(self, data, secure_hash):
"""
Verifies that the given data generates the given secure_hash
Args:
data (bytes): The data to validate.
secure_hash (bytes): The secure hash to validate against.
Returns:
bool: True on success, False otherwise
"""
return secure_hash == self.hash(data)
@staticmethod
def _secure_hash(key, data):
return hmac.new(key, data, hashlib.sha256).digest()
@staticmethod
def _crypt(cryptor, data):
return cryptor.update(data)
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,128 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/rest/schemas/__init__.py | from .root import IndexResponse
from .general import GeneralResponse
from .auth import AuthenticationStatus, AuthSessionConfig
from .device import (
ConsoleStatusResponse,
DeviceStatusResponse,
MediaStateResponse,
InfraredResponse,
InfraredDevice,
InfraredButton,
MediaCommandsResponse,
TextSessionActiveResponse,
InputResponse
) | {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,129 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/sg/protocol.py | """
Smartglass protocol core
**NOTE**: Should not be used directly, use :class:`.Console` !
"""
import uuid
import json
import base64
import logging
import asyncio
import socket
from typing import List, Optional, Tuple, Dict, Union
from xbox.sg import factory, packer, crypto, console
from xbox.sg.packet.message import message_structs
from xbox.sg.enum import PacketType, ConnectionResult, DisconnectReason,\
ServiceChannel, MessageType, AckStatus, SGResultCode, ActiveTitleLocation,\
PairedIdentityState, PublicKeyType
from xbox.sg.constants import WindowsClientInfo, AndroidClientInfo,\
MessageTarget
from xbox.sg.manager import MediaManager, InputManager, TextManager
from xbox.sg.utils.events import Event
from xbox.sg.utils.struct import XStruct
LOGGER = logging.getLogger(__name__)
PORT = 5050
BROADCAST = '255.255.255.255'
MULTICAST = '239.255.255.250'
CHANNEL_MAP = {
ServiceChannel.SystemInput: MessageTarget.SystemInputUUID,
ServiceChannel.SystemInputTVRemote: MessageTarget.SystemInputTVRemoteUUID,
ServiceChannel.SystemMedia: MessageTarget.SystemMediaUUID,
ServiceChannel.SystemText: MessageTarget.SystemTextUUID,
ServiceChannel.SystemBroadcast: MessageTarget.SystemBroadcastUUID
}
class ProtocolError(Exception):
"""
Exception thrown by CoreProtocol
"""
pass
class SmartglassProtocol(asyncio.DatagramProtocol):
HEARTBEAT_INTERVAL = 3.0
def __init__(
self,
address: Optional[str] = None,
crypto_instance: Optional[crypto.Crypto] = None
):
"""
Instantiate Smartglass Protocol handler.
Args:
address: Address
crypto_instance: Crypto instance
"""
self.address = address
self._transport: Optional[asyncio.DatagramTransport] = None
self.crypto = crypto_instance
self._discovered = {}
self.target_participant_id = None
self.source_participant_id = None
self._pending: Dict[str, asyncio.Future] = {}
self._chl_mgr = ChannelManager()
self._seq_mgr = SequenceManager()
self._frg_mgr = FragmentManager()
self.on_timeout = Event()
self.on_discover = Event()
self.on_message = Event()
self.on_json = Event()
self.started = False
async def stop(self) -> None:
"""
Dummy
"""
pass
def connection_made(self, transport: asyncio.DatagramTransport) -> None:
self.started = True
self._transport = transport
def error_received(self, exc: OSError):
print('Error received:', exc.args)
def connection_lost(self, exc: Optional[Exception]):
print("Connection closed")
self._transport.close()
self.started = False
async def send_message(
self,
msg,
channel=ServiceChannel.Core,
addr: Optional[str] = None,
blocking: bool = True,
timeout: int = 5,
retries: int = 3
) -> Optional[XStruct]:
"""
Send message to console.
Packing and encryption happens here.
Args:
msg: Unassembled message to send
channel: Channel to send the message on,
Enum member of `ServiceChannel`
addr: IP address of target console
blocking: If set and `msg` is `Message`-packet, wait for ack
timeout: Seconds to wait for ack, only useful if `blocking`
is `True`
retries: Max retry count.
Returns: None
Raises:
ProtocolError: On failure
"""
if msg.header.pkt_type == PacketType.Message:
msg.header(
sequence_number=self._seq_mgr.next_sequence_num(),
target_participant_id=self.target_participant_id,
source_participant_id=self.source_participant_id,
channel_id=self._chl_mgr.get_channel_id(channel)
)
if self.crypto:
data = packer.pack(msg, self.crypto)
else:
data = packer.pack(msg)
if self.address:
addr = self.address
if not addr:
raise ProtocolError("No address specified in send_message")
elif not data:
raise ProtocolError("No data")
if msg.header.pkt_type == PacketType.Message \
and msg.header.flags.need_ack and blocking:
LOGGER.debug(
"Sending %s message on ServiceChannel %s to %s",
msg.header.flags.msg_type.name, channel.name, addr,
extra={'_msg': msg}
)
seqn = msg.header.sequence_number
tries = 0
result = None
while tries < retries and not result:
if tries > 0:
LOGGER.warning(
f"Message {msg.header.flags.msg_type.name} on "
f"ServiceChannel {channel.name} to {addr} not ack'd "
f"in time, attempt #{tries + 1}",
extra={'_msg': msg}
)
await self._send(data, (addr, PORT))
result = await self._await_ack('ack_%i' % seqn, timeout)
tries += 1
if result:
return result
raise ProtocolError("Exceeded retries")
elif msg.header.pkt_type == PacketType.ConnectRequest:
LOGGER.debug(
f"Sending ConnectRequest to {addr}", extra={'_msg': msg}
)
await self._send(data, (addr, PORT))
async def _send(self, data: bytes, target: Tuple[str, int]):
"""
Send data on the connected transport.
If addr is not provided, the target address that was used at the time
of instantiating the protocol is used.
(e.g. asyncio.create_datagram_endpoint in Console-class).
Args:
data: Data to send
target: Tuple of (ip_address, port)
"""
if self._transport:
self._transport.sendto(data, target)
else:
LOGGER.error('Transport not ready...')
def datagram_received(self, data: bytes, addr: str) -> None:
"""
Handle incoming smartglass packets
Args:
data: Raw packet
addr: IP address of sender
Returns: None
"""
try:
host, _ = addr
if self.crypto:
msg = packer.unpack(data, self.crypto)
else:
msg = packer.unpack(data)
if msg.header.pkt_type == PacketType.DiscoveryResponse:
LOGGER.debug(
f"Received DiscoverResponse from {host}",
extra={'_msg': msg}
)
self._discovered[host] = msg
self.on_discover(host, msg)
elif msg.header.pkt_type == PacketType.ConnectResponse:
LOGGER.debug(
f"Received ConnectResponse from {host}",
extra={'_msg': msg}
)
if 'connect' in self._pending:
self._set_result('connect', msg)
elif msg.header.pkt_type == PacketType.Message:
channel = self._chl_mgr.get_channel(msg.header.channel_id)
message_info = msg.header.flags.msg_type.name
if msg.header.flags.is_fragment:
message_info = 'MessageFragment ({0})'.format(message_info)
LOGGER.debug(
"Received %s message on ServiceChannel %s from %s",
message_info, channel.name, host, extra={'_msg': msg}
)
seq_num = msg.header.sequence_number
self._seq_mgr.add_received(seq_num)
if msg.header.flags.need_ack:
asyncio.create_task(
self.ack(
[msg.header.sequence_number],
[],
ServiceChannel.Core
)
)
self._seq_mgr.low_watermark = seq_num
if msg.header.flags.is_fragment:
sequence_begin = msg.protected_payload.sequence_begin
sequence_end = msg.protected_payload.sequence_end
fragment_payload = self._frg_mgr.reassemble_message(msg)
if not fragment_payload:
return
msg(protected_payload=fragment_payload)
LOGGER.debug("Assembled {0} (Seq {1}:{2})".format(
message_info, sequence_begin, sequence_end
), extra={'_msg': msg})
self._on_message(msg, channel)
else:
self._on_unk(msg)
except Exception:
LOGGER.exception("Exception in CoreProtocol datagram handler")
@staticmethod
def _on_unk(msg) -> None:
LOGGER.error(f'Unhandled message: {msg}')
async def _await_ack(
self,
identifier: str,
timeout: int = 5
) -> Optional[XStruct]:
"""
Wait for acknowledgement of message
Args:
identifier: Identifier of ack
timeout: Timeout in seconds
Returns:
:obj:`.Event`: Event
"""
fut = asyncio.Future()
self._pending[identifier] = fut
try:
await asyncio.wait_for(fut, timeout)
return fut.result()
except asyncio.TimeoutError:
return None
def _set_result(
self,
identifier: str,
result: Union[AckStatus, XStruct]
) -> None:
"""
Called when an acknowledgement comes in, unblocks `_await_ack`
Args:
identifier: Identifier of ack
result: Ack status
Returns: None
"""
self._pending[identifier].set_result(result)
del self._pending[identifier]
async def _heartbeat_task(self) -> None:
"""
Task checking for console activity, firing `on_timeout`-event on
timeout.
Heartbeats are empty "ack" messages that are to be ack'd by the console
Returns:
None
"""
while self.started:
try:
await self.ack([], [], ServiceChannel.Core, need_ack=True)
except ProtocolError:
self.on_timeout()
self.connection_lost(TimeoutError())
break
await asyncio.sleep(self.HEARTBEAT_INTERVAL)
def _on_message(self, msg: XStruct, channel: ServiceChannel) -> None:
"""
Handle msg of type `Message`.
Args:
msg: Message
channel: Channel the message was received on
Returns: None
"""
msg_type = msg.header.flags.msg_type
# First run our internal handlers
if msg_type == MessageType.Ack:
self._on_ack(msg)
elif msg_type == MessageType.StartChannelResponse:
self._chl_mgr.handle_channel_start_response(msg)
elif msg_type == MessageType.Json:
self._on_json(msg, channel)
# Then our hooked handlers
self.on_message(msg, channel)
def _on_ack(self, msg: XStruct) -> None:
"""
Process acknowledgement message.
Args:
msg: Message
Returns: None
"""
for num in msg.protected_payload.processed_list:
identifier = 'ack_%i' % num
self._seq_mgr.add_processed(num)
if identifier in self._pending:
self._set_result(identifier, AckStatus.Processed)
for num in msg.protected_payload.rejected_list:
identifier = 'ack_%i' % num
self._seq_mgr.add_rejected(num)
if identifier in self._pending:
self._set_result(identifier, AckStatus.Rejected)
def _on_json(self, msg: XStruct, channel: ServiceChannel) -> None:
"""
Process json message.
Args:
msg: Message
channel: Channel the message was received on
Returns: None
"""
text = msg.protected_payload.text
if 'fragment_data' in text:
text = self._frg_mgr.reassemble_json(text)
if not text:
# Input message is a fragment, but cannot assemble full msg yet
return
self.on_json(text, channel)
async def discover(
self,
addr: str = None,
tries: int = 5,
blocking: bool = True,
timeout: int = 5
) -> Dict[str, XStruct]:
"""
Discover consoles on the network
Args:
addr (str): IP address
tries (int): Discover attempts
blocking (bool): Wait a given time for responses, otherwise
return immediately
timeout (int): Timeout in seconds (only if `blocking` is `True`)
Returns:
list: List of discovered consoles
"""
self._discovered = {}
msg = factory.discovery()
task = asyncio.create_task(self._discover(msg, addr, tries))
# Blocking for a discovery is different than connect or regular message
if blocking:
try:
await asyncio.wait_for(task, timeout)
except asyncio.TimeoutError:
pass
return self.discovered
async def _discover(
self,
msg,
addr: str,
tries: int
) -> None:
for _ in range(tries):
await self.send_message(msg, addr=BROADCAST)
await self.send_message(msg, addr=MULTICAST)
if addr:
await self.send_message(msg, addr=addr)
await asyncio.sleep(0.5)
@property
def discovered(self) -> Dict[str, XStruct]:
"""
Return discovered consoles
Returns:
Discovered consoles
"""
return self._discovered
async def connect(
self,
userhash: str,
xsts_token: str,
client_uuid: uuid.UUID = uuid.uuid4(),
request_num: int = 0,
retries: int = 3
) -> PairedIdentityState:
"""
Connect to console
Args:
userhash: Userhash from Xbox Live Authentication
xsts_token: XSTS Token from Xbox Live Authentication
client_uuid: Client UUID (default: Generate random uuid)
request_num: Request number
retries: Max. connect attempts
Returns: Pairing State
Raises:
ProtocolError: If connection fails
"""
if not self.crypto:
raise ProtocolError("No crypto")
if isinstance(userhash, type(None)):
userhash = ''
if isinstance(xsts_token, type(None)):
xsts_token = ''
iv = self.crypto.generate_iv()
pubkey_type = self.crypto.pubkey_type
pubkey = self.crypto.pubkey_bytes
msg = factory.connect(
client_uuid, pubkey_type, pubkey, iv, userhash, xsts_token,
request_num, request_num, request_num + 1
)
payload_len = packer.payload_length(msg)
if payload_len < 1024:
messages = [msg]
else:
messages = _fragment_connect_request(
self.crypto, client_uuid, pubkey_type, pubkey,
userhash, xsts_token, request_num
)
tries = 0
result = None
while tries < retries and not result:
for m in messages:
await self.send_message(m)
result = await self._await_ack('connect')
if not result:
raise ProtocolError("Exceeded connect retries")
connect_result = result.protected_payload.connect_result
if connect_result != ConnectionResult.Success:
raise ProtocolError(
"Connecting failed! Result: %s" % connect_result
)
self.target_participant_id = 0
self.source_participant_id = result.protected_payload.participant_id
await self.local_join()
for channel, target_uuid in CHANNEL_MAP.items():
await self.start_channel(channel, target_uuid)
asyncio.create_task(self._heartbeat_task())
return result.protected_payload.pairing_state
async def local_join(
self,
client_info: Union[WindowsClientInfo, AndroidClientInfo] = WindowsClientInfo,
**kwargs
) -> None:
"""
Pair client with console.
Args:
client_info: Either `WindowsClientInfo` or `AndroidClientInfo`
**kwargs:
Returns: None
"""
msg = factory.local_join(client_info)
await self.send_message(msg, **kwargs)
async def start_channel(
self,
channel: ServiceChannel,
messagetarget_uuid: uuid.UUID,
title_id: int = 0,
activity_id: int = 0,
**kwargs
) -> None:
"""
Request opening of specific ServiceChannel
Args:
channel: Channel to start
messagetarget_uuid: Message Target UUID
title_id: Title ID, Only used for ServiceChannel.Title
activity_id: Activity ID, unknown use-case
**kwargs: KwArgs
Returns: None
"""
request_id = self._chl_mgr.get_next_request_id(channel)
msg = factory.start_channel(
request_id, title_id, messagetarget_uuid, activity_id
)
await self.send_message(msg, **kwargs)
async def ack(
self,
processed: List[int],
rejected: List[int],
channel: ServiceChannel,
need_ack: bool = False
) -> None:
"""
Acknowledge received messages that have `need_ack` flag set.
Args:
processed: Processed sequence numbers
rejected: Rejected sequence numbers
channel: Channel to send the ack on
need_ack: Whether we want this ack to be acknowledged by the target
participant.
Will be blocking if set.
Required for heartbeat messages.
Returns: None
"""
low_watermark = self._seq_mgr.low_watermark
msg = factory.acknowledge(
low_watermark, processed, rejected, need_ack=need_ack
)
await self.send_message(msg, channel=channel, blocking=need_ack)
async def json(
self,
data: str,
channel: ServiceChannel
) -> None:
"""
Send json message
Args:
data: JSON dict
channel: Channel to send the message to
Returns: None
"""
msg = factory.json(data)
await self.send_message(msg, channel=channel)
async def power_on(
self,
liveid: str,
addr: Optional[str] = None,
tries: int = 2
) -> None:
"""
Power on console.
Args:
liveid: Live ID of console
addr: IP address of console
tries: PowerOn attempts
Returns: None
"""
msg = factory.power_on(liveid)
for i in range(tries):
await self.send_message(msg, addr=BROADCAST)
await self.send_message(msg, addr=MULTICAST)
if addr:
await self.send_message(msg, addr=addr)
await asyncio.sleep(0.1)
async def power_off(
self,
liveid: str
) -> None:
"""
Power off console
Args:
liveid: Live ID of console
Returns: None
"""
msg = factory.power_off(liveid)
await self.send_message(msg)
async def disconnect(
self,
reason: DisconnectReason = DisconnectReason.Unspecified,
error: int = 0
) -> None:
"""
Disconnect console session
Args:
reason: Disconnect reason
error: Error Code
Returns: None
"""
msg = factory.disconnect(reason, error)
await self.send_message(msg)
async def game_dvr_record(
self,
start_delta: int,
end_delta: int
) -> AckStatus:
"""
Start Game DVR recording
Args:
start_delta: Start time
end_delta: End time
Returns: Acknowledgement status
"""
msg = factory.game_dvr_record(start_delta, end_delta)
return await self.send_message(msg)
async def launch_title(
self,
uri: str,
location: ActiveTitleLocation = ActiveTitleLocation.Full
) -> AckStatus:
"""
Launch title via URI
Args:
uri: Uri string
location: Location
Returns: Ack status
"""
msg = factory.title_launch(location, uri)
return await self.send_message(msg)
class SequenceManager:
def __init__(self):
"""
Process received messages by sequence numbers.
Also add processed / rejected messages to a list.
Tracks the `Low Watermark` that's sent with
`Acknowledgement`-Messages too.
"""
self.processed = []
self.rejected = []
self.received = []
self._low_watermark = 0
self._sequence_num = 0
def add_received(self, sequence_num: int) -> None:
"""
Add received sequence number
Args:
sequence_num: Sequence number
Returns: None
"""
if sequence_num not in self.received:
self.received.append(sequence_num)
def add_processed(self, sequence_num: int) -> None:
"""
Add sequence number of message that was sent to console
and succeeded in processing.
Args:
sequence_num: Sequence number
Returns: None
"""
if sequence_num not in self.processed:
self.processed.append(sequence_num)
def add_rejected(self, sequence_num: int) -> None:
"""
Add sequence number of message that was sent to console
and was rejected by it.
Args:
sequence_num: Sequence number
Returns: None
"""
if sequence_num not in self.rejected:
self.rejected.append(sequence_num)
def next_sequence_num(self) -> int:
"""
Get next sequence number to use for outbound `Message`.
Returns: None
"""
self._sequence_num += 1
return self._sequence_num
@property
def low_watermark(self) -> int:
"""
Get current `Low Watermark`
Returns: Low Watermark
"""
return self._low_watermark
@low_watermark.setter
def low_watermark(self, value: int) -> None:
"""
Set `Low Watermark`
Args:
value: Last received sequence number from console
Returns: None
"""
if value > self._low_watermark:
self._low_watermark = value
class ChannelError(Exception):
"""
Exception thrown by :class:`ChannelManager`.
"""
pass
class ChannelManager:
CHANNEL_CORE = 0
CHANNEL_ACK = 0x1000000000000000
def __init__(self):
"""
Keep track of established ServiceChannels
"""
self._channel_mapping = {}
self._requests = {}
self._request_id = 0
def handle_channel_start_response(self, msg: XStruct) -> ServiceChannel:
"""
Handle message of type `StartChannelResponse`
Args:
msg: Start Channel Response message
Raises:
:class:`ChannelError`: If channel acquire failed
Returns: Acquired ServiceChannel
"""
# Find ServiceChannel by RequestId
request_id = msg.protected_payload.channel_request_id
channel = self._requests.get(request_id)
if not channel:
raise ChannelError("Request Id %d not found. Was the channel request saved?" % request_id)
if msg.protected_payload.result != SGResultCode.SG_E_SUCCESS:
raise ChannelError("Acquiring ServiceChannel %s failed" % channel.name)
# Save Channel Id for appropriate ServiceChannel
channel_id = msg.protected_payload.target_channel_id
self._channel_mapping[channel] = channel_id
self._requests.pop(request_id)
LOGGER.debug("Acquired ServiceChannel %s -> Channel: 0x%x", channel.name, channel_id)
return channel
def get_next_request_id(self, channel: ServiceChannel) -> int:
"""
Get next Channel request id for ServiceChannel
Incremented on each call.
Args:
channel: Service channel
Returns: Channel request id
"""
# Clear old request for same ServiceChannel
self._requests = {key: val for key, val in self._requests.items()
if val != channel}
self._request_id += 1
self._requests[self._request_id] = channel
return self._request_id
def get_channel(self, channel_id: int) -> ServiceChannel:
"""
Get matching ServiceChannel enum for provided Channel ID of `Message`
Args:
channel_id: Channel of Message
Returns: Service channel
"""
# Core and Ack are fixed, don't need mapping
if channel_id == self.CHANNEL_CORE:
return ServiceChannel.Core
elif channel_id == self.CHANNEL_ACK:
return ServiceChannel.Ack
for key, value in self._channel_mapping.items():
if value == channel_id:
return key
raise ChannelError("ServiceChannel not found for channel_id: 0x%x"
% channel_id)
def get_channel_id(self, channel: ServiceChannel) -> int:
"""
Get Channel ID for use in `Message` for provided ServiceChannel
Args:
channel: Service channel
Returns: Channel ID for use in `Message`
"""
# Core and Ack are fixed, don't need mapping
if channel == ServiceChannel.Core:
return self.CHANNEL_CORE
elif channel == ServiceChannel.Ack:
return self.CHANNEL_ACK
if channel not in self._channel_mapping:
raise ChannelError(
f"Channel ID not found for ServiceChannel: {channel}"
)
return self._channel_mapping[channel]
def reset(self) -> None:
"""
Erase the channels table
Returns:
None
"""
self._requests = {}
self._channel_mapping = {}
self._request_id = 0
class FragmentError(Exception):
"""
Exception thrown by :class:`FragmentManager`.
"""
pass
class FragmentManager:
"""
Assembles fragmented messages
"""
def __init__(self):
self.msg_queue = {}
self.json_queue = {}
def reassemble_message(self, msg: XStruct) -> Optional[XStruct]:
"""
Reassemble message fragment
Args:
msg: Message fragment
Returns: Reassembled / decoded payload on success,
`None` if payload is not ready or assembly failed.
"""
msg_type = msg.header.flags.msg_type
payload = msg.protected_payload
current_sequence = msg.header.sequence_number
sequence_begin = payload.sequence_begin
sequence_end = payload.sequence_end
self.msg_queue[current_sequence] = payload.data
wanted_sequences = list(range(sequence_begin, sequence_end))
assembled = b''
for s in wanted_sequences:
data = self.msg_queue.get(s)
if not data:
return
assembled += data
[self.msg_queue.pop(s) for s in wanted_sequences]
# Parse raw data with original message struct
struct = message_structs.get(msg_type)
if not struct:
raise FragmentError(
f'Failed to find message struct for fragmented {msg_type}'
)
return struct.parse(assembled)
def reassemble_json(self, json_msg: dict) -> Optional[dict]:
"""
Reassemble fragmented json message
Args:
json_msg: Fragmented json message
Returns: Reassembled / Decoded json object on success,
`None` if datagram is not ready or assembly failed
"""
datagram_id, datagram_size =\
int(json_msg['datagram_id']), int(json_msg['datagram_size'])
fragment_offset = int(json_msg['fragment_offset'])
fragments = self.json_queue.get(datagram_id)
if not fragments:
# Just add initial fragment
self.json_queue[datagram_id] = [json_msg]
return None
# It's a follow-up fragment
# Check if we already received this datagram
for entry in fragments:
if fragment_offset == int(entry['fragment_offset']):
return
# Append current fragment to datagram list
fragments.append(json_msg)
# Check if fragment can be assembled
# If so, assemble and pop the fragments from queue
if sum(int(f['fragment_length']) for f in fragments) == datagram_size:
sorted_fragments = sorted(
fragments, key=lambda f: int(f['fragment_offset'])
)
output = ''.join(f['fragment_data'] for f in sorted_fragments)
self.json_queue.pop(datagram_id)
return self._decode(output)
return None
@staticmethod
def _encode(obj: dict) -> str:
"""
Dump a dict as json string, then encode with base64
Args:
obj: Dict to encode
Returns: base64 encoded string
"""
bytestr = json.dumps(obj, separators=(',', ':'), sort_keys=True)\
.encode('utf-8')
return base64.b64encode(bytestr).decode('utf-8')
@staticmethod
def _decode(data: str) -> dict:
"""
Decode a base64 encoded json object
Args:
data: Base64 string
Returns: Decoded json object
"""
return json.loads(base64.b64decode(data).decode('utf-8'))
def _fragment_connect_request(
crypto_instance: crypto.Crypto,
client_uuid: uuid.UUID,
pubkey_type: PublicKeyType,
pubkey: bytes,
userhash: str,
auth_token: str,
request_num: int = 0
) -> List:
"""
Internal method to fragment ConnectRequest.
Args:
crypto_instance: Instance of :class:`Crypto`
client_uuid: Client UUID
pubkey_type Public Key Type
pubkey: Public Key
userhash: Xbox Live Account userhash
auth_token: Xbox Live Account authentication token (XSTS)
request_num: Request Number
Returns:
list: List of ConnectRequest fragments
"""
messages = []
# Calculate packet length (without authentication data)
dummy_msg = factory.connect(
client_uuid, pubkey_type, pubkey, b'\x00' * 16, u'', u'', 0, 0, 0
)
dummy_payload_len = packer.payload_length(dummy_msg)
# Do fragmenting
total_auth_len = len(userhash + auth_token)
max_size = 1024 - dummy_payload_len
fragments = total_auth_len // max_size
overlap = total_auth_len % max_size
if overlap > 0:
fragments += 1
group_start = request_num
group_end = group_start + fragments
if fragments <= 1:
raise FragmentError('Authentication data too small to fragment')
auth_position = 0
for fragment_num in range(fragments):
available = max_size
current_hash = u''
if fragment_num == 0:
current_hash = userhash
available -= len(current_hash)
current_auth = auth_token[auth_position: auth_position + available]
auth_position += len(current_auth)
iv = crypto_instance.generate_iv()
messages.append(
factory.connect(
client_uuid, pubkey_type, pubkey, iv,
current_hash, current_auth, request_num + fragment_num,
group_start, group_end)
)
return messages
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,130 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /tests/test_pcap.py | from xbox.scripts import pcap
def test_pcap_filter(pcap_filepath):
packets = list(pcap.packet_filter(pcap_filepath))
assert len(packets) == 26
def test_run_parser(pcap_filepath, crypto):
pcap.parse(pcap_filepath, crypto)
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,131 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/sg/packet/simple.py | # flake8: noqa
"""
Construct containers for simple-message header and payloads
"""
from construct import *
from xbox.sg import enum
from xbox.sg.enum import PacketType
from xbox.sg.utils.struct import XStruct
from xbox.sg.utils.adapters import CryptoTunnel, XSwitch, XEnum, CertificateAdapter, UUIDAdapter, SGString, FieldIn
pkt_types = [
PacketType.PowerOnRequest,
PacketType.DiscoveryRequest, PacketType.DiscoveryResponse,
PacketType.ConnectRequest, PacketType.ConnectResponse
]
header = XStruct(
'pkt_type' / XEnum(Int16ub, PacketType),
'unprotected_payload_length' / Default(Int16ub, 0),
'protected_payload_length' / If(
FieldIn('pkt_type', [PacketType.ConnectRequest, PacketType.ConnectResponse]),
Default(Int16ub, 0)
),
'version' / Default(Int16ub, 2)
)
power_on_request = XStruct(
'liveid' / SGString()
)
discovery_request = XStruct(
'flags' / Int32ub,
'client_type' / XEnum(Int16ub, enum.ClientType),
'minimum_version' / Int16ub,
'maximum_version' / Int16ub
)
discovery_response = XStruct(
'flags' / XEnum(Int32ub, enum.PrimaryDeviceFlag),
'type' / XEnum(Int16ub, enum.ClientType),
'name' / SGString(),
'uuid' / UUIDAdapter('utf8'),
'last_error' / Int32ub,
'cert' / CertificateAdapter()
)
connect_request_unprotected = XStruct(
'sg_uuid' / UUIDAdapter(),
'public_key_type' / XEnum(Int16ub, enum.PublicKeyType),
'public_key' / XSwitch(this.public_key_type, {
enum.PublicKeyType.EC_DH_P256: Bytes(0x40),
enum.PublicKeyType.EC_DH_P384: Bytes(0x60),
enum.PublicKeyType.EC_DH_P521: Bytes(0x84)
}),
'iv' / Bytes(0x10)
)
connect_request_protected = XStruct(
'userhash' / SGString(),
'jwt' / SGString(),
'connect_request_num' / Int32ub,
'connect_request_group_start' / Int32ub,
'connect_request_group_end' / Int32ub
)
connect_response_unprotected = XStruct(
'iv' / Bytes(0x10)
)
connect_response_protected = XStruct(
'connect_result' / XEnum(Int16ub, enum.ConnectionResult),
'pairing_state' / XEnum(Int16ub, enum.PairedIdentityState),
'participant_id' / Int32ub
)
struct = XStruct(
'header' / header,
'unprotected_payload' / XSwitch(
this.header.pkt_type, {
PacketType.PowerOnRequest: power_on_request,
PacketType.DiscoveryRequest: discovery_request,
PacketType.DiscoveryResponse: discovery_response,
PacketType.ConnectRequest: connect_request_unprotected,
PacketType.ConnectResponse: connect_response_unprotected
}
),
'protected_payload' / CryptoTunnel(
XSwitch(
this.header.pkt_type, {
PacketType.ConnectRequest: connect_request_protected,
PacketType.ConnectResponse: connect_response_protected
},
Pass
)
)
)
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,132 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/sg/utils/events.py | """
Wrapper around asyncio's tasks
"""
import asyncio
class Event(object):
def __init__(self, asynchronous: bool = False):
self.handlers = []
self.asynchronous = asynchronous
def add(self, handler):
if not callable(handler):
raise TypeError("Handler should be callable")
self.handlers.append(handler)
def remove(self, handler):
if handler in self.handlers:
self.handlers.remove(handler)
def __iadd__(self, handler):
self.add(handler)
return self
def __isub__(self, handler):
self.remove(handler)
return self
def __call__(self, *args, **kwargs):
for handler in self.handlers:
if self.asynchronous:
asyncio.create_task(handler(*args, **kwargs))
else:
handler(*args, **kwargs)
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,133 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/rest/schemas/device.py | from typing import List, Dict, Optional
from pydantic import BaseModel
class DeviceStatusResponse(BaseModel):
liveid: str
ip_address: str
connection_state: str
pairing_state: str
device_status: str
last_error: int
authenticated_users_allowed: bool
console_users_allowed: bool
anonymous_connection_allowed: bool
is_certificate_pending: bool
class ActiveTitle(BaseModel):
title_id: str
aum: str
name: str
image: Optional[str]
type: Optional[str]
has_focus: bool
title_location: str
product_id: str
sandbox_id: str
class ConsoleStatusResponse(BaseModel):
live_tv_provider: str
kernel_version: str
locale: str
active_titles: Optional[List[ActiveTitle]]
class MediaStateResponse(BaseModel):
title_id: str
aum_id: str
asset_id: str
media_type: str
sound_level: str
enabled_commands: str
playback_status: str
rate: str
position: str
media_start: int
media_end: int
min_seek: int
max_seek: int
metadata: Optional[Dict[str, str]]
class TextSessionActiveResponse(BaseModel):
text_session_active: bool
class InfraredButton(BaseModel):
url: str
value: str
class InfraredDevice(BaseModel):
device_type: str
device_brand: Optional[str]
device_model: Optional[str]
device_name: Optional[str]
device_id: str
buttons: Dict[str, InfraredButton]
class InfraredResponse(BaseModel):
__root__: Dict[str, InfraredDevice]
class MediaCommandsResponse(BaseModel):
commands: List[str]
class InputResponse(BaseModel):
buttons: List[str]
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,134 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/auxiliary/packet.py | from construct import Struct, Int16ub
AUX_PACKET_MAGIC = 0xDEAD
aux_header_struct = Struct(
'magic' / Int16ub,
'payload_size' / Int16ub
# payload
# hash
)
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,135 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/auxiliary/relay.py | import logging
# import gevent
import asyncio
from typing import Optional
from xbox.sg.crypto import PKCS7Padding
from xbox.sg.utils.events import Event
from xbox.auxiliary import packer
from xbox.auxiliary.packet import aux_header_struct, AUX_PACKET_MAGIC
from xbox.auxiliary.crypto import AuxiliaryStreamCrypto
from xbox.sg.utils.struct import XStructObj
log = logging.getLogger(__name__)
class AuxiliaryPackerException(Exception):
pass
class ConsoleConnection(object):
BUFFER_SIZE = 2048
def __init__(self, address, port, crypto):
self.address = address
self.port = port
self.crypto = crypto
self._reader: Optional[asyncio.StreamReader] = None
self._writer: Optional[asyncio.StreamWriter] = None
self._recv_task: Optional[asyncio.Task] = None
self.on_message = Event()
def start(self):
self._reader, self._writer = asyncio.open_connection(
self.address, self.port
)
self._recv_task = asyncio.create_task(self._recv())
def stop(self):
self._recv_task.cancel()
def handle(self, data):
try:
msg = packer.unpack(data, self.crypto)
# Fire event
self.on_message(msg)
except Exception as e:
log.exception("Exception while handling Console Aux data, error: {}".format(e))
async def _recv(self):
while True:
data = await self._reader.read(4)
header = aux_header_struct.parse(data)
if header.magic != AUX_PACKET_MAGIC:
raise Exception('Invalid packet magic received from console')
payload_sz = header.payload_size + PKCS7Padding.size(
header.payload_size, 16
)
remaining_payload_bytes = payload_sz
while remaining_payload_bytes > 0:
tmp = await self._reader.read(remaining_payload_bytes)
remaining_payload_bytes -= len(tmp)
data += tmp
data += await self._reader.read(32)
self.handle(data)
async def send(self, msg):
packets = packer.pack(msg, self.crypto)
if not packets:
raise Exception('No data')
for packet in packets:
self._writer.write(packet)
class LocalConnection(asyncio.Protocol):
data_received_event = Event()
connection_made_event = Event()
def connection_made(self, transport: asyncio.BaseTransport) -> None:
self.transport = transport
self.connection_made(transport)
def data_received(self, data: bytes) -> None:
self.data_received(data)
def close_connection(self) -> None:
print('Close the client socket')
self.transport.close()
class AuxiliaryRelayService(object):
def __init__(
self,
loop: asyncio.AbstractEventLoop,
connection_info: XStructObj,
listen_port: int
):
if len(connection_info.endpoints) > 1:
raise Exception(
'Auxiliary Stream advertises more than one endpoint!'
)
self._loop = loop
self.crypto = AuxiliaryStreamCrypto.from_connection_info(
connection_info
)
self.target_ip = connection_info.endpoints[0].ip
self.target_port = connection_info.endpoints[0].port
self.console_connection = ConsoleConnection(
self.target_ip,
self.target_port,
self.crypto
)
self.server = self._loop.create_server(
lambda: LocalConnection(),
'0.0.0.0', listen_port
)
self.client_transport = None
async def run(self):
async with self.server as local_connection:
local_connection.data_received_event += self._handle_client_data
local_connection.connection_made_event += self.connection_made
while True:
# HACK / FIXME
await asyncio.sleep(10000)
def connection_made(self, transport):
self.client_transport = transport
peername = transport.get_extra_info('peername')
print('Connection from {}'.format(peername))
self.console_connection.on_message += self._handle_console_data
self.console_connection.start()
def _handle_console_data(self, data):
# Data from console gets decrypted and forwarded to aux client
if self.client_transport:
self.client_transport.send(data)
def _handle_client_data(self, data):
# Data from aux client gets encrypted and sent to console
self.console_connection.send(data)
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,136 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/auxiliary/packer.py | from typing import List
from xbox.auxiliary.crypto import AuxiliaryStreamCrypto
from xbox.sg.crypto import PKCS7Padding
from xbox.auxiliary.packet import aux_header_struct, AUX_PACKET_MAGIC
class AuxiliaryPackerException(Exception):
pass
def pack(
data: bytes,
crypto: AuxiliaryStreamCrypto,
server_data: bool = False
) -> List[bytes]:
"""
Encrypt auxiliary data blob
Args:
data: Data
crypto: Crypto context
server_data: Whether to encrypt with `server IV`
Returns:
bytes: Encrypted message
"""
# Store payload size without padding
payload_size = len(data)
# Pad data
padded = PKCS7Padding.pad(data, 16)
if not server_data:
ciphertext = crypto.encrypt(padded)
else:
ciphertext = crypto.encrypt_server(padded)
header = aux_header_struct.build(dict(
magic=AUX_PACKET_MAGIC,
payload_size=payload_size)
)
msg = header + ciphertext
hmac = crypto.hash(msg)
msg += hmac
messages = list()
while len(msg) > 1448:
fragment, msg = msg[:1448], msg[1448:]
messages.append(fragment)
messages.append(msg)
return messages
def unpack(
data: bytes,
crypto: AuxiliaryStreamCrypto,
client_data: bool = False
) -> bytes:
"""
Split and decrypt auxiliary data blob
Args:
data: Data blob
crypto: Crypto context
client_data: Whether to decrypt with 'client IV'
Returns:
bytes: Decrypted message
"""
# Split header from rest of data
header, payload, hmac = data[:4], data[4:-32], data[-32:]
parsed = aux_header_struct.parse(header)
if not crypto.verify(header + payload, hmac):
raise AuxiliaryPackerException('Hash verification failed')
if not client_data:
plaintext = crypto.decrypt(payload)
else:
plaintext = crypto.decrypt_client(payload)
# Cut off padding, before returning
return plaintext[:parsed.payload_size]
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,137 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/rest/api.py | from fastapi import APIRouter
from xbox.rest.routes import root, auth, device, web
api_router = APIRouter()
api_router.include_router(root.router, tags=["root"])
api_router.include_router(auth.router, prefix="/auth", tags=["auth"])
api_router.include_router(device.router, prefix="/device", tags=["device"])
api_router.include_router(web.router, prefix="/web", tags=["web"]) | {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,138 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/handlers/__init__.py | """
CLI script handlers
"""
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,139 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/scripts/rest_server.py | import argparse
import uvicorn
REST_DEFAULT_SERVER_PORT=5557
def main():
parser = argparse.ArgumentParser(description='Xbox REST server')
parser.add_argument(
'--host', '-b', default='127.0.0.1',
help='Interface address to bind the server')
parser.add_argument(
'--port', '-p', type=int, default=REST_DEFAULT_SERVER_PORT,
help=f'Port to bind to, default: {REST_DEFAULT_SERVER_PORT}')
parser.add_argument(
'--reload', '-r', action='store_true',
help='Auto-reload server on filechanges (DEVELOPMENT)')
args = parser.parse_args()
uvicorn.run('xbox.rest.app:app', host=args.host, port=args.port, reload=args.reload)
if __name__ == '__main__':
main() | {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,140 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /tests/test_rest_consolewrap.py | import pytest
from xbox.rest.consolewrap import ConsoleWrap
from xbox.sg import enum
def test_consolewrap_init(console):
wrap = ConsoleWrap(console)
assert wrap.console == console
assert 'text' in wrap.console.managers
assert 'input' in wrap.console.managers
assert 'stump' in wrap.console.managers
assert 'media' in wrap.console.managers
@pytest.mark.asyncio
async def test_discover():
discovered = await ConsoleWrap.discover(tries=1, blocking=False, timeout=1)
assert isinstance(discovered, list)
@pytest.mark.asyncio
async def test_poweron():
await ConsoleWrap.power_on('FD0123456789', tries=1, iterations=1)
def test_media_commands(console):
commands = ConsoleWrap(console).media_commands
assert isinstance(commands, dict)
assert 'play' in commands
for k, v in commands.items():
assert isinstance(k, str)
assert isinstance(v, enum.MediaControlCommand)
def test_input_keys(console):
keys = ConsoleWrap(console).input_keys
assert isinstance(keys, dict)
assert 'nexus' in keys
for k, v in keys.items():
assert isinstance(k, str)
assert isinstance(v, enum.GamePadButton)
def test_liveid(console):
assert ConsoleWrap(console).liveid == console.liveid
def test_available(console):
console._device_status = enum.DeviceStatus.Unavailable
assert ConsoleWrap(console).available is False
console._device_status = enum.DeviceStatus.Available
assert ConsoleWrap(console).available is True
def test_connected(console):
console._connection_state = enum.ConnectionState.Disconnected
assert ConsoleWrap(console).connected is False
console._connection_state = enum.ConnectionState.Connected
assert ConsoleWrap(console).connected is True
console._connection_state = enum.ConnectionState.Connecting
assert ConsoleWrap(console).connected is False
def test_usable(console):
console._connection_state = enum.ConnectionState.Reconnecting
assert ConsoleWrap(console).usable is False
console._connection_state = enum.ConnectionState.Disconnecting
assert ConsoleWrap(console).usable is False
console._connection_state = enum.ConnectionState.Disconnected
assert ConsoleWrap(console).usable is False
console._connection_state = enum.ConnectionState.Error
assert ConsoleWrap(console).usable is False
console._connection_state = enum.ConnectionState.Connected
assert ConsoleWrap(console).usable is True
def test_connection_state(console):
console._connection_state = enum.ConnectionState.Reconnecting
assert ConsoleWrap(console).connection_state == enum.ConnectionState.Reconnecting
def test_pairing_state(console):
console._pairing_state = enum.PairedIdentityState.Paired
assert ConsoleWrap(console).pairing_state == enum.PairedIdentityState.Paired
def test_device_status(console):
console._device_status = enum.DeviceStatus.Available
assert ConsoleWrap(console).device_status == enum.DeviceStatus.Available
def test_authenticated_users_allowed(console):
console.flags = enum.PrimaryDeviceFlag.AllowAuthenticatedUsers
assert ConsoleWrap(console).authenticated_users_allowed is True
console.flags = enum.PrimaryDeviceFlag.AllowConsoleUsers
assert ConsoleWrap(console).authenticated_users_allowed is False
console.flags = enum.PrimaryDeviceFlag.CertificatePending | enum.PrimaryDeviceFlag.AllowConsoleUsers
assert ConsoleWrap(console).authenticated_users_allowed is False
def test_console_users_allowed(console):
console.flags = enum.PrimaryDeviceFlag.AllowAuthenticatedUsers
assert ConsoleWrap(console).console_users_allowed is False
console.flags = enum.PrimaryDeviceFlag.AllowConsoleUsers
assert ConsoleWrap(console).console_users_allowed is True
console.flags = enum.PrimaryDeviceFlag.CertificatePending | enum.PrimaryDeviceFlag.AllowConsoleUsers
assert ConsoleWrap(console).console_users_allowed is True
def test_anonymous_connection_allowed(console):
console.flags = enum.PrimaryDeviceFlag.AllowAuthenticatedUsers
assert ConsoleWrap(console).anonymous_connection_allowed is False
console.flags = enum.PrimaryDeviceFlag.AllowConsoleUsers
assert ConsoleWrap(console).anonymous_connection_allowed is False
console.flags = enum.PrimaryDeviceFlag.CertificatePending | enum.PrimaryDeviceFlag.AllowAnonymousUsers
assert ConsoleWrap(console).anonymous_connection_allowed is True
def test_is_certificate_pending(console):
console.flags = enum.PrimaryDeviceFlag.AllowAuthenticatedUsers
assert ConsoleWrap(console).is_certificate_pending is False
console.flags = enum.PrimaryDeviceFlag.AllowConsoleUsers
assert ConsoleWrap(console).is_certificate_pending is False
console.flags = enum.PrimaryDeviceFlag.CertificatePending | enum.PrimaryDeviceFlag.AllowConsoleUsers
assert ConsoleWrap(console).is_certificate_pending is True
def test_console_status(console, console_status):
console._console_status = None
assert ConsoleWrap(console).console_status is None
console._console_status = console_status
status = ConsoleWrap(console).console_status
assert status is not None
def test_media_status(console, media_state, console_status, console_status_with_media):
console.media._media_state = None
assert ConsoleWrap(console).media_status is None
console.media._media_state = media_state
console._console_status = console_status_with_media
console._connection_state = enum.ConnectionState.Disconnecting
assert ConsoleWrap(console).media_status is None
console._console_status = console_status # miss-matched apps
console._connection_state = enum.ConnectionState.Connected
state = ConsoleWrap(console).media_status
assert ConsoleWrap(console).media_status is None
console._console_status = console_status_with_media
state = ConsoleWrap(console).media_status
def test_status(console):
status = ConsoleWrap(console).status
assert status is not None
@pytest.mark.asyncio
async def test_connect(console):
console.flags = enum.PrimaryDeviceFlag.AllowAuthenticatedUsers
console._device_status = enum.DeviceStatus.Available
console._connection_state = enum.ConnectionState.Disconnected
console._pairing_state = enum.PairedIdentityState.NotPaired
with pytest.raises(Exception):
await ConsoleWrap(console).connect()
console._connection_state = enum.ConnectionState.Connected
state = await ConsoleWrap(console).connect()
assert state == enum.ConnectionState.Connected
console._connection_state = enum.ConnectionState.Disconnected
console.flags = enum.PrimaryDeviceFlag.AllowAnonymousUsers
# blocks forever
# state = ConsoleWrap(console).connect()
# assert state == enum.ConnectionState.Disconnected
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,141 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/sg/packet/message.py | # flake8: noqa
"""
Construct containers for message header and payloads
"""
from construct import *
from xbox.sg import enum
from xbox.sg.enum import PacketType, MessageType
from xbox.sg.utils.struct import XStruct
from xbox.sg.utils.adapters import CryptoTunnel, UUIDAdapter, JsonAdapter, XSwitch, XEnum, SGString, PrefixedBytes
header = XStruct(
'pkt_type' / Default(XEnum(Int16ub, PacketType), PacketType.Message),
'protected_payload_length' / Default(Int16ub, 0),
'sequence_number' / Int32ub,
'target_participant_id' / Int32ub,
'source_participant_id' / Int32ub,
'flags' / BitStruct(
'version' / Default(BitsInteger(2), 2),
'need_ack' / Flag,
'is_fragment' / Flag,
'msg_type' / XEnum(BitsInteger(12), MessageType)
),
'channel_id' / Int64ub
)
fragment = XStruct(
'sequence_begin' / Int32ub,
'sequence_end' / Int32ub,
'data' / PrefixedBytes(Int16ub)
)
acknowledge = XStruct(
'low_watermark' / Int32ub,
'processed_list' / PrefixedArray(Int32ub, Int32ub),
'rejected_list' / PrefixedArray(Int32ub, Int32ub)
)
json = XStruct(
'text' / JsonAdapter(SGString())
)
local_join = XStruct(
'device_type' / XEnum(Int16ub, enum.ClientType),
'native_width' / Int16ub,
'native_height' / Int16ub,
'dpi_x' / Int16ub,
'dpi_y' / Int16ub,
'device_capabilities' / XEnum(Int64ub, enum.DeviceCapabilities),
'client_version' / Int32ub,
'os_major_version' / Int32ub,
'os_minor_version' / Int32ub,
'display_name' / SGString()
)
auxiliary_stream = XStruct(
'connection_info_flag' / Int8ub,
'connection_info' / If(this.connection_info_flag == 1, Struct(
'crypto_key' / PrefixedBytes(Int16ub),
'server_iv' / PrefixedBytes(Int16ub),
'client_iv' / PrefixedBytes(Int16ub),
'sign_hash' / PrefixedBytes(Int16ub),
'endpoints' / PrefixedArray(Int16ub, Struct(
'ip' / SGString(),
'port' / SGString()
))
))
)
power_off = XStruct(
'liveid' / SGString()
)
game_dvr_record = XStruct(
'start_time_delta' / Int32sb,
'end_time_delta' / Int32sb
)
unsnap = XStruct(
'unk' / Bytes(1)
)
gamepad = XStruct(
'timestamp' / Int64ub,
'buttons' / XEnum(Int16ub, enum.GamePadButton),
'left_trigger' / Float32b,
'right_trigger' / Float32b,
'left_thumbstick_x' / Float32b,
'left_thumbstick_y' / Float32b,
'right_thumbstick_x' / Float32b,
'right_thumbstick_y' / Float32b
)
paired_identity_state_changed = XStruct(
'state' / XEnum(Int16ub, enum.PairedIdentityState)
)
media_state = XStruct(
'title_id' / Int32ub,
'aum_id' / SGString(),
'asset_id' / SGString(),
'media_type' / XEnum(Int16ub, enum.MediaType),
'sound_level' / XEnum(Int16ub, enum.SoundLevel),
'enabled_commands' / XEnum(Int32ub, enum.MediaControlCommand),
'playback_status' / XEnum(Int16ub, enum.MediaPlaybackStatus),
'rate' / Float32b,
'position' / Int64ub,
'media_start' / Int64ub,
'media_end' / Int64ub,
'min_seek' / Int64ub,
'max_seek' / Int64ub,
'metadata' / PrefixedArray(Int16ub, Struct(
'name' / SGString(),
'value' / SGString()
))
)
media_controller_removed = XStruct(
'title_id' / Int32ub
)
media_command_result = XStruct(
'request_id' / Int64ub,
'result' / Int32ub
)
media_command = XStruct(
'request_id' / Int64ub,
'title_id' / Int32ub,
'command' / XEnum(Int32ub, enum.MediaControlCommand),
'seek_position' / If(this.command == enum.MediaControlCommand.Seek, Int64ub)
)
orientation = XStruct(
'timestamp' / Int64ub,
'rotation_matrix_value' / Float32b,
'w' / Float32b,
'x' / Float32b,
'y' / Float32b,
'z' / Float32b
)
compass = XStruct(
'timestamp' / Int64ub,
'magnetic_north' / Float32b,
'true_north' / Float32b
)
inclinometer = XStruct(
'timestamp' / Int64ub,
'pitch' / Float32b,
'roll' / Float32b,
'yaw' / Float32b
)
gyrometer = XStruct(
'timestamp' / Int64ub,
'angular_velocity_x' / Float32b,
'angular_velocity_y' / Float32b,
'angular_velocity_z' / Float32b
)
accelerometer = XStruct(
'timestamp' / Int64ub,
'acceleration_x' / Float32b,
'acceleration_y' / Float32b,
'acceleration_z' / Float32b
)
_touchpoint = XStruct(
'touchpoint_id' / Int32ub,
'touchpoint_action' / XEnum(Int16ub, enum.TouchAction),
'touchpoint_x' / Int32ub,
'touchpoint_y' / Int32ub
)
touch = XStruct(
'touch_msg_timestamp' / Int32ub,
'touchpoints' / PrefixedArray(Int16ub, _touchpoint)
)
disconnect = XStruct(
'reason' / XEnum(Int32ub, enum.DisconnectReason),
'error_code' / Int32ub
)
stop_channel = XStruct(
'target_channel_id' / Int64ub
)
start_channel_request = XStruct(
'channel_request_id' / Int32ub,
'title_id' / Int32ub,
'service' / UUIDAdapter(),
'activity_id' / Int32ub
)
start_channel_response = XStruct(
'channel_request_id' / Int32ub,
'target_channel_id' / Int64ub,
'result' / XEnum(Int32ub, enum.SGResultCode)
)
title_launch = XStruct(
'location' / XEnum(Int16ub, enum.ActiveTitleLocation),
'uri' / SGString()
)
system_text_done = XStruct(
'text_session_id' / Int32ub,
'text_version' / Int32ub,
'flags' / Int32ub,
'result' / XEnum(Int32ub, enum.TextResult)
)
system_text_acknowledge = XStruct(
'text_session_id' / Int32ub,
'text_version_ack' / Int32ub
)
_system_text_input_delta = XStruct(
'offset' / Int32ub,
'delete_count' / Int32ub,
'insert_content' / SGString()
)
system_text_input = XStruct(
'text_session_id' / Int32ub,
'base_version' / Int32ub,
'submitted_version' / Int32ub,
'total_text_byte_len' / Int32ub,
'selection_start' / Int32sb,
'selection_length' / Int32sb,
'flags' / Int16ub,
'text_chunk_byte_start' / Int32ub,
'text_chunk' / SGString(),
'delta' / Optional(PrefixedArray(Int16ub, _system_text_input_delta))
)
title_text_selection = XStruct(
'text_session_id' / Int64ub,
'text_buffer_version' / Int32ub,
'start' / Int32ub,
'length' / Int32ub
)
title_text_input = XStruct(
'text_session_id' / Int64ub,
'text_buffer_version' / Int32ub,
'result' / XEnum(Int16ub, enum.TextResult),
'text' / SGString()
)
text_configuration = XStruct(
'text_session_id' / Int64ub,
'text_buffer_version' / Int32ub,
'text_options' / XEnum(Int32ub, enum.TextOption),
'input_scope' / XEnum(Int32ub, enum.TextInputScope),
'max_text_length' / Int32ub,
'locale' / SGString(),
'prompt' / SGString()
)
_active_title = XStruct(
'title_id' / Int32ub,
'disposition' / BitStruct(
'has_focus' / Flag,
'title_location' / XEnum(BitsInteger(15), enum.ActiveTitleLocation)
),
'product_id' / UUIDAdapter(),
'sandbox_id' / UUIDAdapter(),
'aum' / SGString()
)
console_status = XStruct(
'live_tv_provider' / Int32ub,
'major_version' / Int32ub,
'minor_version' / Int32ub,
'build_number' / Int32ub,
'locale' / SGString(),
'active_titles' / PrefixedArray(Int16ub, _active_title)
)
active_surface_change = XStruct(
'surface_type' / XEnum(Int16ub, enum.ActiveSurfaceType),
'server_tcp_port' / Int16ub,
'server_udp_port' / Int16ub,
'session_id' / UUIDAdapter(),
'render_width' / Int16ub,
'render_height' / Int16ub,
'master_session_key' / Bytes(0x20)
)
message_structs = {
MessageType.Ack: acknowledge,
MessageType.Group: Pass,
MessageType.LocalJoin: local_join,
MessageType.StopActivity: Pass,
MessageType.AuxilaryStream: auxiliary_stream,
MessageType.ActiveSurfaceChange: active_surface_change,
MessageType.Navigate: Pass,
MessageType.Json: json,
MessageType.Tunnel: Pass,
MessageType.ConsoleStatus: console_status,
MessageType.TitleTextConfiguration: text_configuration,
MessageType.TitleTextInput: title_text_input,
MessageType.TitleTextSelection: title_text_selection,
MessageType.MirroringRequest: Pass,
MessageType.TitleLaunch: title_launch,
MessageType.StartChannelRequest: start_channel_request,
MessageType.StartChannelResponse: start_channel_response,
MessageType.StopChannel: stop_channel,
MessageType.System: Pass,
MessageType.Disconnect: disconnect,
MessageType.TitleTouch: touch,
MessageType.Accelerometer: accelerometer,
MessageType.Gyrometer: gyrometer,
MessageType.Inclinometer: inclinometer,
MessageType.Compass: compass,
MessageType.Orientation: orientation,
MessageType.PairedIdentityStateChanged: paired_identity_state_changed,
MessageType.Unsnap: unsnap,
MessageType.GameDvrRecord: game_dvr_record,
MessageType.PowerOff: power_off,
MessageType.MediaControllerRemoved: media_controller_removed,
MessageType.MediaCommand: media_command,
MessageType.MediaCommandResult: media_command_result,
MessageType.MediaState: media_state,
MessageType.Gamepad: gamepad,
MessageType.SystemTextConfiguration: text_configuration,
MessageType.SystemTextInput: system_text_input,
MessageType.SystemTouch: touch,
MessageType.SystemTextAck: system_text_acknowledge,
MessageType.SystemTextDone: system_text_done
}
struct = XStruct(
'header' / header,
'protected_payload' / CryptoTunnel(
IfThenElse(this.header.flags.is_fragment, fragment,
XSwitch(
this.header.flags.msg_type,
message_structs,
Pass
)
)
)
)
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,142 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /tests/test_auxmanager.py | import pytest
from xbox.sg.enum import ServiceChannel
from xbox.auxiliary.manager import TitleManager, TitleManagerError
def test_manager_messagehandling(console, decrypted_packets):
manager = TitleManager(console)
def handle_msg(msg):
manager._pre_on_message(msg, ServiceChannel.Title)
assert manager.active_surface is None
assert manager.connection_info is None
# Send unpacked msgs to manager
handle_msg(decrypted_packets['active_surface_change'])
handle_msg(decrypted_packets['auxiliary_stream_connection_info'])
invalid_msg = decrypted_packets['auxiliary_stream_hello']
invalid_msg.header.flags(msg_type=0x3)
with pytest.raises(TitleManagerError):
handle_msg(invalid_msg)
assert manager.active_surface == decrypted_packets['active_surface_change'].protected_payload
assert manager.connection_info == decrypted_packets['auxiliary_stream_connection_info'].protected_payload.connection_info
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,143 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /tests/conftest.py | import os
import pytest
import uuid
import json
from fastapi import FastAPI
from fastapi.testclient import TestClient
from binascii import unhexlify
from construct import Container
from xbox.sg import enum, packer, packet
from xbox.sg.console import Console
from xbox.sg.crypto import Crypto
from xbox.sg.manager import MediaManager, TextManager, InputManager
from xbox.auxiliary.crypto import AuxiliaryStreamCrypto
from xbox.stump.manager import StumpManager
from xbox.rest.app import app as rest_app
from xbox.rest.consolewrap import ConsoleWrap
@pytest.fixture(scope='session')
def uuid_dummy():
return uuid.UUID('de305d54-75b4-431b-adb2-eb6b9e546014')
@pytest.fixture(scope='session')
def console_address():
return '10.11.12.12'
@pytest.fixture(scope='session')
def console_name():
return 'TestConsole'
@pytest.fixture(scope='session')
def console_liveid():
return 'FD0000123456789'
@pytest.fixture(scope='session')
def console_flags():
return enum.PrimaryDeviceFlag.AllowAnonymousUsers | enum.PrimaryDeviceFlag.AllowAuthenticatedUsers
@pytest.fixture(scope='session')
def public_key_bytes():
return unhexlify(
b'041815d5382df79bd792a8d8342fbc717eacef6a258f779279e5463573e06b'
b'f84c6a88fac904870bf3a26f856e65f483195c4323eef47a048f23a031da6bd0929d'
)
@pytest.fixture(scope='session')
def shared_secret_bytes():
return unhexlify(
'82bba514e6d19521114940bd65121af234c53654a8e67add7710b3725db44f77'
'30ed8e3da7015a09fe0f08e9bef3853c0506327eb77c9951769d923d863a2f5e'
)
@pytest.fixture(scope='session')
def crypto(shared_secret_bytes):
return Crypto.from_shared_secret(shared_secret_bytes)
@pytest.fixture(scope='session')
def console(console_address, console_name, uuid_dummy, console_liveid, console_flags, public_key_bytes):
c = Crypto.from_bytes(public_key_bytes)
console = Console(
console_address, console_name, uuid_dummy,
console_liveid, console_flags, 0, c.foreign_pubkey
)
console.add_manager(StumpManager)
console.add_manager(MediaManager)
console.add_manager(TextManager)
console.add_manager(InputManager)
return console
@pytest.fixture(scope='session')
def public_key(public_key_bytes):
c = Crypto.from_bytes(public_key_bytes)
return c.foreign_pubkey
@pytest.fixture(scope='session')
def packets():
# Who cares about RAM anyway?
data = {}
data_path = os.path.join(os.path.dirname(__file__), 'data', 'packets')
for f in os.listdir(data_path):
with open(os.path.join(data_path, f), 'rb') as fh:
data[f] = fh.read()
return data
@pytest.fixture(scope='session')
def stump_json():
# Who cares about RAM anyway?
data = {}
data_path = os.path.join(os.path.dirname(__file__), 'data', 'stump_json')
for f in os.listdir(data_path):
with open(os.path.join(data_path, f), 'rt') as fh:
data[f] = json.load(fh)
return data
@pytest.fixture(scope='session')
def decrypted_packets(packets, crypto):
return {k: packer.unpack(v, crypto) for k, v in packets.items()}
@pytest.fixture(scope='session')
def pcap_filepath():
return os.path.join(os.path.dirname(__file__), 'data', 'sg_capture.pcap')
@pytest.fixture(scope='session')
def certificate_data():
filepath = os.path.join(os.path.dirname(__file__), 'data', 'selfsigned_cert.bin')
with open(filepath, 'rb') as f:
data = f.read()
return data
@pytest.fixture(scope='session')
def json_fragments():
filepath = os.path.join(os.path.dirname(__file__), 'data', 'json_fragments.json')
with open(filepath, 'rt') as f:
data = json.load(f)
return data['fragments']
@pytest.fixture(scope='session')
def aux_streams():
data = {}
data_path = os.path.join(os.path.dirname(__file__), 'data', 'aux_streams')
for f in os.listdir(data_path):
with open(os.path.join(data_path, f), 'rb') as fh:
data[f] = fh.read()
return data
@pytest.fixture(scope='session')
def aux_crypto(decrypted_packets):
connection_info = decrypted_packets['auxiliary_stream_connection_info'].protected_payload.connection_info
return AuxiliaryStreamCrypto.from_connection_info(connection_info)
@pytest.fixture
def rest_client():
app = FastAPI()
client = TestClient(app)
yield client
@pytest.fixture(scope='session')
def media_state():
return packet.message.media_state(
title_id=274278798,
aum_id='AIVDE_s9eep9cpjhg6g!App',
asset_id='',
media_type=enum.MediaType.Video,
sound_level=enum.SoundLevel.Full,
enabled_commands=enum.MediaControlCommand.Play | enum.MediaControlCommand.Pause,
playback_status=enum.MediaPlaybackStatus.Playing,
rate=1.00,
position=0,
media_start=0,
media_end=0,
min_seek=0,
max_seek=0,
metadata=[
Container(name='title', value='Some Movietitle'),
Container(name='subtitle', value='')
]
)
@pytest.fixture(scope='session')
def active_title():
struct = packet.message._active_title(
title_id=714681658,
product_id=uuid.UUID('00000000-0000-0000-0000-000000000000'),
sandbox_id=uuid.UUID('00000000-0000-0000-0000-000000000000'),
aum='Xbox.Home_8wekyb3d8bbwe!Xbox.Home.Application',
disposition=Container(
has_focus=True,
title_location=enum.ActiveTitleLocation.StartView
)
)
return struct
@pytest.fixture(scope='session')
def active_media_title():
struct = packet.message._active_title(
title_id=714681658,
product_id=uuid.UUID('00000000-0000-0000-0000-000000000000'),
sandbox_id=uuid.UUID('00000000-0000-0000-0000-000000000000'),
aum='AIVDE_s9eep9cpjhg6g!App',
disposition=Container(
has_focus=True,
title_location=enum.ActiveTitleLocation.StartView
)
)
return struct
@pytest.fixture(scope='session')
def console_status(active_title):
return packet.message.console_status(
live_tv_provider=0,
major_version=10,
minor_version=0,
build_number=14393,
locale='en-US',
active_titles=[
active_title
]
)
@pytest.fixture(scope='session')
def console_status_with_media(active_media_title):
return packet.message.console_status(
live_tv_provider=0,
major_version=10,
minor_version=0,
build_number=14393,
locale='en-US',
active_titles=[
active_media_title
]
)
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,144 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/rest/routes/auth.py | import secrets
import aiohttp
from typing import Optional
from fastapi import APIRouter, HTTPException, status
from fastapi.responses import RedirectResponse
from .. import singletons, schemas
from ..common import generate_authentication_status, generate_authentication_manager
from xbox.webapi.scripts import CLIENT_ID, CLIENT_SECRET
from xbox.webapi.api.client import XboxLiveClient
router = APIRouter()
@router.get('/', response_model=schemas.AuthenticationStatus)
def authentication_overview():
if not singletons.authentication_manager:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail='You have to login first')
return generate_authentication_status(singletons.authentication_manager)
@router.get('/login', status_code=status.HTTP_307_TEMPORARY_REDIRECT)
async def xboxlive_login(
client_id: str = CLIENT_ID,
client_secret: Optional[str] = CLIENT_SECRET,
redirect_uri: str = 'http://localhost:5557/auth/callback',
scopes: str = 'Xboxlive.signin,Xboxlive.offline_access'
):
if scopes:
scopes = scopes.split(',')
auth_session_config = schemas.AuthSessionConfig(
client_id=client_id,
client_secret=client_secret,
redirect_uri=redirect_uri,
scopes=scopes
)
# Create local instance of AuthenticationManager
# -> Final instance will be created and saved in the
# callback route
auth_mgr = generate_authentication_manager(auth_session_config)
# Generating a random state to transmit in the authorization url
session_state = secrets.token_hex(10)
# Storing the state/session config so it can be retrieved
# in the callback function
singletons.auth_session_configs.update({session_state: auth_session_config})
authorization_url = auth_mgr.generate_authorization_url(state=session_state)
return RedirectResponse(authorization_url)
@router.get('/callback', status_code=status.HTTP_307_TEMPORARY_REDIRECT)
async def xboxlive_login_callback(
code: str,
state: str,
error: Optional[str] = None
):
if error:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=error)
elif not code or not state:
parameter_name = 'Code' if not code else 'State'
error_detail = f'{parameter_name} missing from authorization callback'
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=error_detail)
# Get auth session config that was set previously when
# generating authorization redirect
auth_session_config = singletons.auth_session_configs.get(state)
if not auth_session_config:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f'Auth session config for state \'{state}\' not found'
)
# Construct authentication manager that will be cached
auth_mgr = generate_authentication_manager(
auth_session_config,
singletons.http_session
)
await auth_mgr.request_tokens(code)
singletons.authentication_manager = auth_mgr
singletons.xbl_client = XboxLiveClient(singletons.authentication_manager)
return RedirectResponse(url='/auth')
@router.get('/refresh', status_code=status.HTTP_307_TEMPORARY_REDIRECT)
async def refresh_tokens():
if not singletons.authentication_manager:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail='You have to login first')
async with aiohttp.ClientSession() as http_session:
singletons.authentication_manager.session = http_session
singletons.authentication_manager.oauth = await singletons.authentication_manager.refresh_oauth_token()
singletons.authentication_manager.user_token = await singletons.authentication_manager.request_user_token()
singletons.authentication_manager.xsts_token = await singletons.authentication_manager.request_xsts_token()
return RedirectResponse(url='/auth')
@router.get('/logout', response_model=schemas.GeneralResponse)
async def xboxlive_logout():
singletons.authentication_manager = None
return schemas.GeneralResponse(success=True)
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,145 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/handlers/gamepad_input.py | """
Input smartglass client
Send controller input via stdin (terminal) to the console
"""
import sys
import logging
from xbox.sg.enum import GamePadButton
LOGGER = logging.getLogger(__name__)
input_map = {
"i": GamePadButton.DPadUp,
"k": GamePadButton.DPadDown,
"j": GamePadButton.DPadLeft,
"l": GamePadButton.DPadRight,
"a": GamePadButton.PadA,
"b": GamePadButton.PadB,
"x": GamePadButton.PadX,
"y": GamePadButton.PadY,
"t": GamePadButton.View,
"z": GamePadButton.Nexu,
"u": GamePadButton.Menu
}
def get_getch_func():
"""
Source: https://code.activestate.com/recipes/577977-get-single-keypress/
"""
try:
import tty
import termios
except ImportError:
# Probably Windows.
try:
import msvcrt
except ImportError:
# Just give up here.
raise ImportError('getch not available')
else:
return msvcrt.getch
else:
def getch():
"""
getch() -> key character
Read a single keypress from stdin and return the resulting character.
Nothing is echoed to the console. This call will block if a keypress
is not already available, but will not wait for Enter to be pressed.
If the pressed key was a modifier key, nothing will be detected; if
it were a special function key, it may return the first character of
of an escape sequence, leaving additional characters in the buffer.
"""
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
return getch
async def input_loop(console):
getch = get_getch_func()
while True:
ch = getch()
print(ch)
if ord(ch) == 3: # CTRL-C
sys.exit(1)
elif ch not in input_map:
continue
button = input_map[ch]
await console.gamepad_input(button)
await console.wait(0.1)
await console.gamepad_input(GamePadButton.Clear)
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,146 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /tests/test_packer.py | from binascii import hexlify, unhexlify
from xbox.sg import packer, enum
from xbox.sg.constants import MessageTarget
def _unpack(data, crypto):
return packer.unpack(data, crypto)
def _pack(msg, crypto):
return packer.pack(msg, crypto)
def test_poweron_request(packets, crypto):
unpacked = _unpack(packets['poweron_request'], crypto)
assert unpacked.header.pkt_type == enum.PacketType.PowerOnRequest
assert unpacked.header.unprotected_payload_length == 19
assert unpacked.header.version == 0
assert unpacked.unprotected_payload.liveid == 'FD00112233FFEE66'
def test_discovery_request(packets, crypto):
unpacked = _unpack(packets['discovery_request'], crypto)
assert unpacked.header.pkt_type == enum.PacketType.DiscoveryRequest
assert unpacked.header.unprotected_payload_length == 10
assert unpacked.header.version == 0
assert unpacked.unprotected_payload.flags == 0
assert unpacked.unprotected_payload.client_type == enum.ClientType.Android
assert unpacked.unprotected_payload.minimum_version == 0
assert unpacked.unprotected_payload.maximum_version == 2
def test_discovery_response(packets, crypto, public_key):
unpacked = _unpack(packets['discovery_response'], crypto)
assert unpacked.header.pkt_type == enum.PacketType.DiscoveryResponse
assert unpacked.header.unprotected_payload_length == 580
assert unpacked.header.version == 2
assert unpacked.unprotected_payload.name == 'XboxOne'
assert str(unpacked.unprotected_payload.uuid) == 'DE305D54-75B4-431B-ADB2-EB6B9E546014'.lower()
assert unpacked.unprotected_payload.last_error == 0
assert unpacked.unprotected_payload.cert.liveid == 'FFFFFFFFFFF'
assert unpacked.unprotected_payload.cert.pubkey.public_numbers() == public_key.public_numbers()
def test_connect_request(packets, crypto):
unpacked = _unpack(packets['connect_request'], crypto)
assert unpacked.header.pkt_type == enum.PacketType.ConnectRequest
assert unpacked.header.unprotected_payload_length == 98
assert unpacked.header.protected_payload_length == 47
assert unpacked.header.version == 2
assert str(unpacked.unprotected_payload.sg_uuid) == 'de305d54-75b4-431b-adb2-eb6b9e546014'
assert unpacked.unprotected_payload.public_key == b'\xff' * 64
assert unpacked.unprotected_payload.iv == unhexlify('2979d25ea03d97f58f46930a288bf5d2')
assert unpacked.protected_payload.userhash == 'deadbeefdeadbeefde'
assert unpacked.protected_payload.jwt == 'dummy_token'
assert unpacked.protected_payload.connect_request_num == 0
assert unpacked.protected_payload.connect_request_group_start == 0
assert unpacked.protected_payload.connect_request_group_end == 2
def test_connect_request_anonymous(packets, crypto):
unpacked = _unpack(packets['connect_request_anonymous'], crypto)
assert unpacked.header.pkt_type == enum.PacketType.ConnectRequest
assert unpacked.header.unprotected_payload_length == 98
assert unpacked.header.protected_payload_length == 18
assert unpacked.header.version == 2
assert str(unpacked.unprotected_payload.sg_uuid) == 'de305d54-75b4-431b-adb2-eb6b9e546014'
assert unpacked.unprotected_payload.public_key == b'\xff' * 64
assert unpacked.unprotected_payload.iv == unhexlify('2979d25ea03d97f58f46930a288bf5d2')
assert unpacked.protected_payload.userhash == ''
assert unpacked.protected_payload.jwt == ''
assert unpacked.protected_payload.connect_request_num == 0
assert unpacked.protected_payload.connect_request_group_start == 0
assert unpacked.protected_payload.connect_request_group_end == 1
def test_connect_response(packets, crypto):
unpacked = _unpack(packets['connect_response'], crypto)
assert unpacked.header.pkt_type == enum.PacketType.ConnectResponse
assert unpacked.header.unprotected_payload_length == 16
assert unpacked.header.protected_payload_length == 8
assert unpacked.header.version == 2
assert unpacked.unprotected_payload.iv == unhexlify('c6373202bdfd1167cf9693491d22322a')
assert unpacked.protected_payload.connect_result == enum.ConnectionResult.Success
assert unpacked.protected_payload.pairing_state == enum.PairedIdentityState.NotPaired
assert unpacked.protected_payload.participant_id == 31
def test_local_join(packets, crypto):
unpacked = _unpack(packets['local_join'], crypto)
payload = unpacked.protected_payload
assert unpacked.header.flags.msg_type == enum.MessageType.LocalJoin
assert payload.device_type == enum.ClientType.Android
assert payload.native_width == 600
assert payload.native_height == 1024
assert payload.dpi_x == 160
assert payload.dpi_y == 160
assert payload.device_capabilities == enum.DeviceCapabilities.All
assert payload.client_version == 133713371
assert payload.os_major_version == 42
assert payload.os_minor_version == 0
assert payload.display_name == 'package.name.here'
def test_acknowledge(packets, crypto):
unpacked = _unpack(packets['acknowledge'], crypto)
payload = unpacked.protected_payload
assert unpacked.header.flags.msg_type == enum.MessageType.Ack
assert payload.low_watermark == 0
assert payload.processed_list == [1]
assert payload.rejected_list == []
def test_paired_identity_state_changed(packets, crypto):
unpacked = _unpack(packets['paired_identity_state_changed'], crypto)
payload = unpacked.protected_payload
assert unpacked.header.flags.msg_type == enum.MessageType.PairedIdentityStateChanged
assert payload.state == enum.PairedIdentityState.Paired
def test_fragmented_message(packets, crypto):
data = unhexlify(
b'6a5297cd00424d6963726f736f66742e426c75726179506c617965725f3877656b79623364386262'
b'77652158626f782e426c75726179506c617965722e4170706c69636174696f6e0008883438303036'
b'31303036433030364630303230303035343030363830303635303032303030343630303631303036'
b'43303036433030323030303646303036363030323030303532303036353030363130303633303036'
b'38303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'30303030303030303030303030303030303030303030303030303030303030303030303030303030'
b'303030303030303030303030303030303030303030303030'
)
unpacked = _unpack(packets['fragment_media_state_0'], crypto)
payload = unpacked.protected_payload
assert unpacked.header.flags.msg_type == enum.MessageType.MediaState
assert payload.sequence_begin == 22
assert payload.sequence_end == 25
assert payload.data == data
def test_gamedvr_record(packets, crypto):
unpacked = _unpack(packets['gamedvr_record'], crypto)
payload = unpacked.protected_payload
assert unpacked.header.flags.msg_type == enum.MessageType.GameDvrRecord
assert payload.start_time_delta == -60
assert payload.end_time_delta == 0
def test_title_launch(packets, crypto):
unpacked = _unpack(packets['title_launch'], crypto)
payload = unpacked.protected_payload
assert unpacked.header.flags.msg_type == enum.MessageType.TitleLaunch
assert payload.location == enum.ActiveTitleLocation.Fill
assert payload.uri == 'ms-xbl-0D174C79://default/'
def test_start_channel_request(packets, crypto):
unpacked = _unpack(packets['start_channel_request'], crypto)
payload = unpacked.protected_payload
assert unpacked.header.flags.msg_type == enum.MessageType.StartChannelRequest
assert payload.channel_request_id == 1
assert payload.title_id == 0
assert payload.service == MessageTarget.SystemInputUUID
assert payload.activity_id == 0
def test_start_channel_request_title(packets, crypto):
unpacked = _unpack(packets['start_channel_request_title_channel'], crypto)
payload = unpacked.protected_payload
assert unpacked.header.flags.msg_type == enum.MessageType.StartChannelRequest
assert payload.channel_request_id == 16
assert payload.title_id == 1256782258
assert payload.service == MessageTarget.TitleUUID
assert payload.activity_id == 0
def test_start_channel_response(packets, crypto):
unpacked = _unpack(packets['start_channel_response'], crypto)
payload = unpacked.protected_payload
assert unpacked.header.flags.msg_type == enum.MessageType.StartChannelResponse
assert payload.channel_request_id == 1
assert payload.target_channel_id == 148
assert payload.result == enum.SGResultCode.SG_E_SUCCESS
def test_console_status(packets, crypto):
unpacked = _unpack(packets['console_status'], crypto)
payload = unpacked.protected_payload
assert unpacked.header.flags.msg_type == enum.MessageType.ConsoleStatus
assert payload.live_tv_provider == 0
assert payload.major_version == 10
assert payload.minor_version == 0
assert payload.build_number == 14393
assert payload.locale == 'en-US'
assert len(payload.active_titles) == 1
assert payload.active_titles[0].title_id == 714681658
assert payload.active_titles[0].disposition.has_focus is True
assert payload.active_titles[0].disposition.title_location == enum.ActiveTitleLocation.StartView
assert str(payload.active_titles[0].product_id) == '00000000-0000-0000-0000-000000000000'
assert str(payload.active_titles[0].sandbox_id) == '00000000-0000-0000-0000-000000000000'
assert payload.active_titles[0].aum == 'Xbox.Home_8wekyb3d8bbwe!Xbox.Home.Application'
def test_active_surface_change(packets, crypto):
unpacked = _unpack(packets['active_surface_change'], crypto)
payload = unpacked.protected_payload
assert unpacked.header.flags.msg_type == enum.MessageType.ActiveSurfaceChange
assert payload.surface_type == enum.ActiveSurfaceType.HTML
assert payload.server_tcp_port == 0
assert payload.server_udp_port == 0
assert str(payload.session_id) == '00000000-0000-0000-0000-000000000000'
assert payload.render_width == 0
assert payload.render_height == 0
assert hexlify(payload.master_session_key) == b'0000000000000000000000000000000000000000000000000000000000000000'
def test_auxiliary_stream_hello(packets, crypto):
unpacked = _unpack(packets['auxiliary_stream_hello'], crypto)
payload = unpacked.protected_payload
assert unpacked.header.flags.msg_type == enum.MessageType.AuxilaryStream
assert payload.connection_info_flag == 0
def test_auxiliary_stream_connection_info(packets, crypto):
unpacked = _unpack(packets['auxiliary_stream_connection_info'], crypto)
payload = unpacked.protected_payload
assert unpacked.header.flags.msg_type == enum.MessageType.AuxilaryStream
assert payload.connection_info_flag == 1
assert hexlify(payload.connection_info.crypto_key) == b'14188d32cca3564a6d53f34ad8d21728'
assert hexlify(payload.connection_info.server_iv) == b'09dcb570c9715cf01e0dfaf5ac718445'
assert hexlify(payload.connection_info.client_iv) == b'9fa17a415b1bab5ae320cdceb5e37297'
assert hexlify(payload.connection_info.sign_hash) == b'473f076d2fee90b27821fcad9d0ae7efdfd08f250823db95b90f90cac95784f9'
assert len(payload.connection_info.endpoints) == 1
assert payload.connection_info.endpoints[0].ip == '192.168.8.104'
assert payload.connection_info.endpoints[0].port == '57344'
def test_disconnect(packets, crypto):
unpacked = _unpack(packets['disconnect'], crypto)
payload = unpacked.protected_payload
assert unpacked.header.flags.msg_type == enum.MessageType.Disconnect
assert payload.reason == enum.DisconnectReason.Unspecified
assert payload.error_code == 0
def test_poweroff(packets, crypto):
unpacked = _unpack(packets['power_off'], crypto)
payload = unpacked.protected_payload
assert unpacked.header.flags.msg_type == enum.MessageType.PowerOff
assert payload.liveid == 'FD00112233FFEE66'
def test_json(packets, crypto):
unpacked = _unpack(packets['json'], crypto)
payload = unpacked.protected_payload
assert unpacked.header.flags.msg_type == enum.MessageType.Json
assert payload.text == {'request': 'GetConfiguration', 'msgid': '2ed6c0fd.2'}
def test_gamepad(packets, crypto):
unpacked = _unpack(packets['gamepad'], crypto)
payload = unpacked.protected_payload
assert unpacked.header.flags.msg_type == enum.MessageType.Gamepad
assert payload.timestamp == 0
assert payload.buttons == enum.GamePadButton.PadB
assert payload.left_trigger == 0.0
assert payload.right_trigger == 0.0
assert payload.left_thumbstick_x == 0.0
assert payload.left_thumbstick_y == 0.0
assert payload.right_thumbstick_x == 0.0
assert payload.right_thumbstick_y == 0.0
def test_media_command(packets, crypto):
unpacked = _unpack(packets['media_command'], crypto)
payload = unpacked.protected_payload
assert unpacked.header.flags.msg_type == enum.MessageType.MediaCommand
assert payload.request_id == 0
assert payload.title_id == 274278798
assert payload.command == enum.MediaControlCommand.FastForward
assert payload.seek_position is None
def test_media_state(packets, crypto):
unpacked = _unpack(packets['media_state'], crypto)
payload = unpacked.protected_payload
assert unpacked.header.flags.msg_type == enum.MessageType.MediaState
assert payload.title_id == 274278798
assert payload.aum_id == 'AIVDE_s9eep9cpjhg6g!App'
assert payload.asset_id == ''
assert payload.media_type == enum.MediaType.NoMedia
assert payload.sound_level == enum.SoundLevel.Full
assert payload.enabled_commands == enum.MediaControlCommand(33758)
assert payload.playback_status == enum.MediaPlaybackStatus.Stopped
assert payload.rate == 0.0
assert payload.position == 0
assert payload.media_start == 0
assert payload.media_end == 0
assert payload.min_seek == 0
assert payload.max_seek == 0
assert len(payload.metadata) == 1
assert payload.metadata[0].name == 'title'
assert payload.metadata[0].value == ''
def test_text_acknowledge(packets, crypto):
unpacked = _unpack(packets['system_text_acknowledge'], crypto)
payload = unpacked.protected_payload
assert unpacked.header.flags.msg_type == enum.MessageType.SystemTextAck
assert payload.text_session_id == 8
assert payload.text_version_ack == 2
def test_text_configuration(packets, crypto):
unpacked = _unpack(packets['system_text_configuration'], crypto)
payload = unpacked.protected_payload
assert unpacked.header.flags.msg_type == enum.MessageType.SystemTextConfiguration
assert payload.text_session_id == 9
assert payload.text_buffer_version == 0
assert payload.text_options == enum.TextOption.AcceptsReturn | enum.TextOption.MultiLine
assert payload.input_scope == enum.TextInputScope.Unknown
assert payload.max_text_length == 0
assert payload.locale == 'de-DE'
assert payload.prompt == ''
def test_system_text_done(packets, crypto):
unpacked = _unpack(packets['system_text_done'], crypto)
payload = unpacked.protected_payload
assert unpacked.header.flags.msg_type == enum.MessageType.SystemTextDone
assert payload.text_session_id == 0
assert payload.text_version == 0
assert payload.flags == 0
assert payload.result == enum.TextResult.Cancel
def test_system_text_input(packets, crypto):
unpacked = _unpack(packets['system_text_input'], crypto)
payload = unpacked.protected_payload
assert unpacked.header.flags.msg_type == enum.MessageType.SystemTextInput
assert payload.text_session_id == 8
assert payload.base_version == 1
assert payload.submitted_version == 2
assert payload.total_text_byte_len == 1
assert payload.selection_start == -1
assert payload.selection_length == -1
assert payload.flags == 0
assert payload.text_chunk_byte_start == 0
assert payload.delta is None
assert payload.text_chunk == 'h'
def test_system_touch(packets, crypto):
unpacked = _unpack(packets['system_touch'], crypto)
payload = unpacked.protected_payload
assert unpacked.header.flags.msg_type == enum.MessageType.SystemTouch
assert payload.touch_msg_timestamp == 182459592
assert len(payload.touchpoints) == 1
assert payload.touchpoints[0].touchpoint_id == 1
assert payload.touchpoints[0].touchpoint_action == enum.TouchAction.Down
assert payload.touchpoints[0].touchpoint_x == 244
assert payload.touchpoints[0].touchpoint_y == 255
def test_repack_all(packets, crypto):
for f in packets:
unpacked = _unpack(packets[f], crypto)
# if unpacked.header.pkt_type in simple.pkt_types:
# msg = simple.struct(**unpacked)
# elif unpacked.header.pkt_type == enum.PacketType.Message and unpacked.header.flags.msg_type == enum.MessageType.Json:
# continue # The key order is not preserved when parsing JSON so the parsed message will always differ
# else:
# msg = message.struct(**unpacked)
repacked = _pack(unpacked, crypto)
assert repacked == packets[f], \
'%s was not repacked correctly:\n(repacked)%s\n!=\n(original)%s'\
% (f, hexlify(repacked), hexlify(packets[f]))
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,147 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/rest/schemas/auth.py | from typing import List
from pydantic import BaseModel
from xbox.webapi.authentication.manager import AuthenticationManager
from xbox.webapi.authentication.models import OAuth2TokenResponse, XSTSResponse
class AuthSessionConfig(BaseModel):
client_id: str
client_secret: str
redirect_uri: str
scopes: List[str]
class AuthenticationStatus(BaseModel):
oauth: OAuth2TokenResponse
xsts: XSTSResponse
session_config: AuthSessionConfig
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,148 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/rest/routes/web.py | from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, status
from ..deps import get_xbl_client
from xbox.webapi.api.client import XboxLiveClient
from xbox.webapi.api.provider.titlehub import TitleFields
from xbox.webapi.api.provider.titlehub import models as titlehub_models
from xbox.webapi.api.provider.lists import models as lists_models
router = APIRouter()
@router.get('/title/{title_id}', response_model=titlehub_models.Title)
async def download_title_info(
client: XboxLiveClient = Depends(get_xbl_client),
*,
title_id: int
):
if not client:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail='You have to login first')
try:
resp = await client.titlehub.get_title_info(title_id, [TitleFields.IMAGE])
return resp.titles[0]
except KeyError:
raise HTTPException(status_code=404, detail='Cannot find titles-node json response')
except IndexError:
raise HTTPException(status_code=404, detail='No info for requested title not found')
except Exception as e:
raise HTTPException(status_code=400, detail=f'Download of titleinfo failed, error: {e}')
@router.get('/titlehistory', response_model=titlehub_models.TitleHubResponse)
async def download_title_history(
client: XboxLiveClient = Depends(get_xbl_client),
max_items: Optional[int] = 5
):
if not client:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail='You have to login first')
try:
resp = await client.titlehub.get_title_history(client.xuid, max_items=max_items)
return resp
except Exception as e:
return HTTPException(status_code=400, detail=f'Download of titlehistory failed, error: {e}')
@router.get('/pins', response_model=lists_models.ListsResponse)
async def download_pins(
client: XboxLiveClient = Depends(get_xbl_client)
):
if not client:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail='You have to login first')
try:
resp = await client.lists.get_items(client.xuid)
return resp
except Exception as e:
return HTTPException(status_code=400, detail=f'Download of pins failed, error: {e}')
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,149 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/sg/crypto.py | """
Cryptography portion used for sending Smartglass message
Depending on the foreign public key type, the following Elliptic curves
can be used:
* Prime 256R1
* Prime 384R1
* Prime 521R1
1. On Discovery, the console responds with a DiscoveryResponse
including a certificate, this certificate holds the console's
`public key`.
2. The Client generates appropriate `elliptic curve` and derives the
`shared secret` using `console's public key`
3. The `shared secret` is salted via 2x hashes, see `kdf_salts`
4. The `salted shared secret` is hashed using `SHA-512`
5. The `salted & hashed shared secret` is split into the following
individual keys:
* bytes 0-16: Encryption key (AES 128-CBC)
* bytes 16-32: Initialization Vector key
* bytes 32-64: Hashing key (HMAC SHA-256)
6. The resulting `public key` from this :class:`Crypto` context is
sent with the ConnectRequest message to the console
"""
import os
import hmac
import hashlib
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
from xbox.sg.enum import PublicKeyType
from binascii import unhexlify
CURVE_MAP = {
PublicKeyType.EC_DH_P256: ec.SECP256R1,
PublicKeyType.EC_DH_P384: ec.SECP384R1,
PublicKeyType.EC_DH_P521: ec.SECP521R1
}
PUBLIC_KEY_TYPE_MAP = {v: k for k, v in CURVE_MAP.items()}
class SaltType(object):
"""
Define whether Salt is pre- or appended
"""
Prepend = 1
Append = 2
class Salt(object):
def __init__(self, value, salt_type=SaltType.Prepend):
"""
Handle salting of ECDH shared secret
Args:
value (bytes): Salting bytes
salt_type (:obj:`SaltType`): Salt Type
"""
self.value = value
self.type = salt_type
def apply(self, data):
"""
Appends or prepends salt bytes to data
Args:
data (bytes): Data to be salted
Returns:
bytes: Salted data
"""
if self.type == SaltType.Prepend:
return self.value + data
if self.type == SaltType.Append:
return data + self.value
raise ValueError("Unknown salt type: " + str(self.type))
class Crypto(object):
_backend = default_backend()
_kdf_salts = (
Salt(unhexlify('D637F1AAE2F0418C'), SaltType.Prepend),
Salt(unhexlify('A8F81A574E228AB7'), SaltType.Append)
)
def __init__(self, foreign_public_key, privkey=None, pubkey=None):
"""
Initialize Crypto context via the foreign public key of the console.
The public key is part of the console certificate.
Args:
foreign_public_key (:obj:`ec.EllipticCurvePublicKey`):
The console's public key
privkey (:obj:`ec.EllipticCurvePrivateKey`): Optional private key
pubkey (:obj:`ec.EllipticCurvePublicKey`): Optional public key
"""
if not isinstance(foreign_public_key, ec.EllipticCurvePublicKey):
raise ValueError("Unsupported public key format, \
expected EllipticCurvePublicKey")
if privkey and not isinstance(privkey, ec.EllipticCurvePrivateKey):
raise ValueError("Unsupported private key format, \
expected EllipticCurvePrivateKey")
elif not privkey:
privkey = ec.generate_private_key(
foreign_public_key.curve, self._backend
)
if pubkey and not isinstance(pubkey, ec.EllipticCurvePublicKey):
raise ValueError("Unsupported public key format, \
expected EllipticCurvePublicKey")
elif not pubkey:
self.pubkey = privkey.public_key()
else:
self.pubkey = pubkey
secret = privkey.exchange(ec.ECDH(), foreign_public_key)
salted_secret = secret
for salt in self._kdf_salts:
salted_secret = salt.apply(salted_secret)
self._expanded_secret = hashlib.sha512(salted_secret).digest()
self._encrypt_key = self._expanded_secret[:16]
self._iv_key = self._expanded_secret[16:32]
self._hash_key = self._expanded_secret[32:]
self._pubkey_type = PUBLIC_KEY_TYPE_MAP[type(self.pubkey.curve)]
self._pubkey_bytes = self.pubkey.public_bytes(
format=PublicFormat.UncompressedPoint,
encoding=Encoding.X962)[1:]
self._foreign_pubkey = foreign_public_key
@property
def shared_secret(self):
"""
Shared secret
Returns:
bytes: Shared secret
"""
return self._expanded_secret
@property
def pubkey_type(self):
"""
Public Key Type aka. keystrength
Returns:
:obj:`.PublicKeyType`: Public Key Type
"""
return self._pubkey_type
@property
def pubkey_bytes(self):
"""
Public Key Bytes (minus the first identifier byte!)
Returns:
bytes: Public key
"""
return self._pubkey_bytes
@property
def foreign_pubkey(self):
"""
Foreign key that was used to generate this crypto context
Returns:
:obj:`ec.EllipticCurvePublicKey`: Console's public key
"""
return self._foreign_pubkey
@classmethod
def from_bytes(cls, foreign_public_key, public_key_type=None):
"""
Initialize Crypto context with foreign public key in
bytes / hexstring format.
Args:
foreign_public_key (bytes): Console's public key
public_key_type (:obj:`.PublicKeyType`): Public Key Type
Returns:
:obj:`.Crypto`: Instance
"""
if not isinstance(foreign_public_key, bytes):
raise ValueError("Unsupported foreign public key format, \
expected bytes")
if public_key_type is None:
keylen = len(foreign_public_key)
if keylen == 0x41:
public_key_type = PublicKeyType.EC_DH_P256
elif keylen == 0x61:
public_key_type = PublicKeyType.EC_DH_P384
elif keylen == 0x85:
public_key_type = PublicKeyType.EC_DH_P521
else:
raise ValueError("Invalid public keylength")
curve = CURVE_MAP[public_key_type]
foreign_public_key = ec.EllipticCurvePublicKey.from_encoded_point(
curve(), foreign_public_key
)
return cls(foreign_public_key)
@classmethod
def from_shared_secret(cls, shared_secret):
"""
Set up crypto context with shared secret
Args:
shared_secret (bytes): The shared secret
Returns:
:obj:`.Crypto`: Instance
"""
if not isinstance(shared_secret, bytes):
raise ValueError("Unsupported shared secret format, \
expected bytes")
elif len(shared_secret) != 64:
raise ValueError("Unsupported shared secret length, \
expected 64 bytes")
# We need a dummy foreign key
dummy_key = unhexlify(
'041db1e7943878b28c773228ebdcfb05b985be4a386a55f50066231360785f61b'
'60038caf182d712d86c8a28a0e7e2733a0391b1169ef2905e4e21555b432b262d'
)
ctx = cls.from_bytes(dummy_key)
# Overwriting shared secret
ctx._encrypt_key = shared_secret[:16]
ctx._iv_key = shared_secret[16:32]
ctx._hash_key = shared_secret[32:]
return ctx
def generate_iv(self, seed=None):
"""
Generates an IV to be used in encryption/decryption
Args:
seed (bytes): An optional IV seed
Returns:
bytes: Initialization Vector
"""
if seed:
return self._encrypt(key=self._iv_key, iv=None, data=seed)
return os.urandom(16)
def encrypt(self, iv, plaintext):
"""
Encrypts plaintext with AES-128-CBC
No padding is added here, data has to be aligned to
block size (16 bytes).
Args:
iv (bytes): The IV to use. None where no IV is used.
plaintext (bytes): The plaintext to encrypt.
Returns:
bytes: Encrypted Data
"""
return Crypto._encrypt(self._encrypt_key, iv, plaintext)
def decrypt(self, iv, ciphertext):
"""
Decrypts ciphertext
No padding is removed here.
Args:
iv (bytes): The IV to use. None where no IV is used.
ciphertext (bytes): The hex representation of a ciphertext
to be decrypted
Returns:
bytes: Decrypted data
"""
return Crypto._decrypt(self._encrypt_key, iv, ciphertext)
def hash(self, data):
"""
Securely hashes data with HMAC SHA-256
Args:
data (bytes): The data to securely hash.
Returns:
bytes: Hashed data
"""
return Crypto._secure_hash(self._hash_key, data)
def verify(self, data, secure_hash):
"""
Verifies that the given data generates the given secure_hash
Args:
data (bytes): The data to validate.
secure_hash (bytes): The secure hash to validate against.
Returns:
bool: True on success, False otherwise
"""
return secure_hash == self.hash(data)
@staticmethod
def _secure_hash(key, data):
return hmac.new(key, data, hashlib.sha256).digest()
@staticmethod
def _encrypt(key, iv, data):
return Crypto._crypt(key=key, iv=iv, encrypt=True, data=data)
@staticmethod
def _decrypt(key, iv, data):
return Crypto._crypt(key=key, iv=iv, encrypt=False, data=data)
@staticmethod
def _crypt(key, iv, encrypt, data):
if not iv:
iv = b'\x00' * 16
cipher = Cipher(
algorithms.AES(key), modes.CBC(iv), backend=Crypto._backend
)
if encrypt:
cryptor = cipher.encryptor()
else:
cryptor = cipher.decryptor()
return cryptor.update(data) + cryptor.finalize()
class Padding(object):
"""
Padding base class.
"""
@staticmethod
def size(length, alignment):
"""
Calculate needed padding size.
Args:
length (int): Data size
alignment (int): Data alignment
Returns:
int: Padding size
"""
overlap = length % alignment
if overlap:
return alignment - overlap
else:
return 0
@staticmethod
def pad(payload, alignment):
"""
Abstract method to override
Args:
payload (bytes): Data blob
alignment (int): Data alignment
Returns:
bytes: Data with padding bytes
"""
raise NotImplementedError()
@staticmethod
def remove(payload):
"""
Common method for removing padding from data blob.
Args:
payload (bytes): Padded data.
Returns:
bytes: Data with padding bytes removed
"""
pad_count = payload[-1]
return payload[:-pad_count]
class PKCS7Padding(Padding):
@staticmethod
def pad(payload, alignment):
"""
Add PKCS#7 padding to data blob.
Args:
payload (bytes): Data blob
alignment (int): Data alignment
Returns:
bytes: Data with padding bytes
"""
size = Padding.size(len(payload), alignment)
if size == 0:
return payload
else:
return payload + (size * chr(size).encode())
class ANSIX923Padding(Padding):
@staticmethod
def pad(payload, alignment):
"""
Add ANSI.X923 padding to data blob.
Args:
payload (bytes): Data blob
alignment (int): Data alignment
Returns:
bytes: Data with padding bytes
"""
size = Padding.size(len(payload), alignment)
if size == 0:
return payload
else:
return payload + ((size - 1) * b'\x00') + chr(size).encode()
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,150 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/sg/enum.py | """
Smartglass enumerations
"""
from enum import Enum, Flag
class PacketType(Enum):
"""
Packet Types of core protocol:
Connect*, Discovery*, PowerOnRequest -> SimpleMessage
Message -> Message
"""
ConnectRequest = 0xCC00
ConnectResponse = 0xCC01
DiscoveryRequest = 0xDD00
DiscoveryResponse = 0xDD01
PowerOnRequest = 0xDD02
Message = 0xD00D
class ClientType(Enum):
"""
Client Type
Used in `DiscoveryRequest`, `DiscoveryResponse` and `LocalJoin`-Message.
"""
XboxOne = 0x1
Xbox360 = 0x2
WindowsDesktop = 0x3
WindowsStore = 0x4
WindowsPhone = 0x5
iPhone = 0x6
iPad = 0x7
Android = 0x8
class DeviceCapabilities(Flag):
"""
Bitmask for client device hardware capabilities
"""
Non = 0
Streaming = 1
Audio = 2
Accelerometer = 4
Compass = 8
Gyrometer = 16
Inclinometer = 32
Orientation = 64
All = 0xFFFFFFFFFFFFFFFF
class ConnectionResult(Enum):
"""
Connection Result
Used in result-field of `ConnectResponse` packet.
"""
Success = 0x0
Pending = 0x1
FailureUnknown = 0x2
FailureAnonymousConnectionsDisabled = 0x3
FailureDeviceLimitExceeded = 0x4
FailureSmartGlassDisabled = 0x5
FailureUserAuthFailed = 0x6
FailureUserSignInFailed = 0x7
FailureUserSignInTimeOut = 0x8
FailureUserSignInRequired = 0x9
class PublicKeyType(Enum):
"""
Public Key Type
Used in `ConnectRequest` packet.
"""
EC_DH_P256 = 0x00
EC_DH_P384 = 0x01
EC_DH_P521 = 0x02
Default = 0xFFFF
class AckStatus(Enum):
"""
Acknowledgement Status
Internally used to signalize the waiting
caller the status of acknowledgement.
"""
Pending = 0
Processed = 1
Rejected = 2
class ConnectionState(Enum):
"""
Connection State
Internally used by :obj:`.Console`
"""
Disconnected = 0x0
Connecting = 0x1
Connected = 0x2
Error = 0x3
Disconnecting = 0x4
Reconnecting = 0x5
class DeviceStatus(Enum):
"""
Device Status
Internally used by :obj:`.Console`
"""
DiscoveringAvailability = 0x1
Available = 0x2
Unavailable = 0x3
class PrimaryDeviceFlag(Flag):
"""
Primary Device Flag
Used in flags of `DiscoveryResponse` packet.
"""
Null = 0x0
AllowConsoleUsers = 0x1
AllowAuthenticatedUsers = 0x2
AllowAnonymousUsers = 0x4
CertificatePending = 0x8
class DisconnectReason(Enum):
"""
Disconnect Reason
Used in reason-field of `Disconnect`-Message.
"""
Unspecified = 0x0
Error = 0x1
PowerOff = 0x2
Maintenance = 0x3
AppClose = 0x4
SignOut = 0x5
Reboot = 0x6
Disabled = 0x7
LowPower = 0x8
class PairedIdentityState(Enum):
"""
Paired Identity State
Used in `ConnectResponse` and `PairedIdentityStateChanged`-Message.
"""
NotPaired = 0x0
Paired = 0x1
class ServiceChannel(Enum):
"""
Service Channels
Used internally to identify actual Channel Ids.
"""
Core = 0x0
SystemInput = 0x1
SystemInputTVRemote = 0x2
SystemMedia = 0x3
SystemText = 0x4
SystemBroadcast = 0x5
Ack = 0x6
Title = 0x7
class MessageType(Enum):
"""
Message Type
Used in `Message`-Header.
"""
Null = 0x0
Ack = 0x1
Group = 0x2
LocalJoin = 0x3
StopActivity = 0x5
AuxilaryStream = 0x19
ActiveSurfaceChange = 0x1a
Navigate = 0x1b
Json = 0x1c
Tunnel = 0x1d
ConsoleStatus = 0x1e
TitleTextConfiguration = 0x1f
TitleTextInput = 0x20
TitleTextSelection = 0x21
MirroringRequest = 0x22
TitleLaunch = 0x23
StartChannelRequest = 0x26
StartChannelResponse = 0x27
StopChannel = 0x28
System = 0x29
Disconnect = 0x2a
TitleTouch = 0x2e
Accelerometer = 0x2f
Gyrometer = 0x30
Inclinometer = 0x31
Compass = 0x32
Orientation = 0x33
PairedIdentityStateChanged = 0x36
Unsnap = 0x37
GameDvrRecord = 0x38
PowerOff = 0x39
MediaControllerRemoved = 0xf00
MediaCommand = 0xf01
MediaCommandResult = 0xf02
MediaState = 0xf03
Gamepad = 0xf0a
SystemTextConfiguration = 0xf2b
SystemTextInput = 0xf2c
SystemTouch = 0xf2e
SystemTextAck = 0xf34
SystemTextDone = 0xf35
class ActiveTitleLocation(Enum):
"""
Active Title Location
"""
Full = 0x0
Fill = 0x1
Snapped = 0x2
StartView = 0x3
SystemUI = 0x4
Default = 0x5
class ActiveSurfaceType(Enum):
"""
Active Surface Type
Used in `ActiveSurfaceType`-Message.
"""
Blank = 0x0
Direct = 0x1
HTML = 0x2
TitleTextEntry = 0x3
class MediaType(Enum):
"""
Media Type
Used in `MediaState`-Message.
"""
NoMedia = 0x0
Music = 0x1
Video = 0x2
Image = 0x3
Conversation = 0x4
Game = 0x5
class MediaTransportState(Enum):
"""
Media Transport State
Used in `MediaState`-Message.
"""
Invalid = 0x0
Stopped = 0x1
Starting = 0x2
Playing = 0x3
Paused = 0x4
Buffering = 0x5
class MediaPlaybackStatus(Enum):
"""
Media Playback Status
Used in `MediaState`-Message.
"""
Closed = 0x0
Changing = 0x1
Stopped = 0x2
Playing = 0x3
Paused = 0x4
class MediaControlCommand(Flag):
"""
Media Control Command
Used in `MediaCommand`-Message.
"""
Null = 0x0
Play = 0x2
Pause = 0x4
PlayPauseToggle = 0x8
Stop = 0x10
Record = 0x20
NextTrack = 0x40
PreviousTrack = 0x80
FastForward = 0x100
Rewind = 0x200
ChannelUp = 0x400
ChannelDown = 0x800
Back = 0x1000
View = 0x2000
Menu = 0x4000
Seek = 0x8000
class SoundLevel(Enum):
"""
Sound Level
Used in `MediaState`-Message.
"""
Muted = 0x0
Low = 0x1
Full = 0x2
class GamePadButton(Enum):
"""
Gamepad Button
Used in `Gamepad`-Message.
"""
Clear = 0x0
Enroll = 0x1
Nexu = 0x2
Menu = 0x4
View = 0x8
PadA = 0x10
PadB = 0x20
PadX = 0x40
PadY = 0x80
DPadUp = 0x100
DPadDown = 0x200
DPadLeft = 0x400
DPadRight = 0x800
LeftShoulder = 0x1000
RightShoulder = 0x2000
LeftThumbStick = 0x4000
RightThumbStick = 0x8000
class TouchAction(Enum):
"""
Touch Action
Used in `SystemTouch`/`TitleTouch`-Message.
"""
Null = 0x0
Down = 0x1
Move = 0x2
Up = 0x3
Cancel = 0x4
class TextInputScope(Enum):
"""
Text Input Scope
Used in `TextConfiguration`-Message
"""
Default = 0x0
Url = 0x1
FullFilePath = 0x2
FileName = 0x3
EmailUserName = 0x4
EmailSmtpAddress = 0x5
LogOnName = 0x6
PersonalFullName = 0x7
PersonalNamePrefix = 0x8
PersonalGivenName = 0x9
PersonalMiddleName = 0xa
PersonalSurname = 0xb
PersonalNameSuffix = 0xc
PostalAddress = 0xd
PostalCode = 0xe
AddressStreet = 0xf
AddressStateOrProvince = 0x10
AddressCity = 0x11
AddressCountryName = 0x12
AddressCountryShortName = 0x13
CurrencyAmountAndSymbol = 0x14
CurrencyAmount = 0x15
Date = 0x16
DateMonth = 0x17
DateDay = 0x18
DateYear = 0x19
DateMonthName = 0x1a
DateDayName = 0x1b
Digits = 0x1c
Number = 0x1d
OneChar = 0x1e
Password = 0x1f
TelephoneNumber = 0x20
TelephoneCountryCode = 0x21
TelephoneAreaCode = 0x22
TelephoneLocalNumber = 0x23
Time = 0x24
TimeHour = 0x25
TimeMinorSec = 0x26
NumberFullWidth = 0x27
AlphanumericHalfWidth = 0x28
AlphanumericFullWidth = 0x29
CurrencyChinese = 0x2a
Bopomofo = 0x2b
Hiragana = 0x2c
KatakanaHalfWidth = 0x2d
KatakanaFullWidth = 0x2e
Hanja = 0x2f
HangulHalfWidth = 0x30
HangulFullWidth = 0x31
Search = 0x32
SearchTitleText = 0x33
SearchIncremental = 0x34
ChineseHalfWidth = 0x35
ChineseFullWidth = 0x36
NativeScript = 0x37
Unknown = 0x39
class TextAction(Enum):
"""
Text Action
"""
Cancel = 0x0
Accept = 0x1
class TextOption(Flag):
"""
Text Option
"""
Default = 0x0
AcceptsReturn = 0x1
Password = 0x2
MultiLine = 0x4
SpellCheckEnabled = 0x8
PredictionEnabled = 0x10
RTL = 0x20
Dismiss = 0x4000
class TextResult(Enum):
"""
Text Result
"""
Cancel = 0x0
Accept = 0x1
Null = 0xFFFF
class HashAlgorithm(Enum):
"""
Hash Algorithm
Unused
"""
SHA256 = 0x0
SHA384 = 0x1
SHA512 = 0x2
class AsymmetricAlgorithm(Enum):
"""
Asymmetric Algorithm
Unused
"""
RSA_PKCS1_1024 = 0x0
RSA_OAEP_1024 = 0x1
RSA_PKCS1_2048 = 0x2
RSA_OAEP_2048 = 0x3
EC_DSA_P256 = 0x4
EC_DSA_P384 = 0x5
EC_DSA_P521 = 0x6
EC_DH_P256 = 0x7
EC_DH_P384 = 0x8
EC_DH_P521 = 0x9
class SymmetricAlgorithm(Enum):
"""
Symmetric Algorithm
Unused
"""
AES_CBC_128 = 0x0
AES_CBC_192 = 0x1
AES_CBC_256 = 0x2
class AuthError(Enum):
"""
Authentication Error
Unused
"""
Null = 0x0
DevModeNotAuthorized = 0x2
SystemUpdateRequired = 0x3
ContentUpdateRequired = 0x4
EnforcementBan = 0x5
ThirdPartyBan = 0x6
ParentalControlsBan = 0x7
SubscriptionNotActivated = 0x8
BillingMaintenanceRequired = 0x9
AccountNotCreated = 0xa
NewTermsOfUse = 0xb
CountryNotAuthorized = 0xc
AgeVerificationRequired = 0xd
Curfew = 0xe
ChildAccountNotInFamily = 0xf
CSVTransitionRequired = 0x10
AccountMaintenanceRequired = 0x11
AccountTypeNotAllowed = 0x12
ContentIsolation = 0x13
GamertagMustChange = 0x14
DeviceChallengeRequired = 0x15
SignInCountExceeded = 0x16
RetailAccountNotAllowed = 0x17
SandboxNotAllowed = 0x18
UnknownUser = 0x19
RetailContentNotAuthorized = 0x1a
ContentNotAuthorized = 0x1b
ExpiredDeviceToken = 0x1c
ExpiredTitleToken = 0x1d
ExpiredUserToken = 0x1e
InvalidDeviceToken = 0x1f
InvalidTitleToken = 0x20
InvalidUserToken = 0x21
InvalidRefreshToken = 0x22
class TokensResetReason(Enum):
"""
Tokens Reset Reason
Unused
"""
AuthTicketError = 0x0
AuthTicketChanged = 0x1
EnvironmentChanged = 0x2
SandboxIDChanged = 0x3
class HttpRequestMethod(Enum):
"""
HTTP Request Method
Unused
"""
GET = 0x0
POST = 0x1
class EnvironmentType(Enum):
"""
Environment Type
Unused
"""
Production = 0x0
DNet = 0x1
Mock = 0x2
Null = 0x3
class MetricsOrigin(Enum):
"""
Metrics Origin
Unused
"""
Core = 0x1
SDK = 0x2
Canvas = 0x3
App = 0x4
class SGResultCode(Enum):
"""
Smartglass Result Code
Unused
"""
SG_E_SUCCESS = 0x0
SG_E_ABORT = 0x80000004
SG_E_ACCESS_DENIED = 0x80000005
SG_E_FAIL = 0x80000006
SG_E_HANDLE = 0x80000007
SG_E_INVALID_ARG = 0x80000008
SG_E_NO_INTERFACE = 0x80000009
SG_E_NOT_IMPL = 0x8000000a
SG_E_OUT_OF_MEMORY = 0x8000000b
SG_E_POINTER = 0x8000000c
SG_E_UNEXPECTED = 0x8000000d
SG_E_PENDING = 0x8000000e
SG_E_INVALID_DATA = 0x8000000f
SG_E_CANCELED = 0x80000010
SG_E_INVALID_STATE = 0x80000011
SG_E_NOT_FOUND = 0x80000012
SG_E_NO_MORE_CAPACITY = 0x80000013
SG_E_FAILED_TO_START_THREAD = 0x80000014
SG_E_MESSAGE_EXPIRED = 0x80000015
SG_E_TIMED_OUT = 0x80000016
SG_E_NOT_INITIALIZED = 0x80000017
SG_E_JSON_LENGTH_EXCEEDED = 0x80000018
SG_E_MESSAGE_LENGTH_EXCEEDED = 0x80000019
SG_E_INVALID_CONFIGURATION = 0x8000001a
SG_E_EXPIRED_CONFIGURATION = 0x8000001b
SG_E_AUTH_REQUIRED = 0x8000001d
SG_E_TIMED_OUT_PRESENCE = 0x8000001e
SG_E_TIMED_OUT_CONNECT = 0x8000001f
SG_E_SOCKET_ERROR = 0x80010001
SG_E_HTTP_ERROR = 0x80020001
SG_E_CANCEL_SHUTDOWN = 0x80020002
SG_E_HTTP_STATUS = 0x80020003
SG_E_UNEXPECTED_CRYPTO_ERROR = 0x80030001
SG_E_INVALID_CRYPT_ARG = 0x80030002
SG_E_CRYPTO_INVALID_SIGNATURE = 0x80030003
SG_E_INVALID_CERTIFICATE = 0x80030004
SG_E_CHANNEL_REQUEST_UNKNOWN_ERROR = 0x80040105
SG_E_FAILED_TO_JOIN = 0x80060001
SG_E_ALREADY_CONNECTED = 0x80060002
SG_E_NOT_CONNECTED = 0x80060003
SG_E_CONSOLE_NOT_RESPONDING = 0x80060004
SG_E_CONSOLE_DISCONNECTING = 0x80060005
SG_E_BIG_ENDIAN_STREAM_STRING_NOT_TERMINATED = 0x80070001
SG_E_CHANNEL_ALREADY_STARTED = 0x80080001
SG_E_CHANNEL_FAILED_TO_START = 0x80080002
SG_E_MAXIMUM_CHANNELS_STARTED = 0x80080003
SG_E_JNI_CLASS_NOT_FOUND = 0x80090001
SG_E_JNI_METHOD_NOT_FOUND = 0x80090002
SG_E_JNI_RUNTIME_ERROR = 0x80090003
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,151 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /tests/test_crypto.py | import pytest
from binascii import unhexlify
from xbox.sg.enum import PublicKeyType
def test_generate_random_iv(crypto):
rand_iv = crypto.generate_iv()
rand_iv_2 = crypto.generate_iv()
assert len(rand_iv) == 16
assert len(rand_iv_2) == 16
assert rand_iv != rand_iv_2
def test_generate_seeded_iv(crypto):
seed = unhexlify('000102030405060708090A0B0C0D0E0F')
seed2 = unhexlify('000F0E0D0C0B0A090807060504030201')
seed_iv = crypto.generate_iv(seed)
seed_iv_dup = crypto.generate_iv(seed)
seed_iv_2 = crypto.generate_iv(seed2)
assert len(seed_iv) == 16
assert seed_iv == seed_iv_dup
assert seed_iv != seed_iv_2
def test_encrypt_decrypt(crypto):
plaintext = b'Test String\x00\x00\x00\x00\x00'
seed = unhexlify('000102030405060708090A0B0C0D0E0F')
seed_iv = crypto.generate_iv(seed)
encrypt = crypto.encrypt(seed_iv, plaintext)
decrypt = crypto.decrypt(seed_iv, encrypt)
assert plaintext == decrypt
assert plaintext != encrypt
def test_hash(crypto):
plaintext = b'Test String\x00\x00\x00\x00\x00'
seed = unhexlify('000102030405060708090A0B0C0D0E0F')
seed_iv = crypto.generate_iv(seed)
encrypt = crypto.encrypt(seed_iv, plaintext)
hash = crypto.hash(encrypt)
hash_dup = crypto.hash(encrypt)
verify = crypto.verify(encrypt, hash)
assert hash == hash_dup
assert verify is True
def test_from_bytes(public_key_bytes, public_key):
from xbox.sg.crypto import Crypto
c1 = Crypto.from_bytes(public_key_bytes)
c2 = Crypto.from_bytes(public_key_bytes, PublicKeyType.EC_DH_P256)
# invalid public key type passed
with pytest.raises(ValueError):
Crypto.from_bytes(public_key_bytes, PublicKeyType.EC_DH_P521)
# invalid keylength
with pytest.raises(ValueError):
Crypto.from_bytes(public_key_bytes[5:])
# invalid parameter
with pytest.raises(ValueError):
Crypto.from_bytes(123)
assert c1.foreign_pubkey.public_numbers() == public_key.public_numbers()
assert c2.foreign_pubkey.public_numbers() == public_key.public_numbers()
def test_from_shared_secret(shared_secret_bytes):
from xbox.sg.crypto import Crypto
c = Crypto.from_shared_secret(shared_secret_bytes)
# invalid length
with pytest.raises(ValueError):
c.from_shared_secret(shared_secret_bytes[1:])
# invalid parameter
with pytest.raises(ValueError):
c.from_shared_secret(123)
assert c._encrypt_key == unhexlify(b'82bba514e6d19521114940bd65121af2')
assert c._iv_key == unhexlify(b'34c53654a8e67add7710b3725db44f77')
assert c._hash_key == unhexlify(
b'30ed8e3da7015a09fe0f08e9bef3853c0506327eb77c9951769d923d863a2f5e'
)
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,152 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/handlers/tui.py | """
Terminal UI Smartglass Client
Supported functions: Poweron/off, launch title, gamepad input and entering text.
Additional shows console status (active titles, OS version, locale) and media state.
"""
import json
import urwid
import logging
import asyncio
from typing import List, Optional
from binascii import hexlify
from ..scripts import ExitCodes
from ..sg.console import Console
from ..sg.enum import DeviceStatus, GamePadButton, MediaPlaybackStatus
from ..sg.manager import InputManager, TextManager, MediaManager
from xbox.webapi.authentication.manager import AuthenticationManager
from construct.lib import containers
containers.setGlobalPrintFullStrings(True)
class ControllerRemote(urwid.Filler):
keymap = {
'tab': GamePadButton.View,
'<': GamePadButton.Menu,
'#': GamePadButton.Nexu,
'up': GamePadButton.DPadUp,
'down': GamePadButton.DPadDown,
'left': GamePadButton.DPadLeft,
'right': GamePadButton.DPadRight,
'a': GamePadButton.PadA,
'b': GamePadButton.PadB,
'x': GamePadButton.PadX,
'y': GamePadButton.PadY
}
text = 'Use keyboard to send controller input'
def __init__(self, app, console, original_widget):
self.app = app
self.console = console
super(ControllerRemote, self).__init__(original_widget, 'top')
def keypress(self, size, key):
if key in self.keymap:
button = self.keymap[key]
asyncio.create_task(self.console.gamepad_input(button))
asyncio.create_task(self.console.gamepad_input(GamePadButton.Clear))
elif key in ('q', 'Q'):
return key
else:
return super(ControllerRemote, self).keypress(size, key)
class QuestionBox(urwid.Filler):
def __init__(self, edit_widget, callback, **kwargs):
super(QuestionBox, self).__init__(edit_widget, **kwargs)
self.callback = callback
def keypress(self, size, key):
if key != 'enter':
return super(QuestionBox, self).keypress(size, key)
else:
self.callback(self.original_widget.edit_text)
class TextInput(urwid.Filler):
def __init__(self, app, edit_widget, console, **kwargs):
super(TextInput, self).__init__(edit_widget, **kwargs)
self.app = app
self.console = console
def keypress(self, size, key):
if key != 'enter':
ret = super(TextInput, self).keypress(size, key)
asyncio.create_task(self.console.send_systemtext_input(self.original_widget.edit_text))
return ret
else:
asyncio.create_task(self.console.finish_text_input())
self.app.return_to_details_menu()
class MediaProgressbar(urwid.ProgressBar):
def __init__(self, normal, complete):
super(MediaProgressbar, self).__init__(normal, complete)
self._current_text = 'No media playing'
def get_text(self):
return self._current_text
def update_from_state(self, state):
if not state or state.playback_status in (MediaPlaybackStatus.Stopped, MediaPlaybackStatus.Closed):
self._current_text = 'No media playing'
self.set_completion(0.0)
else:
pos_seconds = state.position / 10000000
total_seconds = state.media_end / 10000000
self._current_text = '{pmin:02d}:{psec:02d} / {tmin:02d}:{tsec:02d}'.format(
pmin=int(pos_seconds // 60),
psec=int(pos_seconds % 60),
tmin=int(total_seconds // 60),
tsec=int(total_seconds % 60)
)
if state.media_end > 0:
self.done = state.media_end
self.set_completion(state.position)
class ConsoleView(urwid.Frame):
def __init__(self, app, console, **kwargs):
self.app = app
self.console = console
self.device_info = urwid.LineBox(urwid.Text('Not available'), 'Device info')
self.status = urwid.LineBox(urwid.Text('Not available'), 'Console status')
self.media_text = urwid.Text('Not available')
self.media_progress = MediaProgressbar('pg normal', 'pg complete')
media_state_pile = urwid.Pile([self.media_text, self.media_progress])
self.media_state = urwid.LineBox(media_state_pile, 'Media State')
self.pile = urwid.Pile([self.device_info, self.status, self.media_state])
self.filler = urwid.Filler(self.pile, valign='top')
self.update_device_info()
self.console.on_timeout += self.update_device_info
self.console.on_pairing_state += lambda _: self.update_device_info()
self.console.on_connection_state += lambda _: self.update_device_info()
self.console.on_active_surface += lambda _: self.update_device_info()
self.console.on_console_status += self.on_console_status
self.console.media.on_media_state += self.on_media_state
self.console.text.on_systemtext_configuration += lambda _: self.app.view_text_input_overlay(self.console)
self.console.text.on_systemtext_input += lambda _: None # Update text overlay with input text
self.console.text.on_systemtext_done += lambda _: self.app.return_to_details_menu()
super(ConsoleView, self).__init__(self.filler, **kwargs)
def update_device_info(self):
text = 'Name: {c.name:<15}\nAddress: {c.address:<15}\nLiveID: {c.liveid:<15}\n' \
'UUID: {c.uuid}\n\n'.format(c=self.console)
text += 'Connection State: {:<15}\n'.format(self.console.connection_state.name)
text += 'Pairing State: {:<15}\n'.format(self.console.pairing_state.name)
# text += 'Active Surface: {}\n'.format(ActiveSurfaceType[self.console.active_surface.surface_type])
text += 'Shared secret: {hex_secret}'.format(
hex_secret=hexlify(self.console._crypto.shared_secret).decode('utf-8')
)
self.device_info.original_widget.set_text(text)
def on_console_status(self, console_status):
if not console_status:
self.status.original_widget.set_text('Not available')
return
text = \
'LiveTV Provider: {status.live_tv_provider:<10}' \
'Locale: {status.locale:<10}' \
'OS: {status.major_version}.{status.minor_version}.{status.build_number}\n'.format(
status=console_status
)
for title in console_status.active_titles:
text += '{focus} {title.aum} (0x{title.title_id:08x}) [{location}]\n'.format(
focus='*' if title.disposition.has_focus else ' ',
title=title, location=title.disposition.title_location.name
)
self.status.original_widget.set_text(text)
def on_media_state(self, state):
if not state:
self.media_text.set_text('Not available')
self.media_progress.update_from_state(state)
return
text = \
'Title: {state.aum_id:<20} (0x{state.title_id:08x}) AssetId: {state.asset_id:<25}\n' \
'MediaType: {media_type:<25} SoundLevel: {sound_level:<25}\n' \
'Playback: {playback_status:<25}\n'.format(
state=state, media_type=state.media_type.name, sound_level=state.sound_level.name,
playback_status=state.playback_status.name
)
for metadata in state.metadata:
text += '{metadata.name}: {metadata.value}\n'.format(metadata=metadata)
if state.playback_status in (MediaPlaybackStatus.Stopped, MediaPlaybackStatus.Closed):
self.media_text.set_text('Not available')
else:
self.media_text.set_text(text)
self.media_progress.update_from_state(state)
def keypress(self, size, key):
if key in ('c', 'C'):
self.app.view_commands_menu(self.console)
else:
return super(ConsoleView, self).keypress(size, key)
class ConsoleButton(urwid.Button):
focus_map = {
None: 'selected',
'connected': 'connected selected'
}
def __init__(self, app, console):
super(ConsoleButton, self).__init__('')
self.app = app
self.console = console
self.console.add_manager(InputManager)
self.console.add_manager(MediaManager)
self.console.add_manager(TextManager)
self.console.on_connection_state += lambda _: self.refresh()
self.console.on_console_status += lambda _: self.refresh()
self.console.on_device_status += lambda _: self.refresh()
urwid.connect_signal(self, 'click', self.callback)
self.textwidget = urwid.AttrWrap(urwid.SelectableIcon('', cursor_position=0), None)
self._w = urwid.AttrMap(self.textwidget, None, self.focus_map)
self.refresh()
def callback(self, *args):
asyncio.create_task(self.cb_connect())
async def cb_connect(self):
if await self.connect():
self.app.view_details_menu(self.console)
async def connect(self):
if self.console.connected:
return True
if not self.console.available:
self.app.view_msgbox('Console unavailable, try refreshing')
return False
userhash = ''
xsts_token = ''
if self.app.auth_mgr:
userhash = self.app.auth_mgr.xsts_token.userhash
xsts_token = self.app.auth_mgr.xsts_token.token
state = await self.console.connect(
userhash=userhash,
xsts_token=xsts_token
)
if not self.console.connected:
self.app.view_msgbox('Connection failed! State: {}'.format(state))
return False
return True
async def disconnect(self):
if self.console.connected:
await self.console.disconnect()
def refresh(self):
text = ' {c.name:<20}{c.address:<20}{c.liveid:<20}{ds:<20}'.format(
c=self.console,
ds=f'{self.console.device_status.name}, {self.console.connection_state.name}'
)
self.textwidget.set_text(text)
if self.console.connected:
self.textwidget.set_attr('connected')
else:
self.textwidget.set_attr(None)
def keypress(self, size, key):
if key in ('p', 'P'):
asyncio.create_task(self.console.power_on())
elif key in ('c', 'C'):
asyncio.create_task(self.connect())
elif key in ('d', 'D'):
asyncio.create_task(self.disconnect())
else:
return super(ConsoleButton, self).keypress(size, key)
class ConsoleList(urwid.Frame):
def __init__(self, app, consoles, header, footer):
walker = urwid.SimpleFocusListWalker([])
listbox = urwid.ListBox(walker)
frame = urwid.Frame(listbox, header=urwid.Text(' {0:<20}{1:<20}{2:<20}{3:<20}'.format(
'Name', 'IP Address', 'Live ID', 'Status'
)))
view = urwid.LineBox(frame, 'Consoles')
self.walker = walker
self.app = app
self.consoles = consoles
super(ConsoleList, self).__init__(view, header=header, footer=footer)
self.walker[:] = [ConsoleButton(self.app, c) for c in self.consoles]
async def refresh(self):
await self._refresh()
async def _refresh(self):
discovered = await Console.discover(blocking=True)
liveids = [d.liveid for d in discovered]
for i, c in enumerate(self.consoles):
if c.liveid in liveids:
# Refresh existing entries
idx = liveids.index(c.liveid)
if c.device_status != discovered[idx].device_status:
self.consoles[i] = discovered[idx]
del discovered[idx]
del liveids[idx]
elif c.liveid not in liveids:
# Set unresponsive consoles to Unavailable
self.consoles[i].device_status = DeviceStatus.Unavailable
# Add newly discovered consoles
self.consoles.extend(discovered)
# Update the consolelist view
self.walker[:] = [ConsoleButton(self.app, c) for c in self.consoles]
def keypress(self, size, key):
if key in ('r', 'R'):
asyncio.create_task(self.refresh())
else:
return super(ConsoleList, self).keypress(size, key)
class CommandList(urwid.SimpleFocusListWalker):
def __init__(self, app, console):
commands = [
('Launch title', self._launch_title),
('Controller remote', self._controller_remote),
('Disconnect', self._disconnect),
('Power off', self._power_off)
]
self.app = app
self.console = console
super(CommandList, self).__init__([CommandButton(text, func) for text, func in commands])
def _launch_title(self):
self.app.view_launch_title_textbox(self.__launch_title)
def __launch_title(self, uri):
asyncio.create_task(self.console.launch_title(uri))
self.app.return_to_details_menu()
def _controller_remote(self):
self.app.view_controller_remote_overlay(self.console)
def _disconnect(self):
asyncio.create_task(self.console.disconnect())
self.app.return_to_main_menu()
def _power_off(self):
asyncio.create_task(self.console.power_off())
self.app.return_to_main_menu()
class CommandButton(urwid.Button):
focus_map = {
None: 'selected',
}
def __init__(self, text, func):
super(CommandButton, self).__init__('')
urwid.connect_signal(self, 'click', self.callback)
self.text = text
self.func = func
self.textwidget = urwid.AttrWrap(urwid.SelectableIcon(' {}'.format(self.text), cursor_position=0), None)
self._w = urwid.AttrMap(self.textwidget, None, self.focus_map)
def callback(self, *args):
self.func()
class UrwidLogHandler(logging.Handler):
def __init__(self, callback):
super(UrwidLogHandler, self).__init__()
self.callback = callback
def emit(self, record):
try:
self.callback(record)
except Exception:
self.handleError(record)
class LogListBox(urwid.ListBox):
def __init__(self, app, size=10000):
self.app = app
self.size = size
self.entries = urwid.SimpleFocusListWalker([])
self.handler = UrwidLogHandler(self._log_callback)
self.handler.setFormatter(app.log_fmt)
logging.root.addHandler(self.handler)
logging.root.setLevel(app.log_level)
super(LogListBox, self).__init__(self.entries)
def _log_callback(self, record):
self.entries.append(LogButton(self.app, self.handler.format(record), record))
if self.focus_position == len(self.entries) - 2:
self.focus_position += 1
if len(self.entries) > self.size:
self.entries[:] = self.entries[len(self.entries) - self.size:]
def keypress(self, size, key):
# Prevents opening the log window multiple times
if key in ('l', 'L'):
pass
else:
return super(LogListBox, self).keypress(size, key)
class LogButton(urwid.Button):
focus_map = {
None: 'selected',
}
def __init__(self, app, text, record):
super(LogButton, self).__init__('')
self.app = app
self.text = text
self.record = record
urwid.connect_signal(self, 'click', self._click)
self.textwidget = urwid.AttrWrap(urwid.SelectableIcon(' {}'.format(self.text), cursor_position=0), None)
self._w = urwid.AttrMap(self.textwidget, None, self.focus_map)
def _click(self, *args):
if hasattr(self.record, '_msg'):
self.app.view_scrollable_overlay(repr(self.record._msg), "Message details", width=80)
class SGDisplay(object):
palette = [
('header', 'yellow', 'dark blue', 'standout'),
('listbar', 'light cyan,bold', 'default'),
('selected', 'black', 'light gray'),
# footer
('foot', 'dark cyan', 'dark blue', 'bold'),
('key', 'light cyan', 'dark blue', 'underline'),
# status
('connected', 'dark green', ''),
('connected selected', 'black', 'dark green'),
# progressbar
('pg normal', 'white', 'black', 'standout'),
('pg complete', 'white', 'dark magenta'),
('pg smooth', 'dark magenta', 'black'),
('caption', 'yellow,bold', 'dark cyan'),
('prompt', 'white', 'dark cyan'),
('dialog', 'white', 'dark cyan'),
('button', 'white', 'dark cyan'),
('button selected', 'white', 'dark cyan'),
]
header_text = ('header', [
"Xbox Smartglass"
])
footer_main_text = ('foot', [
('key', 'R:'), "reload ",
('key', 'C:'), "connect ",
('key', 'D:'), "disconnect ",
('key', 'P:'), "poweron ",
('key', 'L:'), "view log ",
('key', 'Q:'), "quit "
])
footer_console_text = ('foot', [
('key', 'C:'), "commands ",
('key', 'L:'), "view log ",
('key', 'Q:'), "quit "
])
footer_log_text = ('foot', [
('key', 'ENTER:'), "show details ",
('key', 'Q:'), "quit "
])
log_fmt = logging.Formatter(logging.BASIC_FORMAT)
log_level = logging.DEBUG
def __init__(self, consoles: List[Console], auth_mgr: AuthenticationManager):
self.header = urwid.AttrMap(urwid.Text(self.header_text), 'header')
footer = urwid.AttrMap(urwid.Text(self.footer_main_text), 'foot')
self.running = False
self.loop = None
self.consoles = ConsoleList(self, consoles, self.header, footer)
self.auth_mgr = auth_mgr
self.log = LogListBox(self)
self.view_stack = []
def push_view(self, sender, view):
self.view_stack.append(view)
self.loop.widget = view
self.loop.draw_screen()
def pop_view(self, sender):
if len(self.view_stack) > 1:
top_widget = self.view_stack.pop()
if hasattr(top_widget, 'close_view'):
top_widget.close_view(sender)
self.loop.widget = self.view_stack[-1]
self.loop.draw_screen()
else:
self.do_quit()
def view_main_menu(self):
self.push_view(self, self.consoles)
def view_details_menu(self, console):
footer = urwid.AttrMap(urwid.Text(self.footer_console_text), 'foot')
frame = ConsoleView(self, console, header=self.header, footer=footer)
self.push_view(self, frame)
def view_commands_menu(self, console):
bottom = self.view_stack[-1]
commands = urwid.ListBox(CommandList(self, console))
top = urwid.LineBox(commands, 'Commands')
overlay = urwid.Overlay(top, bottom, 'center', ('relative', 25), 'middle', ('relative', 75))
self.push_view(self, overlay)
def view_controller_remote_overlay(self, console):
self.return_to_details_menu()
bottom = self.view_stack[-1]
edit = urwid.Edit('Press Q to quit\n'
'View: <tab>, Menu: <, Nexus: #\n'
'DPad: <Arrow keys>, Button: A-B-X-Y\n')
view = ControllerRemote(self, console, edit)
top = urwid.LineBox(view, title='Controller Remote')
overlay = urwid.Overlay(top, bottom,
'center', ('relative', 25), 'middle', ('relative', 25))
self.push_view(self, overlay)
def view_text_input_overlay(self, console):
self.return_to_details_menu()
bottom = self.view_stack[-1]
edit = urwid.Edit('Enter text\n'
'Press ENTER to send\n')
view = TextInput(self, edit, console)
top = urwid.LineBox(view, title='SystemText Session')
overlay = urwid.Overlay(top, bottom,
'center', ('relative', 25), 'middle', ('relative', 25))
self.push_view(self, overlay)
def view_launch_title_textbox(self, callback):
self.return_to_details_menu()
bottom = self.view_stack[-1]
edit = urwid.Edit('Press ENTER to send uri\n')
question_box = QuestionBox(edit, callback)
top = urwid.LineBox(question_box, title='Enter launch uri')
overlay = urwid.Overlay(top, bottom,
'center', ('relative', 25), 'middle', ('relative', 25))
self.push_view(self, overlay)
def view_msgbox(self, msg, title='Error', width=25, height=75):
bottom = self.view_stack[-1]
text = urwid.Text(msg)
button = urwid.Button('OK')
button._label.align = 'center'
pad_button = urwid.Padding(button, 'center', ('relative', width * 2))
pile = urwid.Pile([text, pad_button])
box = urwid.LineBox(pile, title)
top = urwid.Filler(box, 'top')
overlay = urwid.Overlay(top, bottom, 'center', ('relative', width), 'middle', ('relative', height))
urwid.connect_signal(button, 'click', lambda _: self.pop_view(self))
self.push_view(self, overlay)
def view_scrollable_overlay(self, msg, title='Error', width=25, height=75):
bottom = self.view_stack[-1]
walker = urwid.SimpleFocusListWalker([urwid.Text(l) for l in msg.split('\n')])
text = urwid.ListBox(walker)
line = urwid.LineBox(text, title)
overlay = urwid.Overlay(line, bottom, 'center', ('relative', width), 'middle', ('relative', height))
self.push_view(self, overlay)
def view_log(self):
header = urwid.AttrMap(urwid.Text(self.header_text), 'header')
footer = urwid.AttrMap(urwid.Text(self.footer_log_text), 'foot')
frame = urwid.Frame(self.log, header=header, footer=footer)
self.push_view(self, frame)
def return_to_main_menu(self):
while len(self.view_stack) > 1:
self.pop_view(self)
def return_to_details_menu(self):
while len(self.view_stack) > 2:
self.pop_view(self)
def do_quit(self):
self.running = False
self.loop.stop()
async def run(self, loop):
eventloop = urwid.AsyncioEventLoop(loop=loop)
self.loop = urwid.MainLoop(
urwid.SolidFill('xq'),
handle_mouse=False,
palette=self.palette,
unhandled_input=self.unhandled_input,
event_loop=eventloop
)
self.loop.set_alarm_in(0.0001, lambda *args: self.view_main_menu())
self.loop.start()
self.running = True
await self.consoles.refresh()
while self.running:
await asyncio.sleep(1000)
def unhandled_input(self, input):
if input in ('q', 'Q', 'esc'):
self.pop_view(self)
elif input in ('l', 'L'):
self.view_log()
def load_consoles(filepath: str) -> List[Console]:
try:
with open(filepath, 'r') as fh:
consoles = json.load(fh)
return [Console.from_dict(c) for c in consoles]
except FileNotFoundError:
return []
def save_consoles(filepath: str, consoles: List[Console]) -> None:
consoles = [c.to_dict() for c in consoles]
with open(filepath, 'w') as fh:
json.dump(consoles, fh, indent=2)
async def run_tui(
loop: asyncio.AbstractEventLoop,
consoles_filepath: str,
auth_mgr: Optional[AuthenticationManager] = None
) -> int:
"""
Main entrypoint for TUI
Args:
loop: Eventloop
consoles_filepath: Console json filepath
auth_mgr: Authentication manager
Returns: Exit code
"""
consoles = load_consoles(consoles_filepath) if consoles_filepath else []
app = SGDisplay(consoles, auth_mgr)
await app.run(loop)
if consoles_filepath:
save_consoles(consoles_filepath, app.consoles.consoles)
return ExitCodes.OK | {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,153 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /xbox/rest/routes/device.py | import logging
from typing import Optional, List
from fastapi import APIRouter, Depends, HTTPException
from .. import schemas, singletons
from ..deps import console_exists, console_connected, get_xbl_client, get_authorization
from ..consolewrap import ConsoleWrap
from xbox.webapi.api.client import XboxLiveClient
from xbox.webapi.api.provider.titlehub import TitleFields
from xbox.sg import enum
from xbox.stump import json_model as stump_schemas
logger = logging.getLogger(__name__)
router = APIRouter()
@router.get('/', response_model=List[schemas.DeviceStatusResponse])
async def device_overview(addr: Optional[str] = None):
discovered = await ConsoleWrap.discover(addr=addr)
discovered = discovered.copy()
liveids = [d.liveid for d in discovered]
for i, c in enumerate(singletons.console_cache.values()):
if c.liveid in liveids:
# Refresh existing entries
index = liveids.index(c.liveid)
if c.device_status != discovered[index].device_status:
singletons.console_cache[c.liveid] = ConsoleWrap(discovered[index])
del discovered[index]
del liveids[index]
elif c.liveid not in liveids:
# Set unresponsive consoles to Unavailable
singletons.console_cache[c.liveid].console.device_status = enum.DeviceStatus.Unavailable
# Extend by new entries
for d in discovered:
singletons.console_cache.update({d.liveid: ConsoleWrap(d)})
# Filter for specific console when ip address query is supplied (if available)
consoles = [console.status for console in singletons.console_cache.values()
if (addr and console.status.ip_address == addr) or not addr]
return consoles
@router.get('/{liveid}/poweron', response_model=schemas.GeneralResponse)
async def poweron(liveid: str, addr: Optional[str] = None):
await ConsoleWrap.power_on(liveid, addr=addr)
return schemas.GeneralResponse(success=True)
"""
Require enumerated console
"""
@router.get('/{liveid}', response_model=schemas.DeviceStatusResponse)
def device_info(
console: ConsoleWrap = Depends(console_exists)
):
return console.status
@router.get('/{liveid}/connect', response_model=schemas.GeneralResponse)
async def force_connect(
console: ConsoleWrap = Depends(console_exists),
authentication_data: schemas.AuthenticationStatus = Depends(get_authorization)
):
try:
userhash = ''
xtoken = ''
if authentication_data:
userhash = authentication_data.xsts.userhash
xtoken = authentication_data.xsts.token
state = await console.connect(userhash, xtoken)
except Exception as e:
raise
if state != enum.ConnectionState.Connected:
raise HTTPException(status_code=400, detail='Connection failed')
return schemas.GeneralResponse(success=True, details={'connection_state': state.name})
"""
Require connected console
"""
@router.get('/{liveid}/disconnect', response_model=schemas.GeneralResponse)
async def disconnect(
console: ConsoleWrap = Depends(console_connected)
):
await console.disconnect()
return schemas.GeneralResponse(success=True)
@router.get('/{liveid}/poweroff', response_model=schemas.GeneralResponse)
async def poweroff(
console: ConsoleWrap = Depends(console_connected)
):
if not await console.power_off():
raise HTTPException(status_code=400, detail='Failed to power off')
return schemas.GeneralResponse(success=True)
@router.get('/{liveid}/console_status', response_model=schemas.ConsoleStatusResponse)
async def console_status(
console: ConsoleWrap = Depends(console_connected),
xbl_client: XboxLiveClient = Depends(get_xbl_client)
):
status = console.console_status
# Update Title Info, if authorization data is available
if xbl_client and status:
for t in status.active_titles:
try:
title_id = t.title_id
resp = singletons.title_cache.get(title_id)
if not resp:
resp = await xbl_client.titlehub.get_title_info(title_id, [TitleFields.IMAGE])
if resp.titles[0]:
singletons.title_cache[title_id] = resp
t.name = resp.titles[0].name
t.image = resp.titles[0].display_image
t.type = resp.titles[0].type
except Exception as e:
logger.exception(f'Failed to download title metadata for AUM: {t.aum}', exc_info=e)
return status
@router.get('/{liveid}/launch/{app_id}', response_model=schemas.GeneralResponse, deprecated=True)
async def launch_title(
console: ConsoleWrap = Depends(console_connected),
*,
app_id: str
):
await console.launch_title(app_id)
return schemas.GeneralResponse(success=True, details={'launched': app_id})
@router.get('/{liveid}/media_status', response_model=schemas.MediaStateResponse)
def media_status(
console: ConsoleWrap = Depends(console_connected)
):
return console.media_status
@router.get('/{liveid}/ir', response_model=schemas.InfraredResponse)
async def infrared(
console: ConsoleWrap = Depends(console_connected)
):
stump_config = await console.get_stump_config()
devices = {}
for device_config in stump_config.params:
button_links = {}
for button in device_config.buttons:
button_links[button] = schemas.InfraredButton(
url=f'/device/{console.liveid}/ir/{device_config.device_id}/{button}',
value=device_config.buttons[button]
)
devices[device_config.device_type] = schemas.InfraredDevice(
device_type=device_config.device_type,
device_brand=device_config.device_brand,
device_model=device_config.device_model,
device_name=device_config.device_name,
device_id=device_config.device_id,
buttons=button_links
)
return schemas.InfraredResponse(__root__=devices)
@router.get('/{liveid}/ir/{device_id}', response_model=schemas.InfraredDevice)
async def infrared_available_keys(
console: ConsoleWrap = Depends(console_connected),
*,
device_id: str
):
stump_config = await console.get_stump_config()
for device_config in stump_config.params:
if device_config.device_id != device_id:
continue
button_links = {}
for button in device_config.buttons:
button_links[button] = schemas.InfraredButton(
url=f'/device/{console.liveid}/ir/{device_config.device_id}/{button}',
value=device_config.buttons[button]
)
return schemas.InfraredDevice(
device_type=device_config.device_type,
device_brand=device_config.device_brand,
device_model=device_config.device_model,
device_name=device_config.device_name,
device_id=device_config.device_id,
buttons=button_links
)
raise HTTPException(status_code=400, detail=f'Device Id \'{device_id}\' not found')
@router.get('/{liveid}/ir/{device_id}/{button}', response_model=schemas.GeneralResponse)
async def infrared_send(
console: ConsoleWrap = Depends(console_connected),
*,
device_id: str,
button: str
):
if not await console.send_stump_key(device_id, button):
raise HTTPException(status_code=400, detail='Failed to send button')
return schemas.GeneralResponse(success=True, details={'sent_key': button, 'device_id': device_id})
@router.get('/{liveid}/media', response_model=schemas.MediaCommandsResponse)
def media_overview(
console: ConsoleWrap = Depends(console_connected)
):
return schemas.MediaCommandsResponse(commands=list(console.media_commands.keys()))
@router.get('/{liveid}/media/{command}', response_model=schemas.GeneralResponse)
async def media_command(
console: ConsoleWrap = Depends(console_connected),
*,
command: str,
seek_position: Optional[int] = None
):
cmd = console.media_commands.get(command)
if not cmd:
raise HTTPException(status_code=400, detail=f'Invalid command passed, command: {command}')
elif cmd == enum.MediaControlCommand.Seek and seek_position is None:
raise HTTPException(status_code=400, detail=f'Seek command requires seek_position argument')
await console.send_media_command(cmd, seek_position=seek_position)
return schemas.GeneralResponse(success=True)
@router.get('/{liveid}/input', response_model=schemas.InputResponse)
def input_overview(
console: ConsoleWrap = Depends(console_connected)
):
return schemas.InputResponse(buttons=list(console.input_keys.keys()))
@router.get('/{liveid}/input/{button}', response_model=schemas.GeneralResponse)
async def input_send_button(
console: ConsoleWrap = Depends(console_connected),
*,
button: str
):
btn = console.input_keys.get(button)
if not btn:
raise HTTPException(status_code=400, detail=f'Invalid button passed, button: {button}')
await console.send_gamepad_button(btn)
return schemas.GeneralResponse(success=True)
@router.get('/{liveid}/stump/headend', response_model=stump_schemas.HeadendInfo)
async def stump_headend_info(
console: ConsoleWrap = Depends(console_connected)
):
return await console.get_headend_info()
@router.get('/{liveid}/stump/livetv', response_model=stump_schemas.LiveTvInfo)
async def stump_livetv_info(
console: ConsoleWrap = Depends(console_connected)
):
return await console.get_livetv_info()
@router.get('/{liveid}/stump/tuner_lineups', response_model=stump_schemas.TunerLineups)
async def stump_tuner_lineups(
console: ConsoleWrap = Depends(console_connected)
):
return await console.get_tuner_lineups()
@router.get('/{liveid}/text', response_model=schemas.device.TextSessionActiveResponse)
def text_overview(
console: ConsoleWrap = Depends(console_connected)
):
return schemas.TextSessionActiveResponse(text_session_active=console.text_active)
@router.get('/{liveid}/text/{text}', response_model=schemas.GeneralResponse)
async def text_send(
console: ConsoleWrap = Depends(console_connected),
*,
text: str
):
await console.send_text(text)
return schemas.GeneralResponse(success=True)
@router.get('/{liveid}/gamedvr', response_model=schemas.GeneralResponse)
async def gamedvr_record(
console: ConsoleWrap = Depends(console_connected),
start: Optional[int] = -60,
end: Optional[int] = 0
):
"""
Default to record last 60 seconds
Adjust with start/end query parameter
(delta time in seconds)
"""
try:
await console.dvr_record(start, end)
except Exception as e:
raise HTTPException(status_code=400, detail=f'GameDVR failed, error: {e}')
return schemas.GeneralResponse(success=True)
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,154 | OpenXbox/xbox-smartglass-core-python | refs/heads/master | /tests/test_protocol.py | import pytest
from xbox.sg.protocol import _fragment_connect_request, FragmentError
from xbox.sg.protocol import ChannelManager, ChannelError
from xbox.sg.protocol import SequenceManager
from xbox.sg.protocol import FragmentManager
def test_fragment_connect_request(crypto):
from uuid import UUID
from xbox.sg.enum import PublicKeyType
uuid = UUID('de305d54-75b4-431b-adb2-eb6b9e546014')
pubkey = 64 * b'\xFF'
userhash = '0123456789'
auth_token = (898 * 'A') + (500 * 'B')
fragments = _fragment_connect_request(crypto, uuid, PublicKeyType.EC_DH_P256,
pubkey, userhash, auth_token)
# request_num != 0
fragments_dup = _fragment_connect_request(crypto, uuid, PublicKeyType.EC_DH_P256,
pubkey, userhash, auth_token,
request_num=3)
# Total length (userhash + token) is too small for fragmentation
with pytest.raises(FragmentError):
_fragment_connect_request(crypto, uuid, PublicKeyType.EC_DH_P256,
pubkey, userhash, 898 * 'A')
assert len(fragments) == 2
assert fragments[0].unprotected_payload.sg_uuid == uuid
assert fragments[0].unprotected_payload.public_key == pubkey
assert isinstance(fragments[0].unprotected_payload.iv, bytes) is True
assert fragments[0].protected_payload.userhash == userhash
assert fragments[0].protected_payload.jwt == 898 * 'A'
assert fragments[0].protected_payload.connect_request_num == 0
assert fragments[0].protected_payload.connect_request_group_start == 0
assert fragments[0].protected_payload.connect_request_group_end == 2
assert fragments[1].unprotected_payload.sg_uuid == uuid
assert fragments[1].unprotected_payload.public_key == pubkey
assert isinstance(fragments[1].unprotected_payload.iv, bytes) is True
assert fragments[1].protected_payload.userhash == ''
assert fragments[1].protected_payload.jwt == 500 * 'B'
assert fragments[1].protected_payload.connect_request_num == 1
assert fragments[1].protected_payload.connect_request_group_start == 0
assert fragments[1].protected_payload.connect_request_group_end == 2
assert fragments_dup[0].protected_payload.connect_request_num == 3
assert fragments_dup[0].protected_payload.connect_request_group_start == 3
assert fragments_dup[0].protected_payload.connect_request_group_end == 5
assert fragments_dup[1].protected_payload.connect_request_num == 4
assert fragments_dup[1].protected_payload.connect_request_group_start == 3
assert fragments_dup[1].protected_payload.connect_request_group_end == 5
def test_sequence_manager():
mgr = SequenceManager()
seq_num = 0
for i in range(5):
seq_num = mgr.next_sequence_num()
for i in range(1, 23):
mgr.add_received(i)
for i in range(1, 12):
mgr.add_processed(i)
for i in range(1, 7):
mgr.add_rejected(i)
# Trying to set already existing values
mgr.add_received(4)
mgr.add_processed(5)
mgr.add_rejected(6)
mgr.low_watermark = 89
# Setting smaller sequence than already set
mgr.low_watermark = 12
assert mgr.received == list(range(1, 23))
assert mgr.processed == list(range(1, 12))
assert mgr.rejected == list(range(1, 7))
assert mgr.low_watermark == 89
assert seq_num == 5
def test_channel_manager(packets, crypto):
from xbox.sg.enum import ServiceChannel
from xbox.sg.packer import unpack
start_channel_resp = unpack(packets['start_channel_response'], crypto)
mgr = ChannelManager()
request_id = 0
while request_id != start_channel_resp.protected_payload.channel_request_id:
request_id = mgr.get_next_request_id(ServiceChannel.SystemInputTVRemote)
service_channel = mgr.handle_channel_start_response(start_channel_resp)
assert service_channel == ServiceChannel.SystemInputTVRemote
# Deleting channel references
mgr.reset()
with pytest.raises(ChannelError):
mgr.get_channel(123)
with pytest.raises(ChannelError):
mgr.get_channel_id(ServiceChannel.SystemInputTVRemote)
with pytest.raises(ChannelError):
mgr.handle_channel_start_response(start_channel_resp)
assert mgr.get_channel(0) == ServiceChannel.Core
assert mgr.get_channel(0x1000000000000000) == ServiceChannel.Ack
assert mgr.get_channel_id(ServiceChannel.Core) == 0
assert mgr.get_channel_id(ServiceChannel.Ack) == 0x1000000000000000
def test_fragment_manager_json(json_fragments):
expected_result = {'response': 'GetConfiguration',
'msgid': 'xV5X1YCB.13',
'params': [
{'device_id': '0',
'device_type': 'tv',
'buttons': {
'btn.back': 'Back',
'btn.up': 'Up',
'btn.red': 'Red',
'btn.page_down': 'Page Down',
'btn.ch_down': 'Channel Down',
'btn.func_c': 'Label C',
'btn.format': 'Format',
'btn.digit_2': '2',
'btn.func_a': 'Label A',
'btn.digit_7': '7',
'btn.last': 'Last',
'btn.input': 'Input',
'btn.fast_fwd': 'FFWD',
'btn.menu': 'Menu',
'btn.replay': 'Skip REV',
'btn.power': 'Power',
'btn.left': 'Left',
'btn.blue': 'Blue',
'btn.vol_down': 'Volume Down',
'btn.green': 'Green',
'btn.digit_4': '4',
'btn.digit_9': '9',
'btn.play': 'Play',
'btn.page_up': 'Page Up',
'btn.func_b': 'Label B',
'btn.power_off': 'Off',
'btn.vol_mute': 'Mute',
'btn.record': 'Record',
'btn.subtitle': 'Subtitle',
'btn.rewind': 'Rewind',
'btn.exit': 'Exit',
'btn.down': 'Down',
'btn.sap': 'Sap',
'btn.yellow': 'Yellow',
'btn.func_d': 'Label D',
'btn.info': 'Info',
'btn.digit_5': '5',
'btn.digit_3': '3',
'btn.digit_0': '0',
'btn.skip_fwd': 'Skip FWD',
'btn.delimiter': 'Delimiter',
'btn.right': 'Right',
'btn.vol_up': 'Volume Up',
'btn.ch_up': 'Channel Up',
'btn.digit_8': '8',
'btn.digit_6': '6',
'btn.guide': 'Guide',
'btn.stop': 'Stop',
'btn.select': 'Select',
'btn.power_on': 'On',
'btn.ch_enter': 'Enter',
'btn.digit_1': '1',
'btn.pause': 'Pause',
'btn.dvr': 'Recordings'
}},
{'device_id': '1',
'device_brand': 'Sky Deutschland',
'device_type': 'stb',
'buttons': {
'btn.back': 'Back',
'btn.red': 'Red',
'btn.up': 'Up',
'btn.ch_down': 'Channel Down',
'btn.format': 'Format',
'btn.digit_2': '2',
'btn.digit_7': '7',
'btn.last': 'Last',
'btn.fast_fwd': 'FFWD',
'btn.menu': 'Menu',
'btn.power': 'Power',
'btn.left': 'Left',
'btn.blue': 'Blue',
'btn.vol_down': 'Volume Down',
'btn.green': 'Green',
'btn.digit_4': '4',
'btn.digit_9': '9',
'btn.play': 'Play',
'btn.vol_mute': 'Mute',
'btn.record': 'Record',
'btn.rewind': 'Rewind',
'btn.exit': 'Exit',
'btn.down': 'Down',
'btn.yellow': 'Yellow',
'btn.info': 'Info',
'btn.digit_5': '5',
'btn.digit_3': '3',
'btn.digit_0': '0',
'btn.live': 'Live',
'btn.vol_up': 'Volume Up',
'btn.right': 'Right',
'btn.ch_up': 'Channel Up',
'btn.digit_8': '8',
'btn.digit_6': '6',
'btn.guide': 'Guide',
'btn.stop': 'Stop',
'btn.select': 'Select',
'btn.digit_1': '1',
'btn.pause': 'Pause',
'btn.dvr': 'Recordings'}
},
{'device_id': 'tuner',
'device_type': 'tuner',
'buttons': {
'btn.play': 'PLAY',
'btn.pause': 'PAUSE',
'btn.seek': 'SEEK'
}
}
]}
mgr = FragmentManager()
for msg in json_fragments:
msg1 = mgr.reassemble_json(msg)
for msg in reversed(json_fragments):
msg2 = mgr.reassemble_json(msg)
# Deliver a fragment twice
mgr.reassemble_json(json_fragments[0])
mgr.reassemble_json(json_fragments[1])
mgr.reassemble_json(json_fragments[2])
mgr.reassemble_json(json_fragments[2])
msg3 = mgr.reassemble_json(json_fragments[3])
# Incomplete fragments
for msg in reversed(json_fragments[:-1]):
msg4 = mgr.reassemble_json(msg)
with pytest.raises(KeyError):
mgr.reassemble_json({'not': 'all', 'required': 'fields'})
assert msg1 == expected_result
assert msg2 == expected_result
assert msg3 == expected_result
assert msg4 is None
def test_fragment_manager_fragment_messages(packets, crypto):
from xbox.sg.packer import unpack
fragments = [
unpack(packets['fragment_media_state_0'], crypto),
unpack(packets['fragment_media_state_1'], crypto),
unpack(packets['fragment_media_state_2'], crypto)
]
mgr = FragmentManager()
assert mgr.reassemble_message(fragments.pop()) is None
assert mgr.reassemble_message(fragments.pop()) is None
msg = mgr.reassemble_message(fragments.pop())
assert msg is not None
assert msg.aum_id == 'Microsoft.BlurayPlayer_8wekyb3d8bbwe!Xbox.BlurayPlayer.Application'
assert msg.max_seek == 50460000
assert len(msg.asset_id) == 2184
| {"/xbox/sg/factory.py": ["/xbox/sg/enum.py"], "/xbox/auxiliary/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/utils/events.py"], "/tests/test_auxstream_packing.py": ["/xbox/sg/crypto.py", "/xbox/auxiliary/__init__.py"], "/xbox/rest/singletons.py": ["/xbox/rest/schemas/auth.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/common.py": ["/xbox/rest/schemas/auth.py"], "/xbox/stump/json_model.py": ["/xbox/stump/enum.py"], "/tests/test_stump_json_models.py": ["/xbox/stump/enum.py"], "/tests/test_factory.py": ["/xbox/sg/__init__.py"], "/xbox/rest/app.py": ["/xbox/rest/__init__.py", "/xbox/rest/api.py"], "/tests/test_padding.py": ["/xbox/sg/crypto.py"], "/xbox/rest/deps.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py", "/xbox/rest/schemas/auth.py"], "/xbox/sg/packer.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/scripts/recrypt.py": ["/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/tests/test_console.py": ["/xbox/sg/__init__.py"], "/xbox/stump/manager.py": ["/xbox/sg/utils/events.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py", "/xbox/stump/enum.py"], "/xbox/scripts/pcap.py": ["/xbox/sg/__init__.py", "/xbox/sg/crypto.py", "/xbox/sg/enum.py"], "/xbox/handlers/fallout4_relay.py": ["/xbox/auxiliary/relay.py", "/xbox/sg/utils/struct.py"], "/xbox/sg/utils/adapters.py": ["/xbox/sg/enum.py"], "/xbox/scripts/main_cli.py": ["/xbox/scripts/__init__.py", "/xbox/handlers/__init__.py", "/xbox/auxiliary/manager.py", "/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py"], "/xbox/rest/routes/root.py": ["/xbox/rest/__init__.py"], "/xbox/rest/consolewrap.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/manager.py", "/xbox/stump/manager.py", "/xbox/rest/__init__.py"], "/xbox/sg/console.py": ["/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/sg/enum.py", "/xbox/sg/protocol.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py", "/xbox/stump/manager.py"], "/xbox/sg/constants.py": ["/xbox/sg/enum.py"], "/xbox/sg/manager.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/xbox/rest/schemas/__init__.py": ["/xbox/rest/schemas/root.py", "/xbox/rest/schemas/general.py", "/xbox/rest/schemas/auth.py", "/xbox/rest/schemas/device.py"], "/xbox/sg/protocol.py": ["/xbox/sg/__init__.py", "/xbox/sg/packet/message.py", "/xbox/sg/enum.py", "/xbox/sg/constants.py", "/xbox/sg/manager.py", "/xbox/sg/utils/events.py", "/xbox/sg/utils/struct.py"], "/tests/test_pcap.py": ["/xbox/scripts/__init__.py"], "/xbox/sg/packet/simple.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/xbox/auxiliary/relay.py": ["/xbox/sg/crypto.py", "/xbox/sg/utils/events.py", "/xbox/auxiliary/__init__.py", "/xbox/auxiliary/packet.py", "/xbox/auxiliary/crypto.py", "/xbox/sg/utils/struct.py"], "/xbox/auxiliary/packer.py": ["/xbox/auxiliary/crypto.py", "/xbox/sg/crypto.py", "/xbox/auxiliary/packet.py"], "/tests/test_rest_consolewrap.py": ["/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/xbox/sg/packet/message.py": ["/xbox/sg/__init__.py", "/xbox/sg/enum.py", "/xbox/sg/utils/struct.py", "/xbox/sg/utils/adapters.py"], "/tests/test_auxmanager.py": ["/xbox/sg/enum.py", "/xbox/auxiliary/manager.py"], "/tests/conftest.py": ["/xbox/sg/__init__.py", "/xbox/sg/console.py", "/xbox/sg/crypto.py", "/xbox/sg/manager.py", "/xbox/auxiliary/crypto.py", "/xbox/stump/manager.py", "/xbox/rest/app.py", "/xbox/rest/consolewrap.py"], "/xbox/rest/routes/auth.py": ["/xbox/rest/__init__.py", "/xbox/rest/common.py"], "/xbox/handlers/gamepad_input.py": ["/xbox/sg/enum.py"], "/tests/test_packer.py": ["/xbox/sg/__init__.py", "/xbox/sg/constants.py"], "/xbox/rest/routes/web.py": ["/xbox/rest/deps.py"], "/xbox/sg/crypto.py": ["/xbox/sg/enum.py"], "/tests/test_crypto.py": ["/xbox/sg/enum.py", "/xbox/sg/crypto.py"], "/xbox/handlers/tui.py": ["/xbox/scripts/__init__.py", "/xbox/sg/console.py", "/xbox/sg/enum.py", "/xbox/sg/manager.py"], "/xbox/rest/routes/device.py": ["/xbox/rest/__init__.py", "/xbox/rest/deps.py", "/xbox/rest/consolewrap.py", "/xbox/sg/__init__.py"], "/tests/test_protocol.py": ["/xbox/sg/protocol.py", "/xbox/sg/enum.py", "/xbox/sg/packer.py"]} |
61,172 | Ajinkz/swdc-sublime | refs/heads/master | /Software.py | # Copyright (c) 2018 by Software.com
from threading import Thread, Timer, Event
from package_control import events
from queue import Queue
import webbrowser
import time
import datetime
import json
import os
import sublime_plugin, sublime
from .lib.SoftwareHttp import *
from .lib.SoftwareUtil import *
from .lib.SoftwareMusic import *
from .lib.SoftwareRepo import *
from .lib.SoftwareOffline import *
from .lib.SoftwareSettings import *
DEFAULT_DURATION = 60
PROJECT_DIR = None
check_online_interval_sec = 60 * 10
retry_counter = 0
# payload trigger to store it for later.
def post_json(json_data):
# save the data to the offline data file
storePayload(json_data)
PluginData.reset_source_data()
#
# Background thread used to send data every minute.
#
class BackgroundWorker():
def __init__(self, threads_count, target_func):
self.queue = Queue(maxsize=0)
self.target_func = target_func
self.threads = []
for i in range(threads_count):
thread = Thread(target=self.worker, daemon=True)
thread.start()
self.threads.append(thread)
def worker(self):
while True:
self.target_func(self.queue.get())
self.queue.task_done()
#
# kpm payload data structure
#
class PluginData():
__slots__ = ('source', 'keystrokes', 'start', 'local_start', 'project', 'pluginId', 'version', 'os', 'timezone')
background_worker = BackgroundWorker(1, post_json)
active_datas = {}
line_counts = {}
send_timer = None
def __init__(self, project):
self.source = {}
self.start = 0
self.local_start = 0
self.timezone = ''
self.keystrokes = 0
self.project = project
self.pluginId = PLUGIN_ID
self.version = VERSION
self.timezone = getTimezone()
self.os = getOs()
def json(self):
# make sure all file end times are set
dict_data = {key: getattr(self, key, None)
for key in self.__slots__}
return json.dumps(dict_data)
# send the kpm info
def send(self):
# check if it has data
if PluginData.background_worker and self.hasData():
PluginData.endUnendedFileEndTimes()
PluginData.background_worker.queue.put(self.json())
# check if we have data
def hasData(self):
if (self.keystrokes > 0):
return True
for fileName in self.source:
fileInfo = self.source[fileName]
if (fileInfo['close'] > 0 or
fileInfo['open'] > 0 or
fileInfo['paste'] > 0 or
fileInfo['delete'] > 0 or
fileInfo['add'] > 0 or
fileInfo['netkeys'] > 0):
return True
return False
@staticmethod
def reset_source_data():
PluginData.send_timer = None
for dir in PluginData.active_datas:
keystrokeCountObj = PluginData.active_datas[dir]
# get the lines so we can add that back
for fileName in keystrokeCountObj.source:
fileInfo = keystrokeCountObj.source[fileName]
# add the lines for this file so we can re-use again
PluginData.line_counts[fileName] = fileInfo.get("lines", 0)
if keystrokeCountObj is not None:
keystrokeCountObj.source = {}
keystrokeCountObj.keystrokes = 0
keystrokeCountObj.project['identifier'] = None
keystrokeCountObj.timezone = getTimezone()
@staticmethod
def create_empty_payload(fileName, projectName):
project = {}
project['directory'] = projectName
project['name'] = projectName
return_data = PluginData(project)
PluginData.active_datas[project['directory']] = return_data
PluginData.get_file_info_and_initialize_if_none(return_data, fileName)
return return_data
@staticmethod
def get_active_data(view):
return_data = None
if view is None or view.window() is None:
return return_data
fileName = view.file_name()
if (fileName is None):
fileName = "Untitled"
sublime_variables = view.window().extract_variables()
project = {}
# set it to none as a default
projectFolder = 'Unnamed'
# set the project folder
if 'folder' in sublime_variables:
projectFolder = sublime_variables['folder']
elif 'file_path' in sublime_variables:
projectFolder = sublime_variables['file_path']
# if we have a valid project folder, set the project name from it
if projectFolder != 'Unnamed':
project['directory'] = projectFolder
if 'project_name' in sublime_variables:
project['name'] = sublime_variables['project_name']
else:
# use last file name in the folder as the project name
projectNameIdx = projectFolder.rfind('/')
if projectNameIdx > -1:
projectName = projectFolder[projectNameIdx + 1:]
project['name'] = projectName
else:
project['directory'] = 'Unnamed'
old_active_data = None
if project['directory'] in PluginData.active_datas:
old_active_data = PluginData.active_datas[project['directory']]
if old_active_data is None:
new_active_data = PluginData(project)
PluginData.active_datas[project['directory']] = new_active_data
return_data = new_active_data
else:
return_data = old_active_data
fileInfoData = PluginData.get_file_info_and_initialize_if_none(return_data, fileName)
# This activates the 60 second timer. The callback
# in the Timer sends the data
if (PluginData.send_timer is None):
PluginData.send_timer = Timer(DEFAULT_DURATION, return_data.send)
PluginData.send_timer.start()
return return_data
# ...
@staticmethod
def get_existing_file_info(fileName):
fileInfoData = None
now = round(time.time())
local_start = getLocalStart()
# Get the FileInfo object within the KeystrokesCount object
# based on the specified fileName.
for dir in PluginData.active_datas:
keystrokeCountObj = PluginData.active_datas[dir]
if keystrokeCountObj is not None:
hasExistingKeystrokeObj = True
# we have a keystroke count object, get the fileInfo
if keystrokeCountObj.source is not None and fileName in keystrokeCountObj.source:
# set the fileInfoData we'll return the calling def
fileInfoData = keystrokeCountObj.source[fileName]
else:
# end the other files end times
for fileName in keystrokeCountObj.source:
fileInfo = keystrokeCountObj.source[fileName]
fileInfo["end"] = now
fileInfo["local_end"] = local_start
return fileInfoData
#
@staticmethod
def endUnendedFileEndTimes():
now = round(time.time())
local_start = getLocalStart()
for dir in PluginData.active_datas:
keystrokeCountObj = PluginData.active_datas[dir]
if keystrokeCountObj is not None and keystrokeCountObj.source is not None:
for fileName in keystrokeCountObj.source:
fileInfo = keystrokeCountObj.source[fileName]
if (fileInfo.get("end", 0) == 0):
fileInfo["end"] = now
fileInfo["local_end"] = local_start
@staticmethod
def send_all_datas():
for dir in PluginData.active_datas:
PluginData.active_datas[dir].send()
#.........
@staticmethod
def initialize_file_info(keystrokeCount, fileName):
if keystrokeCount is None:
return
if fileName is None or fileName == '':
fileName = 'Untitled'
# create the new FileInfo, which will contain a dictionary
# of fileName and it's metrics
fileInfoData = PluginData.get_existing_file_info(fileName)
now = round(time.time())
local_start = getLocalStart()
if keystrokeCount.start == 0:
keystrokeCount.start = now
keystrokeCount.local_start = local_start
keystrokeCount.timezone = getTimezone()
# "add" = additive keystrokes
# "netkeys" = add - delete
# "keys" = add + delete
# "delete" = delete keystrokes
if fileInfoData is None:
fileInfoData = {}
fileInfoData['paste'] = 0
fileInfoData['open'] = 0
fileInfoData['close'] = 0
fileInfoData['length'] = 0
fileInfoData['delete'] = 0
fileInfoData['netkeys'] = 0
fileInfoData['add'] = 0
fileInfoData['lines'] = -1
fileInfoData['linesAdded'] = 0
fileInfoData['linesRemoved'] = 0
fileInfoData['syntax'] = ""
fileInfoData['start'] = now
fileInfoData['local_start'] = local_start
fileInfoData['end'] = 0
fileInfoData['local_end'] = 0
keystrokeCount.source[fileName] = fileInfoData
else:
# update the end and local_end to zero since the file is still getting modified
fileInfoData['end'] = 0
fileInfoData['local_end'] = 0
@staticmethod
def get_file_info_and_initialize_if_none(keystrokeCount, fileName):
fileInfoData = PluginData.get_existing_file_info(fileName)
if fileInfoData is None:
PluginData.initialize_file_info(keystrokeCount, fileName)
fileInfoData = PluginData.get_existing_file_info(fileName)
return fileInfoData
@staticmethod
def send_initial_payload():
fileName = "Untitled"
active_data = PluginData.create_empty_payload(fileName, "Unnamed")
PluginData.get_file_info_and_initialize_if_none(active_data, fileName)
fileInfoData = PluginData.get_existing_file_info(fileName)
fileInfoData['add'] = 1
active_data.keystrokes = 1
PluginData.send_all_datas()
class GoToSoftwareCommand(sublime_plugin.TextCommand):
def run(self, edit):
launchWebDashboardUrl()
def is_enabled(self):
loggedOn = getValue("logged_on", True)
online = getValue("online", True)
if (loggedOn is True and online is True):
return True
else:
return False
# code_time_login command
class CodeTimeLogin(sublime_plugin.TextCommand):
def run(self, edit):
launchLoginUrl()
def is_enabled(self):
loggedOn = getValue("logged_on", True)
online = getValue("online", True)
if (loggedOn is False and online is True):
return True
else:
return False
# Command to launch the code time metrics "launch_code_time_metrics"
class LaunchCodeTimeMetrics(sublime_plugin.TextCommand):
def run(self, edit):
launchCodeTimeMetrics()
class LaunchCustomDashboard(sublime_plugin.WindowCommand):
def run(self):
d = datetime.datetime.now()
current_time = d.strftime("%m/%d/%Y")
t = d - datetime.timedelta(days=7)
time_ago = t.strftime("%m/%d/%Y")
# default range: last 7 days
default_range = str(time_ago) + ", " + str(current_time)
self.window.show_input_panel("Enter a start and end date (format: MM/DD/YYYY):", default_range, self.on_done, None, None)
def on_done(self, result):
setValue("date_range", result)
launchCustomDashboard()
class SoftwareTopForty(sublime_plugin.TextCommand):
def run(self, edit):
webbrowser.open("https://api.software.com/music/top40")
def is_enabled(self):
return (getValue("online", True) is True)
class ToggleStatusBarMetrics(sublime_plugin.TextCommand):
def run(self, edit):
log("toggling status bar metrics")
showStatusVal = getValue("show_code_time_status", True)
if (showStatusVal):
setValue("show_code_time_status", False)
else:
setValue("show_code_time_status", True)
toggleStatus()
# Mute Console message
class HideConsoleMessage(sublime_plugin.TextCommand):
def run(self, edit):
log("Code Time: Console Messages Disabled !")
# showStatus("Paused")
setValue("software_logging_on", False)
def is_enabled(self):
return (getValue("software_logging_on", True) is True)
# Command to re-enable Console message
class ShowConsoleMessage(sublime_plugin.TextCommand):
def run(self, edit):
log("Code Time: Console Messages Enabled !")
# showStatus("Code Time")
setValue("software_logging_on", True)
def is_enabled(self):
return (getValue("software_logging_on", True) is False)
# Command to pause kpm metrics
class PauseKpmUpdatesCommand(sublime_plugin.TextCommand):
def run(self, edit):
log("software kpm metrics paused")
showStatus("Paused")
setValue("software_telemetry_on", False)
def is_enabled(self):
return (getValue("software_telemetry_on", True) is True)
# Command to re-enable kpm metrics
class EnableKpmUpdatesCommand(sublime_plugin.TextCommand):
def run(self, edit):
log("Code Time: metrics enabled")
showStatus("Code Time")
setValue("software_telemetry_on", True)
def is_enabled(self):
return (getValue("software_telemetry_on", True) is False)
# Runs once instance per view (i.e. tab, or single file window)
class EventListener(sublime_plugin.EventListener):
def on_load_async(self, view):
fileName = view.file_name()
if (fileName is None):
fileName = "Untitled"
active_data = PluginData.get_active_data(view)
# get the file info to increment the open metric
fileInfoData = PluginData.get_file_info_and_initialize_if_none(active_data, fileName)
if fileInfoData is None:
return
fileSize = view.size()
fileInfoData['length'] = fileSize
# get the number of lines
lines = view.rowcol(fileSize)[0] + 1
fileInfoData['lines'] = lines
# we have the fileinfo, update the metric
fileInfoData['open'] += 1
log('Code Time: opened file %s' % fileName)
# show last status message
redispayStatus()
def on_close(self, view):
fileName = view.file_name()
if (fileName is None):
fileName = "Untitled"
active_data = PluginData.get_active_data(view)
# get the file info to increment the close metric
fileInfoData = PluginData.get_file_info_and_initialize_if_none(active_data, fileName)
if fileInfoData is None:
return
fileSize = view.size()
fileInfoData['length'] = fileSize
# get the number of lines
lines = view.rowcol(fileSize)[0] + 1
fileInfoData['lines'] = lines
# we have the fileInfo, update the metric
fileInfoData['close'] += 1
log('Code Time: closed file %s' % fileName)
# show last status message
redispayStatus()
def on_modified_async(self, view):
global PROJECT_DIR
# get active data will create the file info if it doesn't exist
active_data = PluginData.get_active_data(view)
if active_data is None:
return
# add the count for the file
fileName = view.file_name()
fileInfoData = {}
if (fileName is None):
fileName = "Untitled"
fileInfoData = PluginData.get_file_info_and_initialize_if_none(active_data, fileName)
# If file is untitled then log that msg and set file open metrics to 1
if fileName == "Untitled":
log("Code Time: opened file untitled")
fileInfoData['open'] = 1
else:
pass
if fileInfoData is None:
return
fileSize = view.size()
#lines = 0
# rowcol gives 0-based line number, need to add one as on editor lines starts from 1
lines = view.rowcol(fileSize)[0] + 1
prevLines = fileInfoData['lines']
if (prevLines == 0):
if (PluginData.line_counts.get(fileName) is None):
PluginData.line_counts[fileName] = prevLines
prevLines = PluginData.line_counts[fileName]
elif (prevLines > 0):
fileInfoData['lines'] = prevLines
lineDiff = 0
if (prevLines > 0):
lineDiff = lines - prevLines
if (lineDiff > 0):
fileInfoData['linesAdded'] += lineDiff
log('Code Time: linesAdded incremented')
elif (lineDiff < 0):
fileInfoData['linesRemoved'] += abs(lineDiff)
log('Code Time: linesRemoved incremented')
fileInfoData['lines'] = lines
# subtract the current size of the file from what we had before
# we'll know whether it's a delete, copy+paste, or kpm.
currLen = fileInfoData['length']
charCountDiff = 0
if currLen > 0 or currLen == 0:
# currLen > 0 only worked for existing file, currlen==0 will work for new file
charCountDiff = fileSize - currLen
if (not fileInfoData["syntax"]):
syntax = view.settings().get('syntax')
# get the last occurance of the "/" then get the 1st occurance of the .sublime-syntax
# [language].sublime-syntax
# Packages/Python/Python.sublime-syntax
syntax = syntax[syntax.rfind('/') + 1:-len(".sublime-syntax")]
if (syntax):
fileInfoData["syntax"] = syntax
PROJECT_DIR = active_data.project['directory']
# getResourceInfo is a SoftwareUtil function
if (active_data.project.get("identifier") is None):
resourceInfoDict = getResourceInfo(PROJECT_DIR)
if (resourceInfoDict.get("identifier") is not None):
active_data.project['identifier'] = resourceInfoDict['identifier']
active_data.project['resource'] = resourceInfoDict
fileInfoData['length'] = fileSize
if lineDiff == 0 and charCountDiff > 8:
fileInfoData['paste'] += 1
log('Code Time: pasted incremented')
elif lineDiff == 0 and charCountDiff == -1:
fileInfoData['delete'] += 1
log('Code Time: delete incremented')
elif lineDiff == 0 and charCountDiff == 1:
fileInfoData['add'] += 1
log('Code Time: KPM incremented')
# increment the overall count
if (charCountDiff != 0 or lineDiff != 0):
active_data.keystrokes += 1
# update the netkeys and the keys
# "netkeys" = add - delete
fileInfoData['netkeys'] = fileInfoData['add'] - fileInfoData['delete']
#
# Iniates the plugin tasks once the it's loaded into Sublime.
#
def plugin_loaded():
initializeUser()
def initializeUser():
# check if the session file is there
serverAvailable = checkOnline()
fileExists = softwareSessionFileExists()
jwt = getItem("jwt")
log("JWT VAL: %s" % jwt)
if (fileExists is False or jwt is None):
if (serverAvailable is False):
if (retry_counter == 0):
showOfflinePrompt()
initializeUserTimer = Timer(check_online_interval_sec, initializeUser)
initializeUserTimer.start()
else:
result = createAnonymousUser(serverAvailable)
if (result is None):
if (retry_counter == 0):
showOfflinePrompt()
initializeUserTimer = Timer(check_online_interval_sec, initializeUser)
initializeUserTimer.start()
else:
initializePlugin(True, serverAvailable)
else:
initializePlugin(False, serverAvailable)
def initializePlugin(initializedAnonUser, serverAvailable):
PACKAGE_NAME = __name__.split('.')[0]
log('Code Time: Loaded v%s of package name: %s' % (VERSION, PACKAGE_NAME))
showStatus("Code Time")
setItem("sublime_lastUpdateTime", None)
# fire off timer tasks (seconds, task)
setOnlineStatusTimer = Timer(2, setOnlineStatus)
setOnlineStatusTimer.start()
sendOfflineDataTimer = Timer(10, sendOfflineData)
sendOfflineDataTimer.start()
gatherMusicTimer = Timer(45, gatherMusicInfo)
gatherMusicTimer.start()
hourlyTimer = Timer(60, hourlyTimerHandler)
hourlyTimer.start()
initializeUserInfo(initializedAnonUser)
def initializeUserInfo(initializedAnonUser):
getUserStatus()
if (initializedAnonUser is True):
showLoginPrompt()
PluginData.send_initial_payload()
sendInitHeartbeatTimer = Timer(15, sendInitializedHeartbeat)
sendInitHeartbeatTimer.start()
# re-fetch user info in another 90 seconds
checkUserAuthTimer = Timer(90, userStatusHandler)
checkUserAuthTimer.start()
def userStatusHandler():
getUserStatus()
loggedOn = getValue("logged_on", True)
if (loggedOn is True):
# no need to fetch any longer
return
# re-fetch user info in another 10 minutes
checkUserAuthTimer = Timer(60 * 10, userStatusHandler)
checkUserAuthTimer.start()
def plugin_unloaded():
# clean up the background worker
PluginData.background_worker.queue.join()
def sendInitializedHeartbeat():
sendHeartbeat("INITIALIZED")
# gather the git commits, repo members, heatbeat ping
def hourlyTimerHandler():
sendHeartbeat("HOURLY")
# process commits in a minute
processCommitsTimer = Timer(60, processCommits)
processCommitsTimer.start()
# run the handler in another hour
hourlyTimer = Timer(60 * 60, hourlyTimerHandler)
hourlyTimer.start()
# ...
def processCommits():
global PROJECT_DIR
gatherCommits(PROJECT_DIR)
def showOfflinePrompt():
infoMsg = "Our service is temporarily unavailable. We will try to reconnect again in 10 minutes. Your status bar will not update at this time."
sublime.message_dialog(infoMsg)
def setOnlineStatus():
online = checkOnline()
log("Code Time: Checking online status...")
if (online is True):
setValue("online", True)
log("Code Time: Online")
else:
setValue("online", False)
log("Code Time: Offline")
# run the check in another 1 minute
timer = Timer(60 * 1, setOnlineStatus)
timer.start()
| {"/Software.py": ["/lib/SoftwareUtil.py"]} |
61,173 | Ajinkz/swdc-sublime | refs/heads/master | /lib/SoftwareUtil.py | # Copyright (c) 2018 by Software.com
from threading import Thread, Timer, Event
import os
import json
import time
import datetime
import socket
import sublime_plugin, sublime
import sys
import uuid
import platform
import re, uuid
import webbrowser
from urllib.parse import quote_plus
from subprocess import Popen, PIPE
from .SoftwareHttp import *
from .SoftwareSettings import *
# the plugin version
VERSION = '0.9.4'
PLUGIN_ID = 1
DASHBOARD_LABEL_WIDTH = 25
DASHBOARD_VALUE_WIDTH = 25
MARKER_WIDTH = 4
sessionMap = {}
runningResourceCmd = False
loggedInCacheState = False
timezone=''
# log the message.
def log(message):
if (getValue("software_logging_on", True)):
print(message)
# .
def getUrlEndpoint():
return getValue("software_dashboard_url", "https://app.software.com")
def getOsUsername():
homedir = os.path.expanduser('~')
username = os.path.basename(homedir)
if (username is None or username == ""):
username = os.environ.get("USER")
return username
def getOs():
system = platform.system()
#release = platform.release()
return system
def getTimezone():
global timezone
try:
timezone = time.localtime().tm_zone
except Exception:
pass
# keystrokeCountObj.timezone = ''
return timezone
def getLocalStart():
now = round(time.time())
local_start = now - time.timezone
try:
#If current timezone is not in DST, value of tm_ist will be 0
if time.localtime().tm_isdst == 0:
pass
else:
# we're in DST, add 1
local_start += (60 * 60)
except Exception:
pass
return local_start
def getHostname():
try:
return socket.gethostname()
except Exception:
return os.uname().nodename
# fetch a value from the .software/sesion.json file
def getItem(key):
val = sessionMap.get(key, None)
if (val is not None):
return val
jsonObj = getSoftwareSessionAsJson()
# return a default of None if key isn't found
val = jsonObj.get(key, None)
return val
# get an item from the session json file
def setItem(key, value):
sessionMap[key] = value
jsonObj = getSoftwareSessionAsJson()
jsonObj[key] = value
content = json.dumps(jsonObj)
sessionFile = getSoftwareSessionFile()
with open(sessionFile, 'w') as f:
f.write(content)
def softwareSessionFileExists():
file = getSoftwareDir(False)
sessionFile = os.path.join(file, 'session.json')
return os.path.isfile(sessionFile)
def getSoftwareSessionAsJson():
try:
with open(getSoftwareSessionFile()) as sessionFile:
loadedSessionFile = json.load(sessionFile)
return loadedSessionFile
except Exception:
return {}
def getSoftwareSessionFile():
file = getSoftwareDir(True)
return os.path.join(file, 'session.json')
def getSoftwareDataStoreFile():
file = getSoftwareDir(True)
return os.path.join(file, 'data.json')
def getSoftwareDir(autoCreate):
softwareDataDir = os.path.expanduser('~')
softwareDataDir = os.path.join(softwareDataDir, '.software')
if (autoCreate is True):
os.makedirs(softwareDataDir, exist_ok=True)
return softwareDataDir
def getDashboardFile():
file = getSoftwareDir(True)
return os.path.join(file, 'CodeTime.txt')
def getCustomDashboardFile():
file = getSoftwareDir(True)
return os.path.join(file, 'CustomDashboard.txt')
# execute the applescript command
def runCommand(cmd, args = []):
p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate(cmd)
return stdout.decode('utf-8').strip()
def getItunesTrackState():
script = '''
tell application "iTunes" to get player state
'''
try:
cmd = script.encode('latin-1')
result = runCommand(cmd, ['osascript', '-'])
return result
except Exception as e:
log("Code Time: error getting track state: %s " % e)
# no music found playing
return "stopped"
def getSpotifyTrackState():
script = '''
tell application "Spotify" to get player state
'''
try:
cmd = script.encode('latin-1')
result = runCommand(cmd, ['osascript', '-'])
return result
except Exception as e:
log("Code Time: error getting track state: %s " % e)
# no music found playing
return "stopped"
# get the current track playing (spotify or itunes)
def getTrackInfo():
if sys.platform == "darwin":
return getMacTrackInfo()
elif sys.platform == "win32":
# not supported on other platforms yet
return getWinTrackInfo()
else:
# linux not supported yet
return {}
# windows
def getWinTrackInfo():
# not supported on other platforms yet
return {}
# OS X
def getMacTrackInfo():
script = '''
on buildItunesRecord(appState)
tell application "iTunes"
set track_artist to artist of current track
set track_name to name of current track
set track_genre to genre of current track
set track_id to database ID of current track
set track_duration to duration of current track
set json to "type='itunes';genre='" & track_genre & "';artist='" & track_artist & "';id='" & track_id & "';name='" & track_name & "';state='playing';duration='" & track_duration & "'"
end tell
return json
end buildItunesRecord
on buildSpotifyRecord(appState)
tell application "Spotify"
set track_artist to artist of current track
set track_name to name of current track
set track_duration to duration of current track
set track_id to id of current track
set track_duration to duration of current track
set json to "type='spotify';genre='';artist='" & track_artist & "';id='" & track_id & "';name='" & track_name & "';state='playing';duration='" & track_duration & "'"
end tell
return json
end buildSpotifyRecord
try
if application "Spotify" is running and application "iTunes" is not running then
tell application "Spotify" to set spotifyState to (player state as text)
-- spotify is running and itunes is not
if (spotifyState is "paused" or spotifyState is "playing") then
set jsonRecord to buildSpotifyRecord(spotifyState)
else
set jsonRecord to {}
end if
else if application "Spotify" is running and application "iTunes" is running then
tell application "Spotify" to set spotifyState to (player state as text)
tell application "iTunes" to set itunesState to (player state as text)
-- both are running but use spotify as a higher priority
if spotifyState is "playing" then
set jsonRecord to buildSpotifyRecord(spotifyState)
else if itunesState is "playing" then
set jsonRecord to buildItunesRecord(itunesState)
else if spotifyState is "paused" then
set jsonRecord to buildSpotifyRecord(spotifyState)
else
set jsonRecord to {}
end if
else if application "iTunes" is running and application "Spotify" is not running then
tell application "iTunes" to set itunesState to (player state as text)
set jsonRecord to buildItunesRecord(itunesState)
else
set jsonRecord to {}
end if
return jsonRecord
on error
return {}
end try
'''
try:
cmd = script.encode('latin-1')
result = runCommand(cmd, ['osascript', '-'])
result = result.strip('\r\n')
result = result.replace('"', '')
result = result.replace('\'', '')
if (result):
trackInfo = dict(item.strip().split("=") for item in result.strip().split(";"))
return trackInfo
else:
return {}
except Exception as e:
log("Code Time: error getting track: %s " % e)
# no music found playing
return {}
def runResourceCmd(cmdArgs, rootDir):
if sys.platform == "darwin": # OS X
runningResourceCmd = True
p = Popen(cmdArgs, cwd = rootDir, stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
stdout = stdout.decode('utf-8').strip()
if (stdout):
stdout = stdout.strip('\r\n')
return stdout
else:
return ""
else:
return ""
def getResourceInfo(rootDir):
try:
resourceInfo = {}
tag = runResourceCmd(['git', 'describe', '--all'], rootDir)
if (tag):
resourceInfo['tag'] = tag
identifier = runResourceCmd(['git', 'config', '--get', 'remote.origin.url'], rootDir)
if (identifier):
resourceInfo['identifier'] = identifier
branch = runResourceCmd(['git', 'symbolic-ref', '--short', 'HEAD'], rootDir)
if (branch):
resourceInfo['branch'] = branch
email = runResourceCmd(['git', 'config', 'user.email'], rootDir)
if (email):
resourceInfo['email'] = email
if (resourceInfo.get("identifier") is not None):
return resourceInfo
else:
return {}
except Exception as e:
return {}
def checkOnline():
# non-authenticated ping, no need to set the Authorization header
response = requestIt("GET", "/ping", None, getItem("jwt"))
if (isResponsOk(response)):
return True
else:
return False
def refetchUserStatusLazily(tryCountUntilFoundUser):
currentUserStatus = getUserStatus()
loggedInUser = currentUserStatus.get("loggedInUser", None)
if (loggedInUser is not None or tryCountUntilFoundUser <= 0):
return
# start the time
tryCountUntilFoundUser -= 1
t = Timer(10, refetchUserStatusLazily, [tryCountUntilFoundUser])
t.start()
def launchLoginUrl():
webUrl = getUrlEndpoint()
jwt = getItem("jwt")
webUrl += "/onboarding?token=" + jwt
webbrowser.open(webUrl)
refetchUserStatusLazily(10)
def launchWebDashboardUrl():
webUrl = getUrlEndpoint() + "/login"
webbrowser.open(webUrl)
def isMac():
if sys.platform == "darwin":
return True
return False
def isWindows():
if sys.platform == "win32":
return True
return False
def fetchCustomDashboard(date_range):
try:
date_range_arr = [x.strip() for x in date_range.split(',')]
startDate = date_range_arr[0]
endDate = date_range_arr[1]
start = int(time.mktime(datetime.datetime.strptime(startDate, "%m/%d/%Y").timetuple()))
end = int(time.mktime(datetime.datetime.strptime(endDate, "%m/%d/%Y").timetuple()))
except Exception:
sublime.error_message(
'Invalid date range'
'\n\n'
'Please enter a start and end date in the format, MM/DD/YYYY.'
'\n\n'
'Example: 04/24/2019, 05/01/2019')
log("Code Time: invalid date range")
try:
api = '/dashboard?start=' + str(start) + '&end=' + str(end)
response = requestIt("GET", api, None, getItem("jwt"))
content = response.read().decode('utf-8')
file = getCustomDashboardFile()
with open(file, 'w', encoding='utf-8') as f:
f.write(content)
except Exception:
log("Code Time: Unable to write custom dashboard")
def launchCustomDashboard():
online = getValue("online", True)
date_range = getValue("date_range", "04/24/2019, 05/01/2019")
if (online):
fetchCustomDashboard(date_range)
else:
log("Code Time: could not fetch custom dashboard")
file = getCustomDashboardFile()
sublime.active_window().open_file(file)
def getAppJwt():
serverAvailable = checkOnline()
if (serverAvailable):
now = round(time.time())
api = "/data/apptoken?token=" + str(now)
response = requestIt("GET", api, None, None)
if (response is not None):
responseObjStr = response.read().decode('utf-8')
try:
responseObj = json.loads(responseObjStr)
appJwt = responseObj.get("jwt", None)
if (appJwt is not None):
return appJwt
except Exception as ex:
log("Code Time: Unable to retrieve app token: %s" % ex)
return None
# crate a uuid token to establish a connection
def createToken():
# return os.urandom(16).encode('hex')
uid = uuid.uuid4()
return uid.hex
def createAnonymousUser(serverAvailable):
appJwt = getAppJwt()
if (serverAvailable and appJwt):
username = getOsUsername()
timezone = getTimezone()
hostname = getHostname()
payload = {}
payload["username"] = username
payload["timezone"] = timezone
payload["hostname"] = hostname
payload["creation_annotation"] = "NO_SESSION_FILE"
api = "/data/onboard"
try:
response = requestIt("POST", api, json.dumps(payload), appJwt)
if (response is not None and isResponsOk(response)):
try:
responseObj = json.loads(response.read().decode('utf-8'))
jwt = responseObj.get("jwt", None)
log("created anonymous user with jwt %s " % jwt)
setItem("jwt", jwt)
return jwt
except Exception as ex:
log("Code Time: Unable to retrieve plugin accounts response: %s" % ex)
except Exception as ex:
log("Code Time: Unable to complete anonymous user creation: %s" % ex)
return None
def getUser(serverAvailable):
jwt = getItem("jwt")
if (jwt and serverAvailable):
api = "/users/me"
response = requestIt("GET", api, None, jwt)
if (isResponsOk(response)):
try:
responseObj = json.loads(response.read().decode('utf-8'))
user = responseObj.get("data", None)
return user
except Exception as ex:
log("Code Time: Unable to retrieve user: %s" % ex)
return None
def validateEmail(email):
match = re.findall('\S+@\S+', email)
if match:
return True
return False
def isLoggedOn(serverAvailable):
jwt = getItem("jwt")
if (serverAvailable and jwt is not None):
user = getUser(serverAvailable)
if (user is not None and validateEmail(user.get("email", None))):
setItem("name", user.get("email"))
setItem("jwt", user.get("plugin_jwt"))
return True
api = "/users/plugin/state"
response = requestIt("GET", api, None, jwt)
responseOk = isResponsOk(response)
if (responseOk is True):
try:
responseObj = json.loads(response.read().decode('utf-8'))
state = responseObj.get("state", None)
if (state is not None and state == "OK"):
email = responseObj.get("emai", None)
setItem("name", email)
pluginJwt = responseObj.get("jwt", None)
if (pluginJwt is not None and pluginJwt != jwt):
setItem("jwt", pluginJwt)
# state is ok, return True
return True
elif (state is not None and state == "NOT_FOUND"):
setItem("jwt", None)
except Exception as ex:
log("Code Time: Unable to retrieve logged on response: %s" % ex)
setItem("name", None)
return False
def getUserStatus():
global loggedInCacheState
currentUserStatus = {}
if (loggedInCacheState is True):
currentUserStatus["loggedOn"] = loggedInCacheState
return currentUserStatus
getOsUsername()
serverAvailable = checkOnline()
# check if they're logged in or not
loggedOn = isLoggedOn(serverAvailable)
setValue("logged_on", loggedOn)
currentUserStatus["loggedOn"] = loggedOn
if (loggedOn is True and loggedInCacheState != loggedOn):
log("Code Time: Logged on")
sendHeartbeat("STATE_CHANGE:LOGGED_IN:true")
loggedInCacheState = loggedOn
return currentUserStatus
def sendHeartbeat(reason):
jwt = getItem("jwt")
serverAvailable = checkOnline()
if (jwt is not None and serverAvailable):
payload = {}
payload["pluginId"] = PLUGIN_ID
payload["os"] = getOs()
payload["start"] = round(time.time())
payload["version"] = VERSION
payload["hostname"] = getHostname()
payload["trigger_annotaion"] = reason
api = "/data/heartbeat"
try:
response = requestIt("POST", api, json.dumps(payload), jwt)
if (response is not None and isResponsOk(response) is False):
log("Code Time: Unable to send heartbeat ping")
except Exception as ex:
log("Code Time: Unable to send heartbeat: %s" % ex)
def humanizeMinutes(minutes):
minutes = int(minutes)
humanizedStr = ""
if (minutes == 60):
humanizedStr = "1 hr"
elif (minutes > 60):
floatMin = (minutes / 60)
if (floatMin % 1 == 0):
# don't show zeros after the decimal
humanizedStr = '{:4.0f}'.format(floatMin) + " hrs"
else:
# at least 4 chars (including the dot) with 2 after the dec point
humanizedStr = '{:4.1f}'.format(round(floatMin, 1)) + " hrs"
elif (minutes == 1):
humanizedStr = "1 min"
else:
humanizedStr = '{:1.0f}'.format(minutes) + " min"
return humanizedStr
def getDashboardRow(label, value):
dashboardLabel = getDashboardLabel(label, DASHBOARD_LABEL_WIDTH)
dashboardValue = getDashboardValue(value)
content = "%s : %s\n" % (dashboardLabel, dashboardValue)
return content
def getSectionHeader(label):
content = "%s\n" % label
# add 3 to account for the " : " between the columns
dashLen = DASHBOARD_LABEL_WIDTH + DASHBOARD_VALUE_WIDTH + 15
for i in range(dashLen):
content += "-"
content += "\n"
return content
def getDashboardLabel(label, width):
return getDashboardDataDisplay(width, label)
def getDashboardValue(value):
valueContent = getDashboardDataDisplay(DASHBOARD_VALUE_WIDTH, value)
paddedContent = ""
for i in range(11):
paddedContent += " "
paddedContent = "%s%s" % (paddedContent, valueContent)
return paddedContent
def getDashboardDataDisplay(widthLen, data):
dataLen = len(data)
stringLen = widthLen - len(data)
content = ""
for i in range(stringLen):
content += " "
return "%s%s" % (content, data)
| {"/Software.py": ["/lib/SoftwareUtil.py"]} |
61,193 | zhChenOuO/python-tiny-url | refs/heads/master | /app/models/test_short_url.py | import json
import unittest
from .short_url import ShortURL
from ..errors import ToManyShortURL, NoSupportShortURLCharacter, NoSupportURL, InvalidInput
class TestStringMethods(unittest.TestCase):
def test_url_is_valid(self):
t1 = ShortURL()
t1.init_by_create({"url": "http://google.com"})
self.assertIsNone(t1.verify())
t2 = ShortURL()
t2.init_by_create({"url": "abcd"})
try:
t2.verify()
except NoSupportURL as e:
self.assertEqual(type(e), NoSupportURL)
def test_encode(self):
t1 = ShortURL()
t1.short = "jU"
num = t1.encode()
self.assertEqual(num, 1234)
def test_decode(self):
t1 = ShortURL()
t1.id = 1234
ss = t1.decode()
self.assertEqual(ss, "jU")
if __name__ == '__main__':
unittest.main()
| {"/app/models/test_short_url.py": ["/app/models/short_url.py", "/app/errors.py"], "/app/__init__.py": ["/app/route/short_url.py", "/app/route/static_file.py"], "/app/models/short_url.py": ["/app/errors.py"], "/app/route/static_file.py": ["/app/models/short_url.py", "/app/errors.py"], "/app/route/short_url.py": ["/app/models/short_url.py", "/app/errors.py"]} |
61,194 | zhChenOuO/python-tiny-url | refs/heads/master | /app/__init__.py | # coding:utf-8
import os
from flask import Flask, request, current_app, jsonify, g
from flask_sqlalchemy import SQLAlchemy
from flask_redis import FlaskRedis
from flask_migrate import Migrate
from .extensions import db, redis_store, migrate
from werkzeug.exceptions import HTTPException
import traceback
import sys
import uuid
import json
import logging
from logging.config import dictConfig
def create_app():
app = Flask(__name__, static_url_path='')
app.config.from_pyfile('../deployment/configs/app.cfg', silent=True)
dictConfig({
'version': 1,
'formatters': {'default': {
'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
}},
'handlers': {'wsgi': {
'class': 'logging.StreamHandler',
'stream': 'ext://sys.stdout',
'formatter': 'default'
}},
'root': {
'level': 'DEBUG',
'handlers': ['wsgi']
}
})
register_extensions(app)
register_errorhandlers(app)
register_blueprints(app)
register_access_log(app)
return app
def register_extensions(app):
db.init_app(app)
redis_store.init_app(app)
migrate.init_app(app, db)
def register_errorhandlers(app):
@app.errorhandler(404)
def page_not_found(e):
# note that we set the 404 status explicitly
return app.send_static_file('404.html')
@app.errorhandler(Exception)
def errors(e):
message = getattr(e, 'description', None) or getattr(
e, 'msg', None) or str(e)
error = {
'code': str(getattr(e, 'code', 500)),
'name': str(getattr(e, 'name', '')),
'message': message
}
error['trace'] = traceback.format_exception(*sys.exc_info())
print(''.join(error['trace']))
code = error['code'] if isinstance(e, HTTPException) else 500
return jsonify(error), int(code)
def register_blueprints(app):
from app.route.short_url import short_url_api
app.register_blueprint(short_url_api, url_prefix='/api/v1/shorten')
from app.route.static_file import static_file
app.register_blueprint(static_file, url_prefix='/')
@app.route('/')
def index():
return app.send_static_file('index.html')
def register_access_log(app):
def save_request(request):
req_data = {}
req_data['endpoint'] = request.endpoint
req_data['method'] = request.method
req_data['cookies'] = request.cookies
req_data['data'] = request.data
req_data['headers'] = dict(request.headers)
req_data['headers'].pop('Cookie', None)
req_data['args'] = request.args
req_data['form'] = request.form
req_data['remote_addr'] = request.remote_addr
files = []
for name, fs in request.files.items():
dst = tempfile.NamedTemporaryFile()
fs.save(dst)
dst.flush()
filesize = os.stat(dst.name).st_size
dst.close()
files.append({'name': name, 'filename': fs.filename, 'filesize': filesize,
'mimetype': fs.mimetype, 'mimetype_params': fs.mimetype_params})
req_data['files'] = files
return req_data
def save_response(resp):
resp_data = {}
resp_data['status_code'] = resp.status_code
resp_data['status'] = resp.status
resp_data['headers'] = dict(resp.headers)
resp_data['data'] = resp.response
return resp_data
@app.after_request
def after_request(resp):
req_data = save_request(request)
resp_data = save_response(resp)
params = request.args if request.method == 'GET' else request.get_json()
app.logger.info(
'{} | {} | {}'.format(request.method, request.path, params))
resp.headers.add('Access-Control-Allow-Origin', '*')
resp.headers.add('Access-Control-Allow-Headers',
'Content-Type, X-Token')
resp.headers.add('Access-Control-Allow-Methods',
'GET, POST, PUT, DELETE')
return resp
| {"/app/models/test_short_url.py": ["/app/models/short_url.py", "/app/errors.py"], "/app/__init__.py": ["/app/route/short_url.py", "/app/route/static_file.py"], "/app/models/short_url.py": ["/app/errors.py"], "/app/route/static_file.py": ["/app/models/short_url.py", "/app/errors.py"], "/app/route/short_url.py": ["/app/models/short_url.py", "/app/errors.py"]} |
61,195 | zhChenOuO/python-tiny-url | refs/heads/master | /app/models/short_url.py | # -*- coding: utf-8 -*-
from app.extensions import db
from sqlalchemy.sql import func
import json
import re
from app.errors import ToManyShortURL, NoSupportShortURLCharacter, NoSupportURL, InvalidInput, SameDomin
alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
length = len(alphabet)
regex = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
class ShortURL(db.Model):
__tablename__ = 'short_urls'
__table_args__ = {"schema": "py-shorten"}
id = db.Column(db.Integer, primary_key=True)
url = db.Column(db.String(2048), nullable=False)
created_at = db.Column(db.DateTime(), nullable=False,
server_default=func.now())
short = ""
def __init__(self):
self.url = ""
def init_by_create(self, d: dict):
if 'url' in d:
self.url = d['url']
else:
raise InvalidInput
def verify(self):
if re.match(regex, self.url) is None:
raise NoSupportURL
if "https://py-shorten.herokuapp.com/" in self.url:
raise SameDomin
return None
def init_by_decode(self, s: str):
self.short = s
self.id = self.encode()
def toJSON(self):
return json.dumps({
"id": self.id,
"url": self.url,
"short": self.short,
})
def decode(self) -> str:
if self.id == 0:
return alphabet[0]
s = ""
n = self.id
while n > 0:
s = alphabet[n % length] + s
n = n // length
return s
def encode(self) -> int:
n = 0
for i in self.short:
index = 0
try:
index = alphabet.index(i)
except:
raise NoSupportShortURLCharacter
n = length*n+index
return n
def create(self):
num = db.session.query(ShortURL).count()
if num > 916132832:
raise ToManyShortURL
db.session.add(self)
db.session.commit()
self.short = self.decode()
def get_by_id(self):
return db.session.query(ShortURL).filter(
ShortURL.id == self.id).first()
| {"/app/models/test_short_url.py": ["/app/models/short_url.py", "/app/errors.py"], "/app/__init__.py": ["/app/route/short_url.py", "/app/route/static_file.py"], "/app/models/short_url.py": ["/app/errors.py"], "/app/route/static_file.py": ["/app/models/short_url.py", "/app/errors.py"], "/app/route/short_url.py": ["/app/models/short_url.py", "/app/errors.py"]} |
61,196 | zhChenOuO/python-tiny-url | refs/heads/master | /app/errors.py | # -*- coding: utf-8 -*-
# define Python user-defined exceptions
class Error(Exception):
"""Base class for other exceptions"""
pass
class ToManyShortURL(Error):
"""Raised when the input value is too small"""
pass
class NoSupportShortURLCharacter(Error):
"""Raised when the input value is too small"""
pass
class NoSupportURL(Error):
"""Raised when the input value is too small"""
pass
class SameDomin(Error):
"""Raised when the input value is too small"""
pass
class InvalidInput(Error):
pass
| {"/app/models/test_short_url.py": ["/app/models/short_url.py", "/app/errors.py"], "/app/__init__.py": ["/app/route/short_url.py", "/app/route/static_file.py"], "/app/models/short_url.py": ["/app/errors.py"], "/app/route/static_file.py": ["/app/models/short_url.py", "/app/errors.py"], "/app/route/short_url.py": ["/app/models/short_url.py", "/app/errors.py"]} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.