1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
|
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Events;
using MediaBrowser.Common.IO;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Devices;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Devices;
using MediaBrowser.Model.Events;
using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Querying;
using MediaBrowser.Model.Session;
using MediaBrowser.Model.Users;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using CommonIO;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Model.Entities;
namespace MediaBrowser.Server.Implementations.Devices
{
public class DeviceManager : IDeviceManager
{
private readonly IDeviceRepository _repo;
private readonly IUserManager _userManager;
private readonly IFileSystem _fileSystem;
private readonly ILibraryMonitor _libraryMonitor;
private readonly IServerConfigurationManager _config;
private readonly ILogger _logger;
private readonly INetworkManager _network;
public event EventHandler<GenericEventArgs<CameraImageUploadInfo>> CameraImageUploaded;
/// <summary>
/// Occurs when [device options updated].
/// </summary>
public event EventHandler<GenericEventArgs<DeviceInfo>> DeviceOptionsUpdated;
public DeviceManager(IDeviceRepository repo, IUserManager userManager, IFileSystem fileSystem, ILibraryMonitor libraryMonitor, IServerConfigurationManager config, ILogger logger, INetworkManager network)
{
_repo = repo;
_userManager = userManager;
_fileSystem = fileSystem;
_libraryMonitor = libraryMonitor;
_config = config;
_logger = logger;
_network = network;
}
public async Task<DeviceInfo> RegisterDevice(string reportedId, string name, string appName, string appVersion, string usedByUserId)
{
var device = GetDevice(reportedId) ?? new DeviceInfo
{
Id = reportedId
};
device.ReportedName = name;
device.AppName = appName;
device.AppVersion = appVersion;
if (!string.IsNullOrWhiteSpace(usedByUserId))
{
var user = _userManager.GetUserById(usedByUserId);
device.LastUserId = user.Id.ToString("N");
device.LastUserName = user.Name;
}
device.DateLastModified = DateTime.UtcNow;
await _repo.SaveDevice(device).ConfigureAwait(false);
return device;
}
public Task SaveCapabilities(string reportedId, ClientCapabilities capabilities)
{
return _repo.SaveCapabilities(reportedId, capabilities);
}
public ClientCapabilities GetCapabilities(string reportedId)
{
return _repo.GetCapabilities(reportedId);
}
public DeviceInfo GetDevice(string id)
{
return _repo.GetDevice(id);
}
public QueryResult<DeviceInfo> GetDevices(DeviceQuery query)
{
IEnumerable<DeviceInfo> devices = _repo.GetDevices().OrderByDescending(i => i.DateLastModified);
if (query.SupportsContentUploading.HasValue)
{
var val = query.SupportsContentUploading.Value;
devices = devices.Where(i => GetCapabilities(i.Id).SupportsContentUploading == val);
}
if (query.SupportsSync.HasValue)
{
var val = query.SupportsSync.Value;
devices = devices.Where(i => GetCapabilities(i.Id).SupportsSync == val);
}
if (query.SupportsPersistentIdentifier.HasValue)
{
var val = query.SupportsPersistentIdentifier.Value;
devices = devices.Where(i =>
{
var caps = GetCapabilities(i.Id);
var deviceVal = caps.SupportsPersistentIdentifier;
return deviceVal == val;
});
}
if (!string.IsNullOrWhiteSpace(query.UserId))
{
devices = devices.Where(i => CanAccessDevice(query.UserId, i.Id));
}
var array = devices.ToArray();
return new QueryResult<DeviceInfo>
{
Items = array,
TotalRecordCount = array.Length
};
}
public Task DeleteDevice(string id)
{
return _repo.DeleteDevice(id);
}
public ContentUploadHistory GetCameraUploadHistory(string deviceId)
{
return _repo.GetCameraUploadHistory(deviceId);
}
public async Task AcceptCameraUpload(string deviceId, Stream stream, LocalFileInfo file)
{
var device = GetDevice(deviceId);
var path = GetUploadPath(device);
if (!string.IsNullOrWhiteSpace(file.Album))
{
path = Path.Combine(path, _fileSystem.GetValidFilename(file.Album));
}
path = Path.Combine(path, file.Name);
path = Path.ChangeExtension(path, MimeTypes.ToExtension(file.MimeType) ?? "jpg");
_libraryMonitor.ReportFileSystemChangeBeginning(path);
_fileSystem.CreateDirectory(Path.GetDirectoryName(path));
try
{
using (var fs = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))
{
await stream.CopyToAsync(fs).ConfigureAwait(false);
}
_repo.AddCameraUpload(deviceId, file);
}
finally
{
_libraryMonitor.ReportFileSystemChangeComplete(path, true);
}
if (CameraImageUploaded != null)
{
EventHelper.FireEventIfNotNull(CameraImageUploaded, this, new GenericEventArgs<CameraImageUploadInfo>
{
Argument = new CameraImageUploadInfo
{
Device = device,
FileInfo = file
}
}, _logger);
}
}
private string GetUploadPath(DeviceInfo device)
{
if (!string.IsNullOrWhiteSpace(device.CameraUploadPath))
{
return device.CameraUploadPath;
}
var config = _config.GetUploadOptions();
if (!string.IsNullOrWhiteSpace(config.CameraUploadPath))
{
return config.CameraUploadPath;
}
var path = DefaultCameraUploadsPath;
if (config.EnableCameraUploadSubfolders)
{
path = Path.Combine(path, _fileSystem.GetValidFilename(device.Name));
}
EnsureMediaLibrarySetup();
return path;
}
private string DefaultCameraUploadsPath
{
get { return Path.Combine(_config.CommonApplicationPaths.DataPath, "camerauploads"); }
}
internal void EnsureMediaLibrarySetup()
{
//EnsureMediaLibrarySetup(DefaultCameraUploadsPath, false);
}
private void EnsureMediaLibrarySetup(string libraryPath, bool force)
{
var requiresSetup = false;
var path = Path.Combine(_config.ApplicationPaths.DefaultUserViewsPath, "Camera Uploads");
var collectionMarkerFile = Path.Combine(path, CollectionType.Photos + ".collection");
if (!_fileSystem.FileExists(collectionMarkerFile))
{
requiresSetup = true;
}
var shortcutFile = Path.Combine(path, "camerauploads.mblink");
try
{
if (!string.Equals(_fileSystem.ReadAllText(shortcutFile), libraryPath))
{
requiresSetup = true;
}
}
catch
{
requiresSetup = true;
}
if (requiresSetup)
{
if (!force)
{
var extensions = new[] { ".jpg", ".png" };
var hasPhotos = _fileSystem.GetFiles(libraryPath, true).Any(i => extensions.Contains(i.Extension, StringComparer.OrdinalIgnoreCase));
// Nothing to do
if (!hasPhotos)
{
return;
}
}
}
if (requiresSetup)
{
Directory.CreateDirectory(path);
using (File.Create(collectionMarkerFile))
{
}
_fileSystem.CreateShortcut(shortcutFile, libraryPath);
}
}
public async Task UpdateDeviceInfo(string id, DeviceOptions options)
{
var device = GetDevice(id);
device.CustomName = options.CustomName;
device.CameraUploadPath = options.CameraUploadPath;
await _repo.SaveDevice(device).ConfigureAwait(false);
EventHelper.FireEventIfNotNull(DeviceOptionsUpdated, this, new GenericEventArgs<DeviceInfo>(device), _logger);
}
public bool CanAccessDevice(string userId, string deviceId)
{
if (string.IsNullOrWhiteSpace(userId))
{
throw new ArgumentNullException("userId");
}
if (string.IsNullOrWhiteSpace(deviceId))
{
throw new ArgumentNullException("deviceId");
}
var user = _userManager.GetUserById(userId);
if (user == null)
{
throw new ArgumentException("user not found");
}
if (!CanAccessDevice(user.Policy, deviceId))
{
var capabilities = GetCapabilities(deviceId);
if (capabilities != null && capabilities.SupportsPersistentIdentifier)
{
return false;
}
}
return true;
}
private bool CanAccessDevice(UserPolicy policy, string id)
{
if (policy.EnableAllDevices)
{
return true;
}
if (policy.IsAdministrator)
{
return true;
}
return ListHelper.ContainsIgnoreCase(policy.EnabledDevices, id);
}
}
public class DeviceManagerEntryPoint : IServerEntryPoint
{
private readonly IDeviceManager _deviceManager;
public DeviceManagerEntryPoint(IDeviceManager deviceManager)
{
_deviceManager = deviceManager;
}
public void Run()
{
((DeviceManager)_deviceManager).EnsureMediaLibrarySetup();
}
public void Dispose()
{
}
}
public class DevicesConfigStore : IConfigurationFactory
{
public IEnumerable<ConfigurationStore> GetConfigurations()
{
return new List<ConfigurationStore>
{
new ConfigurationStore
{
Key = "devices",
ConfigurationType = typeof(DevicesOptions)
}
};
}
}
public static class UploadConfigExtension
{
public static DevicesOptions GetUploadOptions(this IConfigurationManager config)
{
return config.GetConfiguration<DevicesOptions>("devices");
}
}
}
|