commit
fe16c3fad4
@ -0,0 +1,117 @@
|
||||
{
|
||||
"LabelRunningTimeValue": "Duración: {0}",
|
||||
"ValueSpecialEpisodeName": "Especial - {0}",
|
||||
"Sync": "Sincronizar",
|
||||
"Songs": "Canciones",
|
||||
"Shows": "Programas",
|
||||
"Playlists": "Listas de reproducción",
|
||||
"Photos": "Fotos",
|
||||
"Movies": "Películas",
|
||||
"HeaderNextUp": "A continuación",
|
||||
"HeaderLiveTV": "TV en vivo",
|
||||
"HeaderFavoriteSongs": "Canciones favoritas",
|
||||
"HeaderFavoriteArtists": "Artistas favoritos",
|
||||
"HeaderFavoriteAlbums": "Álbumes favoritos",
|
||||
"HeaderFavoriteEpisodes": "Episodios favoritos",
|
||||
"HeaderFavoriteShows": "Programas favoritos",
|
||||
"HeaderContinueWatching": "Continuar viendo",
|
||||
"HeaderAlbumArtists": "Artistas del álbum",
|
||||
"Genres": "Géneros",
|
||||
"Folders": "Carpetas",
|
||||
"Favorites": "Favoritos",
|
||||
"Collections": "Colecciones",
|
||||
"Channels": "Canales",
|
||||
"Books": "Libros",
|
||||
"Artists": "Artistas",
|
||||
"Albums": "Álbumes",
|
||||
"TaskDownloadMissingSubtitlesDescription": "Busca subtítulos faltantes en Internet basándose en la configuración de metadatos.",
|
||||
"TaskDownloadMissingSubtitles": "Descargar subtítulos faltantes",
|
||||
"TaskRefreshChannelsDescription": "Actualiza la información de canales de Internet.",
|
||||
"TaskRefreshChannels": "Actualizar canales",
|
||||
"TaskCleanTranscodeDescription": "Elimina archivos transcodificados que tengan más de un día.",
|
||||
"TaskCleanTranscode": "Limpiar directorio de transcodificado",
|
||||
"TaskUpdatePluginsDescription": "Descarga e instala actualizaciones para complementos que están configurados para actualizarse automáticamente.",
|
||||
"TaskUpdatePlugins": "Actualizar complementos",
|
||||
"TaskRefreshPeopleDescription": "Actualiza metadatos de actores y directores en tu biblioteca de medios.",
|
||||
"TaskRefreshPeople": "Actualizar personas",
|
||||
"TaskCleanLogsDescription": "Elimina archivos de registro con más de {0} días de antigüedad.",
|
||||
"TaskCleanLogs": "Limpiar directorio de registros",
|
||||
"TaskRefreshLibraryDescription": "Escanea tu biblioteca de medios por archivos nuevos y actualiza los metadatos.",
|
||||
"TaskRefreshLibrary": "Escanear biblioteca de medios",
|
||||
"TaskRefreshChapterImagesDescription": "Crea miniaturas para videos que tienen capítulos.",
|
||||
"TaskRefreshChapterImages": "Extraer imágenes de los capítulos",
|
||||
"TaskCleanCacheDescription": "Elimina archivos caché que ya no son necesarios para el sistema.",
|
||||
"TaskCleanCache": "Limpiar directorio caché",
|
||||
"TasksChannelsCategory": "Canales de Internet",
|
||||
"TasksApplicationCategory": "Aplicación",
|
||||
"TasksLibraryCategory": "Biblioteca",
|
||||
"TasksMaintenanceCategory": "Mantenimiento",
|
||||
"VersionNumber": "Versión {0}",
|
||||
"ValueHasBeenAddedToLibrary": "{0} se ha añadido a tu biblioteca de medios",
|
||||
"UserStoppedPlayingItemWithValues": "{0} ha terminado de reproducir {1} en {2}",
|
||||
"UserStartedPlayingItemWithValues": "{0} está reproduciendo {1} en {2}",
|
||||
"UserPolicyUpdatedWithName": "La política de usuario ha sido actualizada para {0}",
|
||||
"UserPasswordChangedWithName": "Se ha cambiado la contraseña para el usuario {0}",
|
||||
"UserOnlineFromDevice": "{0} está en línea desde {1}",
|
||||
"UserOfflineFromDevice": "{0} se ha desconectado desde {1}",
|
||||
"UserLockedOutWithName": "El usuario {0} ha sido bloqueado",
|
||||
"UserDownloadingItemWithValues": "{0} está descargando {1}",
|
||||
"UserDeletedWithName": "El usuario {0} ha sido eliminado",
|
||||
"UserCreatedWithName": "El usuario {0} ha sido creado",
|
||||
"User": "Usuario",
|
||||
"TvShows": "Programas de TV",
|
||||
"System": "Sistema",
|
||||
"SubtitleDownloadFailureFromForItem": "Falló la descarga de subtítulos desde {0} para {1}",
|
||||
"StartupEmbyServerIsLoading": "El servidor Jellyfin está cargando. Por favor, intente de nuevo pronto.",
|
||||
"ServerNameNeedsToBeRestarted": "{0} debe ser reiniciado",
|
||||
"ScheduledTaskStartedWithName": "{0} iniciado",
|
||||
"ScheduledTaskFailedWithName": "{0} falló",
|
||||
"ProviderValue": "Proveedor: {0}",
|
||||
"PluginUpdatedWithName": "{0} fue actualizado",
|
||||
"PluginUninstalledWithName": "{0} fue desinstalado",
|
||||
"PluginInstalledWithName": "{0} fue instalado",
|
||||
"Plugin": "Complemento",
|
||||
"NotificationOptionVideoPlaybackStopped": "Reproducción de video detenida",
|
||||
"NotificationOptionVideoPlayback": "Reproducción de video iniciada",
|
||||
"NotificationOptionUserLockedOut": "Usuario bloqueado",
|
||||
"NotificationOptionTaskFailed": "Falla de tarea programada",
|
||||
"NotificationOptionServerRestartRequired": "Se necesita reiniciar el servidor",
|
||||
"NotificationOptionPluginUpdateInstalled": "Actualización de complemento instalada",
|
||||
"NotificationOptionPluginUninstalled": "Complemento desinstalado",
|
||||
"NotificationOptionPluginInstalled": "Complemento instalado",
|
||||
"NotificationOptionPluginError": "Falla de complemento",
|
||||
"NotificationOptionNewLibraryContent": "Nuevo contenido agregado",
|
||||
"NotificationOptionInstallationFailed": "Falla de instalación",
|
||||
"NotificationOptionCameraImageUploaded": "Imagen de la cámara subida",
|
||||
"NotificationOptionAudioPlaybackStopped": "Reproducción de audio detenida",
|
||||
"NotificationOptionAudioPlayback": "Reproducción de audio iniciada",
|
||||
"NotificationOptionApplicationUpdateInstalled": "Actualización de la aplicación instalada",
|
||||
"NotificationOptionApplicationUpdateAvailable": "Actualización de la aplicación disponible",
|
||||
"NewVersionIsAvailable": "Una nueva versión del Servidor Jellyfin está disponible para descargar.",
|
||||
"NameSeasonUnknown": "Temporada desconocida",
|
||||
"NameSeasonNumber": "Temporada {0}",
|
||||
"NameInstallFailed": "Falló la instalación de {0}",
|
||||
"MusicVideos": "Videos musicales",
|
||||
"Music": "Música",
|
||||
"MixedContent": "Contenido mezclado",
|
||||
"MessageServerConfigurationUpdated": "Se ha actualizado la configuración del servidor",
|
||||
"MessageNamedServerConfigurationUpdatedWithValue": "Se ha actualizado la sección {0} de la configuración del servidor",
|
||||
"MessageApplicationUpdatedTo": "El servidor Jellyfin ha sido actualizado a {0}",
|
||||
"MessageApplicationUpdated": "El servidor Jellyfin ha sido actualizado",
|
||||
"Latest": "Recientes",
|
||||
"LabelIpAddressValue": "Dirección IP: {0}",
|
||||
"ItemRemovedWithName": "{0} fue removido de la biblioteca",
|
||||
"ItemAddedWithName": "{0} fue agregado a la biblioteca",
|
||||
"Inherit": "Heredar",
|
||||
"HomeVideos": "Videos caseros",
|
||||
"HeaderRecordingGroups": "Grupos de grabación",
|
||||
"HeaderCameraUploads": "Subidas desde la cámara",
|
||||
"FailedLoginAttemptWithUserName": "Intento fallido de inicio de sesión desde {0}",
|
||||
"DeviceOnlineWithName": "{0} está conectado",
|
||||
"DeviceOfflineWithName": "{0} se ha desconectado",
|
||||
"ChapterNameValue": "Capítulo {0}",
|
||||
"CameraImageUploadedFrom": "Una nueva imagen de cámara ha sido subida desde {0}",
|
||||
"AuthenticationSucceededWithUserName": "{0} autenticado con éxito",
|
||||
"Application": "Aplicación",
|
||||
"AppDeviceValues": "App: {0}, Dispositivo: {1}"
|
||||
}
|
@ -0,0 +1,99 @@
|
||||
{
|
||||
"VersionNumber": "பதிப்பு {0}",
|
||||
"ValueSpecialEpisodeName": "சிறப்பு - {0}",
|
||||
"TasksMaintenanceCategory": "பராமரிப்பு",
|
||||
"TaskCleanCache": "தற்காலிக சேமிப்பு கோப்பகத்தை சுத்தம் செய்யவும்",
|
||||
"TaskRefreshChapterImages": "அத்தியாயப் படங்களை பிரித்தெடுக்கவும்",
|
||||
"TaskRefreshPeople": "மக்களைப் புதுப்பிக்கவும்",
|
||||
"TaskCleanTranscode": "டிரான்ஸ்கோட் கோப்பகத்தை சுத்தம் செய்யவும்",
|
||||
"TaskRefreshChannelsDescription": "இணையச் சேனல் தகவல்களைப் புதுப்பிக்கிறது.",
|
||||
"System": "ஒருங்கியம்",
|
||||
"NotificationOptionTaskFailed": "திட்டமிடப்பட்ட பணி தோல்வியடைந்தது",
|
||||
"NotificationOptionPluginUpdateInstalled": "உட்செருகி புதுப்பிக்கப்பட்டது",
|
||||
"NotificationOptionPluginUninstalled": "உட்செருகி நீக்கப்பட்டது",
|
||||
"NotificationOptionPluginInstalled": "உட்செருகி நிறுவப்பட்டது",
|
||||
"NotificationOptionPluginError": "உட்செருகி செயலிழந்தது",
|
||||
"NotificationOptionCameraImageUploaded": "புகைப்படம் பதிவேற்றப்பட்டது",
|
||||
"MixedContent": "கலப்பு உள்ளடக்கங்கள்",
|
||||
"MessageServerConfigurationUpdated": "சேவையக அமைப்புகள் புதுப்பிக்கப்பட்டன",
|
||||
"MessageApplicationUpdatedTo": "ஜெல்லிஃபின் சேவையகம் {0} இற்கு புதுப்பிக்கப்பட்டது",
|
||||
"MessageApplicationUpdated": "ஜெல்லிஃபின் சேவையகம் புதுப்பிக்கப்பட்டது",
|
||||
"Inherit": "மரபரிமையாகப் பெறு",
|
||||
"HeaderRecordingGroups": "பதிவு குழுக்கள்",
|
||||
"HeaderCameraUploads": "புகைப்பட பதிவேற்றங்கள்",
|
||||
"Folders": "கோப்புறைகள்",
|
||||
"FailedLoginAttemptWithUserName": "{0} இலிருந்து உள்நுழைவு முயற்சி தோல்வியடைந்தது",
|
||||
"DeviceOnlineWithName": "{0} இணைக்கப்பட்டது",
|
||||
"DeviceOfflineWithName": "{0} துண்டிக்கப்பட்டது",
|
||||
"Collections": "தொகுப்புகள்",
|
||||
"CameraImageUploadedFrom": "{0} இலிருந்து புதிய புகைப்படம் பதிவேற்றப்பட்டது",
|
||||
"AppDeviceValues": "செயலி: {0}, சாதனம்: {1}",
|
||||
"TaskDownloadMissingSubtitles": "விடுபட்டுபோன வசன வரிகளைப் பதிவிறக்கு",
|
||||
"TaskRefreshChannels": "சேனல்களை புதுப்பி",
|
||||
"TaskUpdatePlugins": "உட்செருகிகளை புதுப்பி",
|
||||
"TaskRefreshLibrary": "மீடியா நூலகத்தை ஆராய்",
|
||||
"TasksChannelsCategory": "இணைய சேனல்கள்",
|
||||
"TasksApplicationCategory": "செயலி",
|
||||
"TasksLibraryCategory": "நூலகம்",
|
||||
"UserPolicyUpdatedWithName": "பயனர் கொள்கை {0} இற்கு புதுப்பிக்கப்பட்டுள்ளது",
|
||||
"UserPasswordChangedWithName": "{0} பயனருக்கு கடவுச்சொல் மாற்றப்பட்டுள்ளது",
|
||||
"UserLockedOutWithName": "பயனர் {0} முடக்கப்பட்டார்",
|
||||
"UserDownloadingItemWithValues": "{0} ஆல் {1} பதிவிறக்கப்படுகிறது",
|
||||
"UserDeletedWithName": "பயனர் {0} நீக்கப்பட்டார்",
|
||||
"UserCreatedWithName": "பயனர் {0} உருவாக்கப்பட்டார்",
|
||||
"User": "பயனர்",
|
||||
"TvShows": "தொலைக்காட்சித் தொடர்கள்",
|
||||
"Sync": "ஒத்திசைவு",
|
||||
"StartupEmbyServerIsLoading": "ஜெல்லிஃபின் சேவையகம் துவங்குகிறது. சிறிது நேரம் கழித்து முயற்சிக்கவும்.",
|
||||
"Songs": "பாட்டுகள்",
|
||||
"Shows": "தொடர்கள்",
|
||||
"ServerNameNeedsToBeRestarted": "{0} மறுதொடக்கம் செய்யப்பட வேண்டும்",
|
||||
"ScheduledTaskStartedWithName": "{0} துவங்கியது",
|
||||
"ScheduledTaskFailedWithName": "{0} தோல்வியடைந்தது",
|
||||
"ProviderValue": "வழங்குநர்: {0}",
|
||||
"PluginUpdatedWithName": "{0} புதுப்பிக்கப்பட்டது",
|
||||
"PluginUninstalledWithName": "{0} நீக்கப்பட்டது",
|
||||
"PluginInstalledWithName": "{0} நிறுவப்பட்டது",
|
||||
"Plugin": "உட்செருகி",
|
||||
"Playlists": "தொடர் பட்டியல்கள்",
|
||||
"Photos": "புகைப்படங்கள்",
|
||||
"NotificationOptionVideoPlaybackStopped": "நிகழ்பட ஒளிபரப்பு நிறுத்தப்பட்டது",
|
||||
"NotificationOptionVideoPlayback": "நிகழ்பட ஒளிபரப்பு துவங்கியது",
|
||||
"NotificationOptionUserLockedOut": "பயனர் கணக்கு முடக்கப்பட்டது",
|
||||
"NotificationOptionServerRestartRequired": "சேவையக மறுதொடக்கம் தேவை",
|
||||
"NotificationOptionNewLibraryContent": "புதிய உள்ளடக்கங்கள் சேர்க்கப்பட்டன",
|
||||
"NotificationOptionInstallationFailed": "நிறுவல் தோல்வியடைந்தது",
|
||||
"NotificationOptionAudioPlaybackStopped": "ஒலி இசைத்தல் நிறுத்தப்பட்டது",
|
||||
"NotificationOptionAudioPlayback": "ஒலி இசைக்கத் துவங்கியுள்ளது",
|
||||
"NotificationOptionApplicationUpdateInstalled": "செயலி புதுப்பிக்கப்பட்டது",
|
||||
"NotificationOptionApplicationUpdateAvailable": "செயலியினை புதுப்பிக்கலாம்",
|
||||
"NameSeasonUnknown": "பருவம் அறியப்படாதவை",
|
||||
"NameSeasonNumber": "பருவம் {0}",
|
||||
"NameInstallFailed": "{0} நிறுவல் தோல்வியடைந்தது",
|
||||
"MusicVideos": "இசைப்படங்கள்",
|
||||
"Music": "இசை",
|
||||
"Movies": "திரைப்படங்கள்",
|
||||
"Latest": "புதியன",
|
||||
"LabelRunningTimeValue": "ஓடும் நேரம்: {0}",
|
||||
"LabelIpAddressValue": "ஐபி முகவரி: {0}",
|
||||
"ItemRemovedWithName": "{0} நூலகத்திலிருந்து அகற்றப்பட்டது",
|
||||
"ItemAddedWithName": "{0} நூலகத்தில் சேர்க்கப்பட்டது",
|
||||
"HeaderNextUp": "அடுத்ததாக",
|
||||
"HeaderLiveTV": "நேரடித் தொலைக்காட்சி",
|
||||
"HeaderFavoriteSongs": "பிடித்த பாட்டுகள்",
|
||||
"HeaderFavoriteShows": "பிடித்த தொடர்கள்",
|
||||
"HeaderFavoriteEpisodes": "பிடித்த அத்தியாயங்கள்",
|
||||
"HeaderFavoriteArtists": "பிடித்த கலைஞர்கள்",
|
||||
"HeaderFavoriteAlbums": "பிடித்த ஆல்பங்கள்",
|
||||
"HeaderContinueWatching": "தொடர்ந்து பார்",
|
||||
"HeaderAlbumArtists": "இசைக் கலைஞர்கள்",
|
||||
"Genres": "வகைகள்",
|
||||
"Favorites": "பிடித்தவை",
|
||||
"ChapterNameValue": "அத்தியாயம் {0}",
|
||||
"Channels": "சேனல்கள்",
|
||||
"Books": "புத்தகங்கள்",
|
||||
"AuthenticationSucceededWithUserName": "{0} வெற்றிகரமாக அங்கீகரிக்கப்பட்டது",
|
||||
"Artists": "கலைஞர்கள்",
|
||||
"Application": "செயலி",
|
||||
"Albums": "ஆல்பங்கள்"
|
||||
}
|
@ -1,18 +0,0 @@
|
||||
using System.IO;
|
||||
using MediaBrowser.Model.Services;
|
||||
|
||||
namespace Emby.Server.Implementations.SocketSharp
|
||||
{
|
||||
public class HttpFile : IHttpFile
|
||||
{
|
||||
public string Name { get; set; }
|
||||
|
||||
public string FileName { get; set; }
|
||||
|
||||
public long ContentLength { get; set; }
|
||||
|
||||
public string ContentType { get; set; }
|
||||
|
||||
public Stream InputStream { get; set; }
|
||||
}
|
||||
}
|
@ -1,198 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
public sealed class HttpPostedFile : IDisposable
|
||||
{
|
||||
private string _name;
|
||||
private string _contentType;
|
||||
private Stream _stream;
|
||||
private bool _disposed = false;
|
||||
|
||||
internal HttpPostedFile(string name, string content_type, Stream base_stream, long offset, long length)
|
||||
{
|
||||
_name = name;
|
||||
_contentType = content_type;
|
||||
_stream = new ReadSubStream(base_stream, offset, length);
|
||||
}
|
||||
|
||||
public string ContentType => _contentType;
|
||||
|
||||
public int ContentLength => (int)_stream.Length;
|
||||
|
||||
public string FileName => _name;
|
||||
|
||||
public Stream InputStream => _stream;
|
||||
|
||||
/// <summary>
|
||||
/// Releases the unmanaged resources and disposes of the managed resources used.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_stream.Dispose();
|
||||
_stream = null;
|
||||
|
||||
_name = null;
|
||||
_contentType = null;
|
||||
|
||||
_disposed = true;
|
||||
}
|
||||
|
||||
private class ReadSubStream : Stream
|
||||
{
|
||||
private Stream _stream;
|
||||
private long _offset;
|
||||
private long _end;
|
||||
private long _position;
|
||||
|
||||
public ReadSubStream(Stream s, long offset, long length)
|
||||
{
|
||||
_stream = s;
|
||||
_offset = offset;
|
||||
_end = offset + length;
|
||||
_position = offset;
|
||||
}
|
||||
|
||||
public override bool CanRead => true;
|
||||
|
||||
public override bool CanSeek => true;
|
||||
|
||||
public override bool CanWrite => false;
|
||||
|
||||
public override long Length => _end - _offset;
|
||||
|
||||
public override long Position
|
||||
{
|
||||
get => _position - _offset;
|
||||
set
|
||||
{
|
||||
if (value > Length)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(value));
|
||||
}
|
||||
|
||||
_position = Seek(value, SeekOrigin.Begin);
|
||||
}
|
||||
}
|
||||
|
||||
public override void Flush()
|
||||
{
|
||||
}
|
||||
|
||||
public override int Read(byte[] buffer, int dest_offset, int count)
|
||||
{
|
||||
if (buffer == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(buffer));
|
||||
}
|
||||
|
||||
if (dest_offset < 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(dest_offset), "< 0");
|
||||
}
|
||||
|
||||
if (count < 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(count), "< 0");
|
||||
}
|
||||
|
||||
int len = buffer.Length;
|
||||
if (dest_offset > len)
|
||||
{
|
||||
throw new ArgumentException("destination offset is beyond array size", nameof(dest_offset));
|
||||
}
|
||||
|
||||
// reordered to avoid possible integer overflow
|
||||
if (dest_offset > len - count)
|
||||
{
|
||||
throw new ArgumentException("Reading would overrun buffer", nameof(count));
|
||||
}
|
||||
|
||||
if (count > _end - _position)
|
||||
{
|
||||
count = (int)(_end - _position);
|
||||
}
|
||||
|
||||
if (count <= 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
_stream.Position = _position;
|
||||
int result = _stream.Read(buffer, dest_offset, count);
|
||||
if (result > 0)
|
||||
{
|
||||
_position += result;
|
||||
}
|
||||
else
|
||||
{
|
||||
_position = _end;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public override int ReadByte()
|
||||
{
|
||||
if (_position >= _end)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
_stream.Position = _position;
|
||||
int result = _stream.ReadByte();
|
||||
if (result < 0)
|
||||
{
|
||||
_position = _end;
|
||||
}
|
||||
else
|
||||
{
|
||||
_position++;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public override long Seek(long d, SeekOrigin origin)
|
||||
{
|
||||
long real;
|
||||
switch (origin)
|
||||
{
|
||||
case SeekOrigin.Begin:
|
||||
real = _offset + d;
|
||||
break;
|
||||
case SeekOrigin.End:
|
||||
real = _end + d;
|
||||
break;
|
||||
case SeekOrigin.Current:
|
||||
real = _position + d;
|
||||
break;
|
||||
default:
|
||||
throw new ArgumentException("Unknown SeekOrigin value", nameof(origin));
|
||||
}
|
||||
|
||||
long virt = real - _offset;
|
||||
if (virt < 0 || virt > Length)
|
||||
{
|
||||
throw new ArgumentException("Invalid position", nameof(d));
|
||||
}
|
||||
|
||||
_position = _stream.Seek(real, SeekOrigin.Begin);
|
||||
return _position;
|
||||
}
|
||||
|
||||
public override void SetLength(long value)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,522 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MediaBrowser.Controller.Session;
|
||||
using MediaBrowser.Controller.SyncPlay;
|
||||
using MediaBrowser.Model.Session;
|
||||
using MediaBrowser.Model.SyncPlay;
|
||||
|
||||
namespace Emby.Server.Implementations.SyncPlay
|
||||
{
|
||||
/// <summary>
|
||||
/// Class SyncPlayController.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Class is not thread-safe, external locking is required when accessing methods.
|
||||
/// </remarks>
|
||||
public class SyncPlayController : ISyncPlayController
|
||||
{
|
||||
/// <summary>
|
||||
/// Used to filter the sessions of a group.
|
||||
/// </summary>
|
||||
private enum BroadcastType
|
||||
{
|
||||
/// <summary>
|
||||
/// All sessions will receive the message.
|
||||
/// </summary>
|
||||
AllGroup = 0,
|
||||
/// <summary>
|
||||
/// Only the specified session will receive the message.
|
||||
/// </summary>
|
||||
CurrentSession = 1,
|
||||
/// <summary>
|
||||
/// All sessions, except the current one, will receive the message.
|
||||
/// </summary>
|
||||
AllExceptCurrentSession = 2,
|
||||
/// <summary>
|
||||
/// Only sessions that are not buffering will receive the message.
|
||||
/// </summary>
|
||||
AllReady = 3
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The session manager.
|
||||
/// </summary>
|
||||
private readonly ISessionManager _sessionManager;
|
||||
|
||||
/// <summary>
|
||||
/// The SyncPlay manager.
|
||||
/// </summary>
|
||||
private readonly ISyncPlayManager _syncPlayManager;
|
||||
|
||||
/// <summary>
|
||||
/// The group to manage.
|
||||
/// </summary>
|
||||
private readonly GroupInfo _group = new GroupInfo();
|
||||
|
||||
/// <inheritdoc />
|
||||
public Guid GetGroupId() => _group.GroupId;
|
||||
|
||||
/// <inheritdoc />
|
||||
public Guid GetPlayingItemId() => _group.PlayingItem.Id;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsGroupEmpty() => _group.IsEmpty();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SyncPlayController" /> class.
|
||||
/// </summary>
|
||||
/// <param name="sessionManager">The session manager.</param>
|
||||
/// <param name="syncPlayManager">The SyncPlay manager.</param>
|
||||
public SyncPlayController(
|
||||
ISessionManager sessionManager,
|
||||
ISyncPlayManager syncPlayManager)
|
||||
{
|
||||
_sessionManager = sessionManager;
|
||||
_syncPlayManager = syncPlayManager;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts DateTime to UTC string.
|
||||
/// </summary>
|
||||
/// <param name="date">The date to convert.</param>
|
||||
/// <value>The UTC string.</value>
|
||||
private string DateToUTCString(DateTime date)
|
||||
{
|
||||
return date.ToUniversalTime().ToString("o");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Filters sessions of this group.
|
||||
/// </summary>
|
||||
/// <param name="from">The current session.</param>
|
||||
/// <param name="type">The filtering type.</param>
|
||||
/// <value>The array of sessions matching the filter.</value>
|
||||
private SessionInfo[] FilterSessions(SessionInfo from, BroadcastType type)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case BroadcastType.CurrentSession:
|
||||
return new SessionInfo[] { from };
|
||||
case BroadcastType.AllGroup:
|
||||
return _group.Participants.Values.Select(
|
||||
session => session.Session
|
||||
).ToArray();
|
||||
case BroadcastType.AllExceptCurrentSession:
|
||||
return _group.Participants.Values.Select(
|
||||
session => session.Session
|
||||
).Where(
|
||||
session => !session.Id.Equals(from.Id)
|
||||
).ToArray();
|
||||
case BroadcastType.AllReady:
|
||||
return _group.Participants.Values.Where(
|
||||
session => !session.IsBuffering
|
||||
).Select(
|
||||
session => session.Session
|
||||
).ToArray();
|
||||
default:
|
||||
return Array.Empty<SessionInfo>();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a GroupUpdate message to the interested sessions.
|
||||
/// </summary>
|
||||
/// <param name="from">The current session.</param>
|
||||
/// <param name="type">The filtering type.</param>
|
||||
/// <param name="message">The message to send.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <value>The task.</value>
|
||||
private Task SendGroupUpdate<T>(SessionInfo from, BroadcastType type, GroupUpdate<T> message, CancellationToken cancellationToken)
|
||||
{
|
||||
IEnumerable<Task> GetTasks()
|
||||
{
|
||||
SessionInfo[] sessions = FilterSessions(from, type);
|
||||
foreach (var session in sessions)
|
||||
{
|
||||
yield return _sessionManager.SendSyncPlayGroupUpdate(session.Id.ToString(), message, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
return Task.WhenAll(GetTasks());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a playback command to the interested sessions.
|
||||
/// </summary>
|
||||
/// <param name="from">The current session.</param>
|
||||
/// <param name="type">The filtering type.</param>
|
||||
/// <param name="message">The message to send.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <value>The task.</value>
|
||||
private Task SendCommand(SessionInfo from, BroadcastType type, SendCommand message, CancellationToken cancellationToken)
|
||||
{
|
||||
IEnumerable<Task> GetTasks()
|
||||
{
|
||||
SessionInfo[] sessions = FilterSessions(from, type);
|
||||
foreach (var session in sessions)
|
||||
{
|
||||
yield return _sessionManager.SendSyncPlayCommand(session.Id.ToString(), message, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
return Task.WhenAll(GetTasks());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds a new playback command with some default values.
|
||||
/// </summary>
|
||||
/// <param name="type">The command type.</param>
|
||||
/// <value>The SendCommand.</value>
|
||||
private SendCommand NewSyncPlayCommand(SendCommandType type)
|
||||
{
|
||||
return new SendCommand()
|
||||
{
|
||||
GroupId = _group.GroupId.ToString(),
|
||||
Command = type,
|
||||
PositionTicks = _group.PositionTicks,
|
||||
When = DateToUTCString(_group.LastActivity),
|
||||
EmittedAt = DateToUTCString(DateTime.UtcNow)
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds a new group update message.
|
||||
/// </summary>
|
||||
/// <param name="type">The update type.</param>
|
||||
/// <param name="data">The data to send.</param>
|
||||
/// <value>The GroupUpdate.</value>
|
||||
private GroupUpdate<T> NewSyncPlayGroupUpdate<T>(GroupUpdateType type, T data)
|
||||
{
|
||||
return new GroupUpdate<T>()
|
||||
{
|
||||
GroupId = _group.GroupId.ToString(),
|
||||
Type = type,
|
||||
Data = data
|
||||
};
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void InitGroup(SessionInfo session, CancellationToken cancellationToken)
|
||||
{
|
||||
_group.AddSession(session);
|
||||
_syncPlayManager.AddSessionToGroup(session, this);
|
||||
|
||||
_group.PlayingItem = session.FullNowPlayingItem;
|
||||
_group.IsPaused = true;
|
||||
_group.PositionTicks = session.PlayState.PositionTicks ?? 0;
|
||||
_group.LastActivity = DateTime.UtcNow;
|
||||
|
||||
var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupJoined, DateToUTCString(DateTime.UtcNow));
|
||||
SendGroupUpdate(session, BroadcastType.CurrentSession, updateSession, cancellationToken);
|
||||
var pauseCommand = NewSyncPlayCommand(SendCommandType.Pause);
|
||||
SendCommand(session, BroadcastType.CurrentSession, pauseCommand, cancellationToken);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void SessionJoin(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (session.NowPlayingItem?.Id == _group.PlayingItem.Id && request.PlayingItemId == _group.PlayingItem.Id)
|
||||
{
|
||||
_group.AddSession(session);
|
||||
_syncPlayManager.AddSessionToGroup(session, this);
|
||||
|
||||
var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupJoined, DateToUTCString(DateTime.UtcNow));
|
||||
SendGroupUpdate(session, BroadcastType.CurrentSession, updateSession, cancellationToken);
|
||||
|
||||
var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.UserJoined, session.UserName);
|
||||
SendGroupUpdate(session, BroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken);
|
||||
|
||||
// Client join and play, syncing will happen client side
|
||||
if (!_group.IsPaused)
|
||||
{
|
||||
var playCommand = NewSyncPlayCommand(SendCommandType.Play);
|
||||
SendCommand(session, BroadcastType.CurrentSession, playCommand, cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
var pauseCommand = NewSyncPlayCommand(SendCommandType.Pause);
|
||||
SendCommand(session, BroadcastType.CurrentSession, pauseCommand, cancellationToken);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var playRequest = new PlayRequest();
|
||||
playRequest.ItemIds = new Guid[] { _group.PlayingItem.Id };
|
||||
playRequest.StartPositionTicks = _group.PositionTicks;
|
||||
var update = NewSyncPlayGroupUpdate(GroupUpdateType.PrepareSession, playRequest);
|
||||
SendGroupUpdate(session, BroadcastType.CurrentSession, update, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void SessionLeave(SessionInfo session, CancellationToken cancellationToken)
|
||||
{
|
||||
_group.RemoveSession(session);
|
||||
_syncPlayManager.RemoveSessionFromGroup(session, this);
|
||||
|
||||
var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupLeft, _group.PositionTicks);
|
||||
SendGroupUpdate(session, BroadcastType.CurrentSession, updateSession, cancellationToken);
|
||||
|
||||
var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.UserLeft, session.UserName);
|
||||
SendGroupUpdate(session, BroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void HandleRequest(SessionInfo session, PlaybackRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// The server's job is to mantain a consistent state to which clients refer to,
|
||||
// as also to notify clients of state changes.
|
||||
// The actual syncing of media playback happens client side.
|
||||
// Clients are aware of the server's time and use it to sync.
|
||||
switch (request.Type)
|
||||
{
|
||||
case PlaybackRequestType.Play:
|
||||
HandlePlayRequest(session, request, cancellationToken);
|
||||
break;
|
||||
case PlaybackRequestType.Pause:
|
||||
HandlePauseRequest(session, request, cancellationToken);
|
||||
break;
|
||||
case PlaybackRequestType.Seek:
|
||||
HandleSeekRequest(session, request, cancellationToken);
|
||||
break;
|
||||
case PlaybackRequestType.Buffering:
|
||||
HandleBufferingRequest(session, request, cancellationToken);
|
||||
break;
|
||||
case PlaybackRequestType.BufferingDone:
|
||||
HandleBufferingDoneRequest(session, request, cancellationToken);
|
||||
break;
|
||||
case PlaybackRequestType.UpdatePing:
|
||||
HandlePingUpdateRequest(session, request);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles a play action requested by a session.
|
||||
/// </summary>
|
||||
/// <param name="session">The session.</param>
|
||||
/// <param name="request">The play action.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
private void HandlePlayRequest(SessionInfo session, PlaybackRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_group.IsPaused)
|
||||
{
|
||||
// Pick a suitable time that accounts for latency
|
||||
var delay = _group.GetHighestPing() * 2;
|
||||
delay = delay < _group.DefaulPing ? _group.DefaulPing : delay;
|
||||
|
||||
// Unpause group and set starting point in future
|
||||
// Clients will start playback at LastActivity (datetime) from PositionTicks (playback position)
|
||||
// The added delay does not guarantee, of course, that the command will be received in time
|
||||
// Playback synchronization will mainly happen client side
|
||||
_group.IsPaused = false;
|
||||
_group.LastActivity = DateTime.UtcNow.AddMilliseconds(
|
||||
delay
|
||||
);
|
||||
|
||||
var command = NewSyncPlayCommand(SendCommandType.Play);
|
||||
SendCommand(session, BroadcastType.AllGroup, command, cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Client got lost, sending current state
|
||||
var command = NewSyncPlayCommand(SendCommandType.Play);
|
||||
SendCommand(session, BroadcastType.CurrentSession, command, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles a pause action requested by a session.
|
||||
/// </summary>
|
||||
/// <param name="session">The session.</param>
|
||||
/// <param name="request">The pause action.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
private void HandlePauseRequest(SessionInfo session, PlaybackRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!_group.IsPaused)
|
||||
{
|
||||
// Pause group and compute the media playback position
|
||||
_group.IsPaused = true;
|
||||
var currentTime = DateTime.UtcNow;
|
||||
var elapsedTime = currentTime - _group.LastActivity;
|
||||
_group.LastActivity = currentTime;
|
||||
// Seek only if playback actually started
|
||||
// (a pause request may be issued during the delay added to account for latency)
|
||||
_group.PositionTicks += elapsedTime.Ticks > 0 ? elapsedTime.Ticks : 0;
|
||||
|
||||
var command = NewSyncPlayCommand(SendCommandType.Pause);
|
||||
SendCommand(session, BroadcastType.AllGroup, command, cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Client got lost, sending current state
|
||||
var command = NewSyncPlayCommand(SendCommandType.Pause);
|
||||
SendCommand(session, BroadcastType.CurrentSession, command, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles a seek action requested by a session.
|
||||
/// </summary>
|
||||
/// <param name="session">The session.</param>
|
||||
/// <param name="request">The seek action.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
private void HandleSeekRequest(SessionInfo session, PlaybackRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// Sanitize PositionTicks
|
||||
var ticks = SanitizePositionTicks(request.PositionTicks);
|
||||
|
||||
// Pause and seek
|
||||
_group.IsPaused = true;
|
||||
_group.PositionTicks = ticks;
|
||||
_group.LastActivity = DateTime.UtcNow;
|
||||
|
||||
var command = NewSyncPlayCommand(SendCommandType.Seek);
|
||||
SendCommand(session, BroadcastType.AllGroup, command, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles a buffering action requested by a session.
|
||||
/// </summary>
|
||||
/// <param name="session">The session.</param>
|
||||
/// <param name="request">The buffering action.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
private void HandleBufferingRequest(SessionInfo session, PlaybackRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!_group.IsPaused)
|
||||
{
|
||||
// Pause group and compute the media playback position
|
||||
_group.IsPaused = true;
|
||||
var currentTime = DateTime.UtcNow;
|
||||
var elapsedTime = currentTime - _group.LastActivity;
|
||||
_group.LastActivity = currentTime;
|
||||
_group.PositionTicks += elapsedTime.Ticks > 0 ? elapsedTime.Ticks : 0;
|
||||
|
||||
_group.SetBuffering(session, true);
|
||||
|
||||
// Send pause command to all non-buffering sessions
|
||||
var command = NewSyncPlayCommand(SendCommandType.Pause);
|
||||
SendCommand(session, BroadcastType.AllReady, command, cancellationToken);
|
||||
|
||||
var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.GroupWait, session.UserName);
|
||||
SendGroupUpdate(session, BroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Client got lost, sending current state
|
||||
var command = NewSyncPlayCommand(SendCommandType.Pause);
|
||||
SendCommand(session, BroadcastType.CurrentSession, command, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles a buffering-done action requested by a session.
|
||||
/// </summary>
|
||||
/// <param name="session">The session.</param>
|
||||
/// <param name="request">The buffering-done action.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
private void HandleBufferingDoneRequest(SessionInfo session, PlaybackRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_group.IsPaused)
|
||||
{
|
||||
_group.SetBuffering(session, false);
|
||||
|
||||
var requestTicks = SanitizePositionTicks(request.PositionTicks);
|
||||
|
||||
var when = request.When ?? DateTime.UtcNow;
|
||||
var currentTime = DateTime.UtcNow;
|
||||
var elapsedTime = currentTime - when;
|
||||
var clientPosition = TimeSpan.FromTicks(requestTicks) + elapsedTime;
|
||||
var delay = _group.PositionTicks - clientPosition.Ticks;
|
||||
|
||||
if (_group.IsBuffering())
|
||||
{
|
||||
// Others are still buffering, tell this client to pause when ready
|
||||
var command = NewSyncPlayCommand(SendCommandType.Pause);
|
||||
var pauseAtTime = currentTime.AddMilliseconds(delay);
|
||||
command.When = DateToUTCString(pauseAtTime);
|
||||
SendCommand(session, BroadcastType.CurrentSession, command, cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Let other clients resume as soon as the buffering client catches up
|
||||
_group.IsPaused = false;
|
||||
|
||||
if (delay > _group.GetHighestPing() * 2)
|
||||
{
|
||||
// Client that was buffering is recovering, notifying others to resume
|
||||
_group.LastActivity = currentTime.AddMilliseconds(
|
||||
delay
|
||||
);
|
||||
var command = NewSyncPlayCommand(SendCommandType.Play);
|
||||
SendCommand(session, BroadcastType.AllExceptCurrentSession, command, cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Client, that was buffering, resumed playback but did not update others in time
|
||||
delay = _group.GetHighestPing() * 2;
|
||||
delay = delay < _group.DefaulPing ? _group.DefaulPing : delay;
|
||||
|
||||
_group.LastActivity = currentTime.AddMilliseconds(
|
||||
delay
|
||||
);
|
||||
|
||||
var command = NewSyncPlayCommand(SendCommandType.Play);
|
||||
SendCommand(session, BroadcastType.AllGroup, command, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Group was not waiting, make sure client has latest state
|
||||
var command = NewSyncPlayCommand(SendCommandType.Play);
|
||||
SendCommand(session, BroadcastType.CurrentSession, command, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sanitizes the PositionTicks, considers the current playing item when available.
|
||||
/// </summary>
|
||||
/// <param name="positionTicks">The PositionTicks.</param>
|
||||
/// <value>The sanitized PositionTicks.</value>
|
||||
private long SanitizePositionTicks(long? positionTicks)
|
||||
{
|
||||
var ticks = positionTicks ?? 0;
|
||||
ticks = ticks >= 0 ? ticks : 0;
|
||||
if (_group.PlayingItem != null)
|
||||
{
|
||||
var runTimeTicks = _group.PlayingItem.RunTimeTicks ?? 0;
|
||||
ticks = ticks > runTimeTicks ? runTimeTicks : ticks;
|
||||
}
|
||||
|
||||
return ticks;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates ping of a session.
|
||||
/// </summary>
|
||||
/// <param name="session">The session.</param>
|
||||
/// <param name="request">The update.</param>
|
||||
private void HandlePingUpdateRequest(SessionInfo session, PlaybackRequest request)
|
||||
{
|
||||
// Collected pings are used to account for network latency when unpausing playback
|
||||
_group.UpdatePing(session, request.Ping ?? _group.DefaulPing);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public GroupInfoView GetInfo()
|
||||
{
|
||||
return new GroupInfoView()
|
||||
{
|
||||
GroupId = GetGroupId().ToString(),
|
||||
PlayingItemName = _group.PlayingItem.Name,
|
||||
PlayingItemId = _group.PlayingItem.Id.ToString(),
|
||||
PositionTicks = _group.PositionTicks,
|
||||
Participants = _group.Participants.Values.Select(session => session.Session.UserName).Distinct().ToList()
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,405 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using MediaBrowser.Controller.Entities;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Controller.Session;
|
||||
using MediaBrowser.Controller.SyncPlay;
|
||||
using MediaBrowser.Model.Configuration;
|
||||
using MediaBrowser.Model.SyncPlay;
|
||||
|
||||
namespace Emby.Server.Implementations.SyncPlay
|
||||
{
|
||||
/// <summary>
|
||||
/// Class SyncPlayManager.
|
||||
/// </summary>
|
||||
public class SyncPlayManager : ISyncPlayManager, IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// The logger.
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
|
||||
/// <summary>
|
||||
/// The user manager.
|
||||
/// </summary>
|
||||
private readonly IUserManager _userManager;
|
||||
|
||||
/// <summary>
|
||||
/// The session manager.
|
||||
/// </summary>
|
||||
private readonly ISessionManager _sessionManager;
|
||||
|
||||
/// <summary>
|
||||
/// The library manager.
|
||||
/// </summary>
|
||||
private readonly ILibraryManager _libraryManager;
|
||||
|
||||
/// <summary>
|
||||
/// The map between sessions and groups.
|
||||
/// </summary>
|
||||
private readonly Dictionary<string, ISyncPlayController> _sessionToGroupMap =
|
||||
new Dictionary<string, ISyncPlayController>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// The groups.
|
||||
/// </summary>
|
||||
private readonly Dictionary<Guid, ISyncPlayController> _groups =
|
||||
new Dictionary<Guid, ISyncPlayController>();
|
||||
|
||||
/// <summary>
|
||||
/// Lock used for accesing any group.
|
||||
/// </summary>
|
||||
private readonly object _groupsLock = new object();
|
||||
|
||||
private bool _disposed = false;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SyncPlayManager" /> class.
|
||||
/// </summary>
|
||||
/// <param name="logger">The logger.</param>
|
||||
/// <param name="userManager">The user manager.</param>
|
||||
/// <param name="sessionManager">The session manager.</param>
|
||||
/// <param name="libraryManager">The library manager.</param>
|
||||
public SyncPlayManager(
|
||||
ILogger<SyncPlayManager> logger,
|
||||
IUserManager userManager,
|
||||
ISessionManager sessionManager,
|
||||
ILibraryManager libraryManager)
|
||||
{
|
||||
_logger = logger;
|
||||
_userManager = userManager;
|
||||
_sessionManager = sessionManager;
|
||||
_libraryManager = libraryManager;
|
||||
|
||||
_sessionManager.SessionEnded += OnSessionManagerSessionEnded;
|
||||
_sessionManager.PlaybackStopped += OnSessionManagerPlaybackStopped;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets all groups.
|
||||
/// </summary>
|
||||
/// <value>All groups.</value>
|
||||
public IEnumerable<ISyncPlayController> Groups => _groups.Values;
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases unmanaged and optionally managed resources.
|
||||
/// </summary>
|
||||
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_sessionManager.SessionEnded -= OnSessionManagerSessionEnded;
|
||||
_sessionManager.PlaybackStopped -= OnSessionManagerPlaybackStopped;
|
||||
|
||||
_disposed = true;
|
||||
}
|
||||
|
||||
private void CheckDisposed()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
throw new ObjectDisposedException(GetType().Name);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnSessionManagerSessionEnded(object sender, SessionEventArgs e)
|
||||
{
|
||||
var session = e.SessionInfo;
|
||||
if (!IsSessionInGroup(session))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
LeaveGroup(session, CancellationToken.None);
|
||||
}
|
||||
|
||||
private void OnSessionManagerPlaybackStopped(object sender, PlaybackStopEventArgs e)
|
||||
{
|
||||
var session = e.Session;
|
||||
if (!IsSessionInGroup(session))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
LeaveGroup(session, CancellationToken.None);
|
||||
}
|
||||
|
||||
private bool IsSessionInGroup(SessionInfo session)
|
||||
{
|
||||
return _sessionToGroupMap.ContainsKey(session.Id);
|
||||
}
|
||||
|
||||
private bool HasAccessToItem(User user, Guid itemId)
|
||||
{
|
||||
var item = _libraryManager.GetItemById(itemId);
|
||||
|
||||
// Check ParentalRating access
|
||||
var hasParentalRatingAccess = true;
|
||||
if (user.Policy.MaxParentalRating.HasValue)
|
||||
{
|
||||
hasParentalRatingAccess = item.InheritedParentalRatingValue <= user.Policy.MaxParentalRating;
|
||||
}
|
||||
|
||||
if (!user.Policy.EnableAllFolders && hasParentalRatingAccess)
|
||||
{
|
||||
var collections = _libraryManager.GetCollectionFolders(item).Select(
|
||||
folder => folder.Id.ToString("N", CultureInfo.InvariantCulture)
|
||||
);
|
||||
var intersect = collections.Intersect(user.Policy.EnabledFolders);
|
||||
return intersect.Any();
|
||||
}
|
||||
else
|
||||
{
|
||||
return hasParentalRatingAccess;
|
||||
}
|
||||
}
|
||||
|
||||
private Guid? GetSessionGroup(SessionInfo session)
|
||||
{
|
||||
ISyncPlayController group;
|
||||
_sessionToGroupMap.TryGetValue(session.Id, out group);
|
||||
if (group != null)
|
||||
{
|
||||
return group.GetGroupId();
|
||||
}
|
||||
else
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void NewGroup(SessionInfo session, CancellationToken cancellationToken)
|
||||
{
|
||||
var user = _userManager.GetUserById(session.UserId);
|
||||
|
||||
if (user.Policy.SyncPlayAccess != SyncPlayAccess.CreateAndJoinGroups)
|
||||
{
|
||||
_logger.LogWarning("NewGroup: {0} does not have permission to create groups.", session.Id);
|
||||
|
||||
var error = new GroupUpdate<string>()
|
||||
{
|
||||
Type = GroupUpdateType.CreateGroupDenied
|
||||
};
|
||||
_sessionManager.SendSyncPlayGroupUpdate(session.Id.ToString(), error, CancellationToken.None);
|
||||
return;
|
||||
}
|
||||
|
||||
lock (_groupsLock)
|
||||
{
|
||||
if (IsSessionInGroup(session))
|
||||
{
|
||||
LeaveGroup(session, cancellationToken);
|
||||
}
|
||||
|
||||
var group = new SyncPlayController(_sessionManager, this);
|
||||
_groups[group.GetGroupId()] = group;
|
||||
|
||||
group.InitGroup(session, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void JoinGroup(SessionInfo session, Guid groupId, JoinGroupRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
var user = _userManager.GetUserById(session.UserId);
|
||||
|
||||
if (user.Policy.SyncPlayAccess == SyncPlayAccess.None)
|
||||
{
|
||||
_logger.LogWarning("JoinGroup: {0} does not have access to SyncPlay.", session.Id);
|
||||
|
||||
var error = new GroupUpdate<string>()
|
||||
{
|
||||
Type = GroupUpdateType.JoinGroupDenied
|
||||
};
|
||||
_sessionManager.SendSyncPlayGroupUpdate(session.Id.ToString(), error, CancellationToken.None);
|
||||
return;
|
||||
}
|
||||
|
||||
lock (_groupsLock)
|
||||
{
|
||||
ISyncPlayController group;
|
||||
_groups.TryGetValue(groupId, out group);
|
||||
|
||||
if (group == null)
|
||||
{
|
||||
_logger.LogWarning("JoinGroup: {0} tried to join group {0} that does not exist.", session.Id, groupId);
|
||||
|
||||
var error = new GroupUpdate<string>()
|
||||
{
|
||||
Type = GroupUpdateType.GroupDoesNotExist
|
||||
};
|
||||
_sessionManager.SendSyncPlayGroupUpdate(session.Id.ToString(), error, CancellationToken.None);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!HasAccessToItem(user, group.GetPlayingItemId()))
|
||||
{
|
||||
_logger.LogWarning("JoinGroup: {0} does not have access to {1}.", session.Id, group.GetPlayingItemId());
|
||||
|
||||
var error = new GroupUpdate<string>()
|
||||
{
|
||||
GroupId = group.GetGroupId().ToString(),
|
||||
Type = GroupUpdateType.LibraryAccessDenied
|
||||
};
|
||||
_sessionManager.SendSyncPlayGroupUpdate(session.Id.ToString(), error, CancellationToken.None);
|
||||
return;
|
||||
}
|
||||
|
||||
if (IsSessionInGroup(session))
|
||||
{
|
||||
if (GetSessionGroup(session).Equals(groupId))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
LeaveGroup(session, cancellationToken);
|
||||
}
|
||||
|
||||
group.SessionJoin(session, request, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void LeaveGroup(SessionInfo session, CancellationToken cancellationToken)
|
||||
{
|
||||
// TODO: determine what happens to users that are in a group and get their permissions revoked
|
||||
lock (_groupsLock)
|
||||
{
|
||||
ISyncPlayController group;
|
||||
_sessionToGroupMap.TryGetValue(session.Id, out group);
|
||||
|
||||
if (group == null)
|
||||
{
|
||||
_logger.LogWarning("LeaveGroup: {0} does not belong to any group.", session.Id);
|
||||
|
||||
var error = new GroupUpdate<string>()
|
||||
{
|
||||
Type = GroupUpdateType.NotInGroup
|
||||
};
|
||||
_sessionManager.SendSyncPlayGroupUpdate(session.Id.ToString(), error, CancellationToken.None);
|
||||
return;
|
||||
}
|
||||
|
||||
group.SessionLeave(session, cancellationToken);
|
||||
|
||||
if (group.IsGroupEmpty())
|
||||
{
|
||||
_logger.LogInformation("LeaveGroup: removing empty group {0}.", group.GetGroupId());
|
||||
_groups.Remove(group.GetGroupId(), out _);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public List<GroupInfoView> ListGroups(SessionInfo session, Guid filterItemId)
|
||||
{
|
||||
var user = _userManager.GetUserById(session.UserId);
|
||||
|
||||
if (user.Policy.SyncPlayAccess == SyncPlayAccess.None)
|
||||
{
|
||||
return new List<GroupInfoView>();
|
||||
}
|
||||
|
||||
// Filter by item if requested
|
||||
if (!filterItemId.Equals(Guid.Empty))
|
||||
{
|
||||
return _groups.Values.Where(
|
||||
group => group.GetPlayingItemId().Equals(filterItemId) && HasAccessToItem(user, group.GetPlayingItemId())
|
||||
).Select(
|
||||
group => group.GetInfo()
|
||||
).ToList();
|
||||
}
|
||||
// Otherwise show all available groups
|
||||
else
|
||||
{
|
||||
return _groups.Values.Where(
|
||||
group => HasAccessToItem(user, group.GetPlayingItemId())
|
||||
).Select(
|
||||
group => group.GetInfo()
|
||||
).ToList();
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void HandleRequest(SessionInfo session, PlaybackRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
var user = _userManager.GetUserById(session.UserId);
|
||||
|
||||
if (user.Policy.SyncPlayAccess == SyncPlayAccess.None)
|
||||
{
|
||||
_logger.LogWarning("HandleRequest: {0} does not have access to SyncPlay.", session.Id);
|
||||
|
||||
var error = new GroupUpdate<string>()
|
||||
{
|
||||
Type = GroupUpdateType.JoinGroupDenied
|
||||
};
|
||||
_sessionManager.SendSyncPlayGroupUpdate(session.Id.ToString(), error, CancellationToken.None);
|
||||
return;
|
||||
}
|
||||
|
||||
lock (_groupsLock)
|
||||
{
|
||||
ISyncPlayController group;
|
||||
_sessionToGroupMap.TryGetValue(session.Id, out group);
|
||||
|
||||
if (group == null)
|
||||
{
|
||||
_logger.LogWarning("HandleRequest: {0} does not belong to any group.", session.Id);
|
||||
|
||||
var error = new GroupUpdate<string>()
|
||||
{
|
||||
Type = GroupUpdateType.NotInGroup
|
||||
};
|
||||
_sessionManager.SendSyncPlayGroupUpdate(session.Id.ToString(), error, CancellationToken.None);
|
||||
return;
|
||||
}
|
||||
|
||||
group.HandleRequest(session, request, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void AddSessionToGroup(SessionInfo session, ISyncPlayController group)
|
||||
{
|
||||
if (IsSessionInGroup(session))
|
||||
{
|
||||
throw new InvalidOperationException("Session in other group already!");
|
||||
}
|
||||
|
||||
_sessionToGroupMap[session.Id] = group;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void RemoveSessionFromGroup(SessionInfo session, ISyncPlayController group)
|
||||
{
|
||||
if (!IsSessionInGroup(session))
|
||||
{
|
||||
throw new InvalidOperationException("Session not in any group!");
|
||||
}
|
||||
|
||||
ISyncPlayController tempGroup;
|
||||
_sessionToGroupMap.Remove(session.Id, out tempGroup);
|
||||
|
||||
if (!tempGroup.GetGroupId().Equals(group.GetGroupId()))
|
||||
{
|
||||
throw new InvalidOperationException("Session was in wrong group!");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue