Exemple #1
0
        public async Task Sync(IServerSyncProvider provider,
            ISyncDataProvider dataProvider,
            SyncTarget target,
            IProgress<double> progress,
            CancellationToken cancellationToken)
        {
            var serverId = _appHost.SystemId;
            var serverName = _appHost.FriendlyName;

            await SyncData(provider, dataProvider, serverId, target, cancellationToken).ConfigureAwait(false);
            progress.Report(3);

            var innerProgress = new ActionableProgress<double>();
            innerProgress.RegisterAction(pct =>
            {
                var totalProgress = pct * .97;
                totalProgress += 1;
                progress.Report(totalProgress);
            });
            await GetNewMedia(provider, dataProvider, target, serverId, serverName, innerProgress, cancellationToken);

            // Do the data sync twice so the server knows what was removed from the device
            await SyncData(provider, dataProvider, serverId, target, cancellationToken).ConfigureAwait(false);
            
            progress.Report(100);
        }
        /// <summary>
        /// Default ctor.
        /// </summary>
        public RequestFactory(SyncTarget target, string accessToken)
        {
            var config = PluginConfiguration.Configuration;

            this.syncAccount = config.SyncAccounts.FirstOrDefault(x => x.Id == target.Id);
            this.accessToken = accessToken;
        }
 public IEnumerable<SyncQualityOption> GetQualityOptions(SyncTarget target)
 {
     return new List<SyncQualityOption>
     {
         new SyncQualityOption
         {
             Name = "Original",
             Id = "original",
             Description = "Syncs original files as-is, regardless of whether the device is capable of playing them or not."
         },
         new SyncQualityOption
         {
             Name = "High",
             Id = "high",
             IsDefault = true
         },
         new SyncQualityOption
         {
             Name = "Medium",
             Id = "medium"
         },
         new SyncQualityOption
         {
             Name = "Low",
             Id = "low"
         }
     };
 }
        public DeviceProfile GetDeviceProfile(SyncTarget target, string profile, string quality)
        {
            var caps = _deviceManager.GetCapabilities(target.Id);

            var deviceProfile = caps == null || caps.DeviceProfile == null ? new DeviceProfile() : caps.DeviceProfile;
            deviceProfile.MaxStaticBitrate = SyncHelper.AdjustBitrate(deviceProfile.MaxStaticBitrate, quality);

            return deviceProfile;
        }
        public OneDriveCredentials(IConfigurationRetriever configurationRetriever, ILiveAuthenticationApi liveAuthenticationApi, SyncTarget target)
        {
            _configurationRetriever = configurationRetriever;
            _liveAuthenticationApi = liveAuthenticationApi;
            _syncAccountId = target.Id;

            var syncAccount = configurationRetriever.GetSyncAccount(target.Id);
            _accessToken = syncAccount.AccessToken;
        }
        public OneDriveSyncJob FindSyncJob(SyncTarget target, string localPath, string hash)
        {
            var syncJob = SyncJobs.FirstOrDefault(x => x.Target == target && x.LocalPath == localPath && x.Hash == hash);

            if (syncJob != null && syncJob.ExpirationDateTime < DateTime.Now)
            {
                RemoveSyncJob(syncJob);
                syncJob = null;
            }

            return syncJob;
        }
        public async Task<SyncedFileInfo> SendFile(Stream stream, string[] remotePath, SyncTarget target, IProgress<double> progress, CancellationToken cancellationToken)
        {
            var fullPath = GetFullPath(remotePath, target);

            _fileSystem.CreateDirectory(Path.GetDirectoryName(fullPath));

            _logger.Debug("Folder sync saving stream to {0}", fullPath);

            using (var fileStream = _fileSystem.GetFileStream(fullPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
            {
                await stream.CopyToAsync(fileStream).ConfigureAwait(false);
                return GetSyncedFileInfo(fullPath);
            }
        }
Exemple #8
0
        public string GetFullPath(IEnumerable<string> paths, SyncTarget target)
        {
            var account = GetSyncAccounts()
                .FirstOrDefault(i => string.Equals(i.Id, target.Id, StringComparison.OrdinalIgnoreCase));

            if (account == null)
            {
                throw new ArgumentException("Invalid SyncTarget supplied.");
            }

            var list = paths.ToList();
            list.Insert(0, account.Path);

            return Path.Combine(list.ToArray());
        }
        public async Task<SyncedFileInfo> GetSyncedFileInfo(string id, SyncTarget target, CancellationToken cancellationToken)
        {
            _logger.Debug("Getting synced file info for {0} from {1}", id, target.Name);

            var googleCredentials = GetGoogleCredentials(target);

            var url = await _googleDriveService.CreateDownloadUrl(id, googleCredentials, cancellationToken).ConfigureAwait(false);

            return new SyncedFileInfo
            {
                Path = url,
                Protocol = MediaProtocol.Http,
                Id = id
            };
        }
        public async Task<SyncedFileInfo> SendFile(Stream stream, string[] pathParts, SyncTarget target, IProgress<double> progress, CancellationToken cancellationToken)
        {
            var path = GetFullPath(pathParts, target);
            _logger.Debug("Sending file {0} to {1}", path, target.Name);

            var syncAccount = _configurationRetriever.GetSyncAccount(target.Id);

            await UploadFile(path, stream, syncAccount.AccessToken, cancellationToken);

            return new SyncedFileInfo
            {
                Id = path,
                Path = path,
                Protocol = MediaProtocol.Http
            };
        }
Exemple #11
0
        public async Task<SyncedFileInfo> SendFile(Stream stream, string[] remotePath, SyncTarget target, IProgress<double> progress, CancellationToken cancellationToken)
        {
            var fullPath = GetFullPath(remotePath, target);

            Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
            using (var fileStream = _fileSystem.GetFileStream(fullPath, FileMode.Create, FileAccess.Write, FileShare.Read, true))
            {
                await stream.CopyToAsync(fileStream).ConfigureAwait(false);
                return new SyncedFileInfo
                {
                    Path = fullPath,
                    Protocol = MediaProtocol.File,
                    Id = fullPath
                };
            }
        }
Exemple #12
0
        private async Task SyncData(IServerSyncProvider provider,
            ISyncDataProvider dataProvider,
            string serverId,
            SyncTarget target,
            CancellationToken cancellationToken)
        {
            var localItems = await dataProvider.GetLocalItems(target, serverId).ConfigureAwait(false);
            var remoteFiles = await provider.GetFiles(new FileQuery(), target, cancellationToken).ConfigureAwait(false);
            var remoteIds = remoteFiles.Items.Select(i => i.Id).ToList();

            var jobItemIds = new List<string>();

            foreach (var localItem in localItems)
            {
                // TODO: Remove this after a while
                if (string.IsNullOrWhiteSpace(localItem.FileId))
                {
                    jobItemIds.Add(localItem.SyncJobItemId);
                }
                else if (remoteIds.Contains(localItem.FileId, StringComparer.OrdinalIgnoreCase))
                {
                    jobItemIds.Add(localItem.SyncJobItemId);
                }
            }

            var result = await _syncManager.SyncData(new SyncDataRequest
            {
                TargetId = target.Id,
                SyncJobItemIds = jobItemIds

            }).ConfigureAwait(false);

            cancellationToken.ThrowIfCancellationRequested();

            foreach (var itemIdToRemove in result.ItemIdsToRemove)
            {
                try
                {
                    await RemoveItem(provider, dataProvider, serverId, itemIdToRemove, target, cancellationToken).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error deleting item from device. Id: {0}", ex, itemIdToRemove);
                }
            }
        }
        public async Task<SyncedFileInfo> SendFile(Stream stream, string[] pathParts, SyncTarget target, IProgress<double> progress, CancellationToken cancellationToken)
        {
            _logger.Debug("Sending file {0} to {1}", string.Join("/", pathParts), target.Name);

            var syncAccount = _configurationRetriever.GetSyncAccount(target.Id);

            var googleCredentials = GetGoogleCredentials(target);

            var file = await _googleDriveService.UploadFile(stream, pathParts, syncAccount.FolderId, googleCredentials, progress, cancellationToken);

            return new SyncedFileInfo
            {
                Path = file.Item2,
                Protocol = MediaProtocol.Http,
                Id = file.Item1
            };
        }
        public async Task<SyncedFileInfo> GetSyncedFileInfo(string id, SyncTarget target, CancellationToken cancellationToken)
        {
            _logger.Debug("Getting synced file info for {0} from {1}", id, target.Name);

            try
            {
                return await TryGetSyncedFileInfo(id, target, cancellationToken);
            }
            catch (HttpException ex)
            {
                if (ex.StatusCode == HttpStatusCode.NotFound)
                {
                    throw new FileNotFoundException("File not found", ex);
                }

                throw;
            }
        }
        public async Task DeleteFile(string id, SyncTarget target, CancellationToken cancellationToken)
        {
            try
            {
                var oneDriveCredentials = CreateOneDriveCredentials(target);

                await _oneDriveApi.Delete(id, oneDriveCredentials, cancellationToken);
            }
            catch (HttpException ex)
            {
                if (ex.StatusCode == HttpStatusCode.NotFound)
                {
                    throw new FileNotFoundException("File not found", ex);
                }

                throw;
            }
        }
        public async Task<SyncedFileInfo> SendFile(Stream stream, string[] pathParts, SyncTarget target, IProgress<double> progress, CancellationToken cancellationToken)
        {
            string path = GetFullPath(pathParts);
            _logger.Debug("Sending file {0} to {1}", path, target.Name);

            var oneDriveCredentials = CreateOneDriveCredentials(target);

            await CreateFolderHierarchy(pathParts, oneDriveCredentials, cancellationToken);

            var uploadSession = await _oneDriveApi.CreateUploadSession(path, oneDriveCredentials, cancellationToken);
            var id = await UploadFile(uploadSession.uploadUrl, stream, oneDriveCredentials, cancellationToken);

            return new SyncedFileInfo
            {
                Id = id,
                Path = path,
                Protocol = MediaProtocol.Http
            };
        }
        public Task<QueryResult<FileSystemMetadata>> GetFiles(string id, SyncTarget target, CancellationToken cancellationToken)
        {
            var account = GetSyncAccounts()
                .FirstOrDefault(i => string.Equals(i.Id, target.Id, StringComparison.OrdinalIgnoreCase));

            if (account == null)
            {
                throw new ArgumentException("Invalid SyncTarget supplied.");
            }

            var result = new QueryResult<FileSystemMetadata>();

            var file = _fileSystem.GetFileSystemInfo(id);

            if (file.Exists)
            {
                result.TotalRecordCount = 1;
                result.Items = new[] { file }.ToArray();
            }

            return Task.FromResult(result);
        }
Exemple #18
0
        public Task DeleteFile(string id, SyncTarget target, CancellationToken cancellationToken)
        {
            return Task.Run(() =>
            {
                File.Delete(id);

                var account = GetSyncAccounts()
                    .FirstOrDefault(i => string.Equals(i.Id, target.Id, StringComparison.OrdinalIgnoreCase));

                if (account != null)
                {
                    try
                    {
                        DeleteEmptyFolders(account.Path);
                    }
                    catch
                    {
                    }
                }

            }, cancellationToken);
        }
        private void AddMediaSource(List<MediaSourceInfo> list,
            LocalItem item,
            MediaSourceInfo mediaSource,
            IServerSyncProvider provider,
            SyncTarget target)
        {
            SetStaticMediaSourceInfo(item, mediaSource);

            var requiresDynamicAccess = provider as IHasDynamicAccess;

            if (requiresDynamicAccess != null)
            {
                mediaSource.RequiresOpening = true;

                var keyList = new List<string>();
                keyList.Add(provider.GetType().FullName.GetMD5().ToString("N"));
                keyList.Add(target.Id.GetMD5().ToString("N"));
                keyList.Add(item.Id);
                mediaSource.OpenToken = string.Join(StreamIdDelimeterString, keyList.ToArray());
            }

            list.Add(mediaSource);
        }
Exemple #20
0
        private IEnumerable<SyncQualityOption> GetQualityOptions(ISyncProvider provider, SyncTarget target, User user)
        {
            var hasQuality = provider as IHasSyncQuality;
            if (hasQuality != null)
            {
                var options = hasQuality.GetQualityOptions(target);

                if (user != null && !user.Policy.EnableSyncTranscoding)
                {
                    options = options.Where(i => i.IsOriginalQuality);
                }

                return options;
            }

            // Default options for providers that don't override
            return new List<SyncQualityOption>
            {
                new SyncQualityOption
                {
                    Name = "High",
                    Id = "high",
                    IsDefault = true
                },
                new SyncQualityOption
                {
                    Name = "Medium",
                    Id = "medium"
                },
                new SyncQualityOption
                {
                    Name = "Low",
                    Id = "low"
                },
                new SyncQualityOption
                {
                    Name = "Custom",
                    Id = "custom"
                }
            };
        }
Exemple #21
0
        private IEnumerable<SyncProfileOption> GetProfileOptions(ISyncProvider provider, SyncTarget target, User user)
        {
            var hasQuality = provider as IHasSyncQuality;
            if (hasQuality != null)
            {
                return hasQuality.GetProfileOptions(target);
            }

            var list = new List<SyncProfileOption>();

            list.Add(new SyncProfileOption
            {
                Name = "Original",
                Id = "Original",
                Description = "Syncs original files as-is.",
                EnableQualityOptions = false
            });

            if (user == null || user.Policy.EnableSyncTranscoding)
            {
                list.Add(new SyncProfileOption
                {
                    Name = "Baseline",
                    Id = "baseline",
                    Description = "Designed for compatibility with all devices, including web browsers. Targets H264/AAC video and MP3 audio."
                });

                list.Add(new SyncProfileOption
                {
                    Name = "General",
                    Id = "general",
                    Description = "Designed for compatibility with Chromecast, Roku, Smart TV's, and other similar devices. Targets H264/AAC/AC3 video and MP3 audio.",
                    IsDefault = true
                });
            }

            return list;
        }
 public DeviceProfile GetDeviceProfile(SyncTarget target)
 {
     return new DeviceProfile();
 }
Exemple #23
0
        private SyncJobOptions GetSyncJobOptions(ISyncProvider provider, SyncTarget target, string profile, string quality)
        {
            var hasProfile = provider as IHasSyncQuality;

            if (hasProfile != null)
            {
                return hasProfile.GetSyncJobOptions(target, profile, quality);
            }

            return GetDefaultSyncJobOptions(profile, quality);
        }
Exemple #24
0
        private string GetSyncTargetId(ISyncProvider provider, SyncTarget target)
        {
            var hasUniqueId = provider as IHasUniqueTargetIds;

            if (hasUniqueId != null)
            {
                return target.Id;
            }

            return target.Id;
            //var providerId = GetSyncProviderId(provider);
            //return (providerId + "-" + target.Id).GetMD5().ToString("N");
        }
Exemple #25
0
 public Task<Stream> GetFile(string id, SyncTarget target, IProgress<double> progress, CancellationToken cancellationToken)
 {
     return Task.FromResult((Stream)File.OpenRead(id));
 }
        public SyncJobOptions GetSyncJobOptions(SyncTarget target, string profile, string quality)
        {
            var isConverting = !string.Equals(quality, "original", StringComparison.OrdinalIgnoreCase);

            return new SyncJobOptions
            {
                DeviceProfile = GetDeviceProfile(target, profile, quality),
                IsConverting = isConverting
            };
        }
Exemple #27
0
        public Task<QueryResult<FileMetadata>> GetFiles(FileQuery query, SyncTarget target, CancellationToken cancellationToken)
        {
            var account = GetSyncAccounts()
                .FirstOrDefault(i => string.Equals(i.Id, target.Id, StringComparison.OrdinalIgnoreCase));

            if (account == null)
            {
                throw new ArgumentException("Invalid SyncTarget supplied.");
            }

            var result = new QueryResult<FileMetadata>();

            if (!string.IsNullOrWhiteSpace(query.Id))
            {
                var file = _fileSystem.GetFileSystemInfo(query.Id);

                if (file.Exists)
                {
                    result.TotalRecordCount = 1;
                    result.Items = new[] { file }.Select(GetFile).ToArray();
                }

                return Task.FromResult(result);
            }

            if (query.FullPath != null && query.FullPath.Length > 0)
            {
                var file = _fileSystem.GetFileSystemInfo(query.FullPath[0]);

                if (file.Exists)
                {
                    result.TotalRecordCount = 1;
                    result.Items = new[] { file }.Select(GetFile).ToArray();
                }

                return Task.FromResult(result);
            }

            var files = _fileSystem.GetFiles(account.Path, true)
                .Select(GetFile)
                .ToArray();

            result.Items = files;
            result.TotalRecordCount = files.Length;

            return Task.FromResult(result);
        }
Exemple #28
0
        public Task<SyncedFileInfo> SendFile(string path, string[] pathParts, SyncTarget target, IProgress<double> progress, CancellationToken cancellationToken)
        {
            var fullPath = GetFullPath(pathParts, target);

            Directory.CreateDirectory(Path.GetDirectoryName(fullPath));

            File.Copy(path, fullPath, true);

            return Task.FromResult(new SyncedFileInfo
            {
                Path = fullPath,
                Protocol = MediaProtocol.File,
                Id = fullPath
            });

        }
Exemple #29
0
 public ISyncDataProvider GetDataProvider(IServerSyncProvider provider, SyncTarget target)
 {
     return _dataProviders.GetOrAdd(target.Id, key => new TargetDataProvider(provider, target, _appHost, _logger, _json, _fileSystem, _config.CommonApplicationPaths));
 }
 public IEnumerable<SyncProfileOption> GetProfileOptions(SyncTarget target)
 {
     return new List<SyncProfileOption>();
 }