jellyfin/Emby.Server.Implementations/Devices/DeviceManager.cs

504 lines
16 KiB
C#
Raw Normal View History

2014-10-11 20:38:13 +00:00
using MediaBrowser.Common.Configuration;
2014-10-13 20:14:53 +00:00
using MediaBrowser.Common.Events;
2015-05-26 15:31:50 +00:00
using MediaBrowser.Common.Net;
2014-10-11 20:38:13 +00:00
using MediaBrowser.Controller.Devices;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Devices;
2014-10-13 20:14:53 +00:00
using MediaBrowser.Model.Events;
2014-12-29 20:18:48 +00:00
using MediaBrowser.Model.Extensions;
2014-10-13 20:14:53 +00:00
using MediaBrowser.Model.Logging;
2015-09-10 18:28:22 +00:00
using MediaBrowser.Model.Net;
2014-12-13 03:56:30 +00:00
using MediaBrowser.Model.Querying;
2014-10-11 20:38:13 +00:00
using MediaBrowser.Model.Session;
2015-01-02 05:36:27 +00:00
using MediaBrowser.Model.Users;
2014-10-11 20:38:13 +00:00
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
2016-10-25 19:02:04 +00:00
using MediaBrowser.Model.IO;
2015-11-03 04:34:47 +00:00
using MediaBrowser.Controller.Configuration;
2018-09-12 17:26:21 +00:00
using MediaBrowser.Controller.Entities;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Controller.Security;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Common.Extensions;
2014-10-11 20:38:13 +00:00
2016-11-03 07:14:14 +00:00
namespace Emby.Server.Implementations.Devices
2014-10-11 20:38:13 +00:00
{
public class DeviceManager : IDeviceManager
{
2018-09-12 17:26:21 +00:00
private readonly IJsonSerializer _json;
2014-10-11 20:38:13 +00:00
private readonly IUserManager _userManager;
private readonly IFileSystem _fileSystem;
private readonly ILibraryMonitor _libraryMonitor;
2015-11-03 04:34:47 +00:00
private readonly IServerConfigurationManager _config;
2014-10-13 20:14:53 +00:00
private readonly ILogger _logger;
2015-05-26 15:31:50 +00:00
private readonly INetworkManager _network;
2018-09-12 17:26:21 +00:00
private readonly ILibraryManager _libraryManager;
private readonly ILocalizationManager _localizationManager;
2014-10-13 20:14:53 +00:00
2018-09-12 17:26:21 +00:00
private readonly IAuthenticationRepository _authRepo;
public event EventHandler<GenericEventArgs<Tuple<string, DeviceOptions>>> DeviceOptionsUpdated;
public event EventHandler<GenericEventArgs<CameraImageUploadInfo>> CameraImageUploaded;
2018-09-12 17:26:21 +00:00
private readonly object _cameraUploadSyncLock = new object();
private readonly object _capabilitiesSyncLock = new object();
2014-12-13 03:56:30 +00:00
2018-09-12 17:26:21 +00:00
public DeviceManager(IAuthenticationRepository authRepo, IJsonSerializer json, ILibraryManager libraryManager, ILocalizationManager localizationManager, IUserManager userManager, IFileSystem fileSystem, ILibraryMonitor libraryMonitor, IServerConfigurationManager config, ILogger logger, INetworkManager network)
2014-10-11 20:38:13 +00:00
{
2018-09-12 17:26:21 +00:00
_json = json;
2014-10-11 20:38:13 +00:00
_userManager = userManager;
_fileSystem = fileSystem;
_libraryMonitor = libraryMonitor;
_config = config;
2014-10-13 20:14:53 +00:00
_logger = logger;
2015-05-26 15:31:50 +00:00
_network = network;
2018-09-12 17:26:21 +00:00
_libraryManager = libraryManager;
_localizationManager = localizationManager;
_authRepo = authRepo;
2014-10-11 20:38:13 +00:00
}
2018-09-12 17:26:21 +00:00
private Dictionary<string, ClientCapabilities> _capabilitiesCache = new Dictionary<string, ClientCapabilities>(StringComparer.OrdinalIgnoreCase);
public void SaveCapabilities(string deviceId, ClientCapabilities capabilities)
2014-10-11 20:38:13 +00:00
{
2018-09-12 17:26:21 +00:00
var path = Path.Combine(GetDevicePath(deviceId), "capabilities.json");
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
2018-09-12 17:26:21 +00:00
lock (_capabilitiesSyncLock)
2014-10-11 20:38:13 +00:00
{
2018-09-12 17:26:21 +00:00
_capabilitiesCache[deviceId] = capabilities;
2014-10-11 20:38:13 +00:00
2018-09-12 17:26:21 +00:00
_json.SerializeToFile(capabilities, path);
}
}
2014-10-11 20:38:13 +00:00
2018-09-12 17:26:21 +00:00
public void UpdateDeviceOptions(string deviceId, DeviceOptions options)
{
_authRepo.UpdateDeviceOptions(deviceId, options);
2014-10-11 20:38:13 +00:00
2018-09-12 17:26:21 +00:00
if (DeviceOptionsUpdated != null)
{
DeviceOptionsUpdated(this, new GenericEventArgs<Tuple<string, DeviceOptions>>()
{
Argument = new Tuple<string, DeviceOptions>(deviceId, options)
});
2014-10-11 20:38:13 +00:00
}
2018-09-12 17:26:21 +00:00
}
2014-10-11 20:38:13 +00:00
2018-09-12 17:26:21 +00:00
public DeviceOptions GetDeviceOptions(string deviceId)
{
return _authRepo.GetDeviceOptions(deviceId);
}
2014-10-11 20:38:13 +00:00
2018-09-12 17:26:21 +00:00
public ClientCapabilities GetCapabilities(string id)
{
lock (_capabilitiesSyncLock)
{
ClientCapabilities result;
if (_capabilitiesCache.TryGetValue(id, out result))
{
return result;
}
2017-10-13 19:18:05 +00:00
2018-09-12 17:26:21 +00:00
var path = Path.Combine(GetDevicePath(id), "capabilities.json");
try
{
return _json.DeserializeFromFile<ClientCapabilities>(path) ?? new ClientCapabilities();
}
catch
{
}
}
2014-10-13 20:14:53 +00:00
2018-09-12 17:26:21 +00:00
return new ClientCapabilities();
2014-10-11 20:38:13 +00:00
}
2018-09-12 17:26:21 +00:00
public DeviceInfo GetDevice(string id)
2014-10-11 20:38:13 +00:00
{
2018-09-12 17:26:21 +00:00
return GetDevice(id, true);
2014-10-11 20:38:13 +00:00
}
2018-09-12 17:26:21 +00:00
private DeviceInfo GetDevice(string id, bool includeCapabilities)
2014-10-11 20:38:13 +00:00
{
2018-09-12 17:26:21 +00:00
var session = _authRepo.Get(new AuthenticationInfoQuery
{
DeviceId = id
2014-10-11 20:38:13 +00:00
2018-09-12 17:26:21 +00:00
}).Items.FirstOrDefault();
var device = session == null ? null : ToDeviceInfo(session);
return device;
2014-10-11 20:38:13 +00:00
}
2014-12-13 03:56:30 +00:00
public QueryResult<DeviceInfo> GetDevices(DeviceQuery query)
2014-10-11 20:38:13 +00:00
{
2018-09-12 17:26:21 +00:00
var sessions = _authRepo.Get(new AuthenticationInfoQuery
{
//UserId = query.UserId
HasUser = true
}).Items;
2014-12-13 03:56:30 +00:00
2014-12-15 05:49:04 +00:00
if (query.SupportsSync.HasValue)
{
var val = query.SupportsSync.Value;
2018-09-12 17:26:21 +00:00
sessions = sessions.Where(i => GetCapabilities(i.DeviceId).SupportsSync == val).ToArray();
2014-12-15 05:49:04 +00:00
}
2018-09-12 17:26:21 +00:00
if (!query.UserId.Equals(Guid.Empty))
2014-12-13 03:56:30 +00:00
{
2018-09-12 17:26:21 +00:00
var user = _userManager.GetUserById(query.UserId);
2014-12-13 03:56:30 +00:00
2018-09-12 17:26:21 +00:00
sessions = sessions.Where(i => CanAccessDevice(user, i.DeviceId)).ToArray();
2014-12-31 06:24:49 +00:00
}
2018-09-12 17:26:21 +00:00
var array = sessions.Select(ToDeviceInfo).ToArray();
2014-12-13 03:56:30 +00:00
return new QueryResult<DeviceInfo>
{
Items = array,
TotalRecordCount = array.Length
};
2014-10-11 20:38:13 +00:00
}
2018-09-12 17:26:21 +00:00
private DeviceInfo ToDeviceInfo(AuthenticationInfo authInfo)
{
var caps = GetCapabilities(authInfo.DeviceId);
return new DeviceInfo
{
AppName = authInfo.AppName,
AppVersion = authInfo.AppVersion,
Id = authInfo.DeviceId,
LastUserId = authInfo.UserId,
LastUserName = authInfo.UserName,
Name = authInfo.DeviceName,
DateLastActivity = authInfo.DateLastActivity,
IconUrl = caps == null ? null : caps.IconUrl
};
}
private string GetDevicesPath()
{
return Path.Combine(_config.ApplicationPaths.DataPath, "devices");
}
private string GetDevicePath(string id)
2014-10-11 20:38:13 +00:00
{
2018-09-12 17:26:21 +00:00
return Path.Combine(GetDevicesPath(), id.GetMD5().ToString("N"));
2014-10-11 20:38:13 +00:00
}
public ContentUploadHistory GetCameraUploadHistory(string deviceId)
{
2018-09-12 17:26:21 +00:00
var path = Path.Combine(GetDevicePath(deviceId), "camerauploads.json");
lock (_cameraUploadSyncLock)
{
try
{
return _json.DeserializeFromFile<ContentUploadHistory>(path);
}
catch (IOException)
{
return new ContentUploadHistory
{
DeviceId = deviceId
};
}
}
2014-10-11 20:38:13 +00:00
}
public async Task AcceptCameraUpload(string deviceId, Stream stream, LocalFileInfo file)
{
2018-09-12 17:26:21 +00:00
var device = GetDevice(deviceId, false);
var uploadPathInfo = GetUploadPath(device);
var path = uploadPathInfo.Item1;
2014-10-11 20:38:13 +00:00
if (!string.IsNullOrWhiteSpace(file.Album))
{
path = Path.Combine(path, _fileSystem.GetValidFilename(file.Album));
}
path = Path.Combine(path, file.Name);
2015-09-10 18:28:22 +00:00
path = Path.ChangeExtension(path, MimeTypes.ToExtension(file.MimeType) ?? "jpg");
2014-10-11 20:38:13 +00:00
2017-05-10 19:12:03 +00:00
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
2015-09-10 18:28:22 +00:00
2018-09-12 17:26:21 +00:00
await EnsureLibraryFolder(uploadPathInfo.Item2, uploadPathInfo.Item3).ConfigureAwait(false);
_libraryMonitor.ReportFileSystemChangeBeginning(path);
2014-10-11 20:38:13 +00:00
try
{
2016-10-25 19:02:04 +00:00
using (var fs = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
2014-10-11 20:38:13 +00:00
{
await stream.CopyToAsync(fs).ConfigureAwait(false);
}
2018-09-12 17:26:21 +00:00
AddCameraUpload(deviceId, file);
2014-10-11 20:38:13 +00:00
}
finally
{
_libraryMonitor.ReportFileSystemChangeComplete(path, true);
}
if (CameraImageUploaded != null)
{
EventHelper.FireEventIfNotNull(CameraImageUploaded, this, new GenericEventArgs<CameraImageUploadInfo>
{
Argument = new CameraImageUploadInfo
{
Device = device,
FileInfo = file
}
}, _logger);
}
2014-10-11 20:38:13 +00:00
}
2018-09-12 17:26:21 +00:00
private void AddCameraUpload(string deviceId, LocalFileInfo file)
{
2018-09-12 17:26:21 +00:00
var path = Path.Combine(GetDevicePath(deviceId), "camerauploads.json");
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
lock (_cameraUploadSyncLock)
2014-10-13 20:14:53 +00:00
{
2018-09-12 17:26:21 +00:00
ContentUploadHistory history;
try
{
history = _json.DeserializeFromFile<ContentUploadHistory>(path);
}
catch (IOException)
{
history = new ContentUploadHistory
{
DeviceId = deviceId
};
}
history.DeviceId = deviceId;
var list = history.FilesUploaded.ToList();
list.Add(file);
history.FilesUploaded = list.ToArray(list.Count);
_json.SerializeToFile(history, path);
2014-10-13 20:14:53 +00:00
}
2018-09-12 17:26:21 +00:00
}
2014-10-12 01:46:02 +00:00
2018-09-12 17:26:21 +00:00
internal Task EnsureLibraryFolder(string path, string name)
{
var existingFolders = _libraryManager
.RootFolder
.Children
.OfType<Folder>()
.Where(i => _fileSystem.AreEqual(path, i.Path) || _fileSystem.ContainsSubPath(i.Path, path))
.ToList();
if (existingFolders.Count > 0)
{
return Task.CompletedTask;
}
_fileSystem.CreateDirectory(path);
var libraryOptions = new LibraryOptions
{
PathInfos = new[] { new MediaPathInfo { Path = path } },
EnablePhotos = true,
EnableRealtimeMonitor = false,
SaveLocalMetadata = true
};
if (string.IsNullOrWhiteSpace(name))
{
name = _localizationManager.GetLocalizedString("HeaderCameraUploads");
}
return _libraryManager.AddVirtualFolder(name, CollectionType.HomeVideos, libraryOptions, true);
}
private Tuple<string, string, string> GetUploadPath(DeviceInfo device)
{
2014-10-13 20:14:53 +00:00
var config = _config.GetUploadOptions();
2017-03-07 18:27:56 +00:00
var path = config.CameraUploadPath;
2018-09-12 17:26:21 +00:00
2017-03-07 18:27:56 +00:00
if (string.IsNullOrWhiteSpace(path))
2014-10-11 20:38:13 +00:00
{
2017-03-07 18:27:56 +00:00
path = DefaultCameraUploadsPath;
2014-10-11 20:38:13 +00:00
}
2018-09-12 17:26:21 +00:00
var topLibraryPath = path;
2014-10-12 01:46:02 +00:00
if (config.EnableCameraUploadSubfolders)
{
path = Path.Combine(path, _fileSystem.GetValidFilename(device.Name));
}
2018-09-12 17:26:21 +00:00
return new Tuple<string, string, string>(path, topLibraryPath, null);
2015-11-03 04:34:47 +00:00
}
2018-09-12 17:26:21 +00:00
internal string GetUploadsPath()
2014-10-13 20:14:53 +00:00
{
2018-09-12 17:26:21 +00:00
var config = _config.GetUploadOptions();
var path = config.CameraUploadPath;
2014-10-13 20:14:53 +00:00
2018-09-12 17:26:21 +00:00
if (string.IsNullOrWhiteSpace(path))
{
path = DefaultCameraUploadsPath;
}
2017-10-13 19:18:05 +00:00
2018-09-12 17:26:21 +00:00
return path;
}
2014-10-13 20:14:53 +00:00
2018-09-12 17:26:21 +00:00
private string DefaultCameraUploadsPath
{
get { return Path.Combine(_config.CommonApplicationPaths.DataPath, "camerauploads"); }
2014-10-13 20:14:53 +00:00
}
2014-12-29 20:18:48 +00:00
2018-09-12 17:26:21 +00:00
public bool CanAccessDevice(User user, string deviceId)
2014-12-29 20:18:48 +00:00
{
2018-09-12 17:26:21 +00:00
if (user == null)
2014-12-29 20:18:48 +00:00
{
2018-09-12 17:26:21 +00:00
throw new ArgumentException("user not found");
2014-12-29 20:18:48 +00:00
}
2018-09-12 17:26:21 +00:00
if (string.IsNullOrEmpty(deviceId))
2014-12-29 20:18:48 +00:00
{
throw new ArgumentNullException("deviceId");
}
if (!CanAccessDevice(user.Policy, deviceId))
{
var capabilities = GetCapabilities(deviceId);
2015-01-20 05:19:13 +00:00
if (capabilities != null && capabilities.SupportsPersistentIdentifier)
2014-12-29 20:18:48 +00:00
{
return false;
}
}
return true;
}
private bool CanAccessDevice(UserPolicy policy, string id)
{
if (policy.EnableAllDevices)
{
return true;
}
2015-10-26 05:29:32 +00:00
if (policy.IsAdministrator)
{
return true;
}
2018-09-12 17:26:21 +00:00
return policy.EnabledDevices.Contains(id, StringComparer.OrdinalIgnoreCase);
}
}
public class DeviceManagerEntryPoint : IServerEntryPoint
{
private readonly DeviceManager _deviceManager;
private readonly IServerConfigurationManager _config;
private readonly IFileSystem _fileSystem;
private ILogger _logger;
public DeviceManagerEntryPoint(IDeviceManager deviceManager, IServerConfigurationManager config, IFileSystem fileSystem, ILogger logger)
{
_deviceManager = (DeviceManager)deviceManager;
_config = config;
_fileSystem = fileSystem;
_logger = logger;
}
public async void Run()
{
if (!_config.Configuration.CameraUploadUpgraded && _config.Configuration.IsStartupWizardCompleted)
{
var path = _deviceManager.GetUploadsPath();
if (_fileSystem.DirectoryExists(path))
{
try
{
await _deviceManager.EnsureLibraryFolder(path, null).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.ErrorException("Error creating camera uploads library", ex);
}
_config.Configuration.CameraUploadUpgraded = true;
_config.SaveConfiguration();
}
}
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: dispose managed state (managed objects).
}
// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
// TODO: set large fields to null.
disposedValue = true;
}
}
// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~DeviceManagerEntryPoint() {
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
2014-12-29 20:18:48 +00:00
}
2018-09-12 17:26:21 +00:00
#endregion
2014-10-11 20:38:13 +00:00
}
public class DevicesConfigStore : IConfigurationFactory
{
public IEnumerable<ConfigurationStore> GetConfigurations()
{
2018-09-12 17:26:21 +00:00
return new ConfigurationStore[]
2014-10-11 20:38:13 +00:00
{
new ConfigurationStore
{
Key = "devices",
ConfigurationType = typeof(DevicesOptions)
}
};
}
}
public static class UploadConfigExtension
{
public static DevicesOptions GetUploadOptions(this IConfigurationManager config)
{
return config.GetConfiguration<DevicesOptions>("devices");
}
}
2015-09-20 17:56:26 +00:00
}