/// <inheritdoc />
        public async Task UpdateAsync(ContentHash contentHash, bool touch, IClock clock, UpdateFileInfo updateFileInfo)
        {
            ContentDirectory.TryGetValue(contentHash, out var existingInfo);

            ContentFileInfo cloneInfo = null;

            if (existingInfo != null)
            {
                cloneInfo = new ContentFileInfo(existingInfo.FileSize, existingInfo.LastAccessedFileTimeUtc, existingInfo.ReplicaCount);
                if (touch)
                {
                    existingInfo.UpdateLastAccessed(clock);
                }
            }

            var updateTask = updateFileInfo(cloneInfo);

            if (updateTask != null)
            {
                var updateInfo = await updateTask;
                if (updateInfo != null)
                {
                    ContentDirectory.TryGetValue(contentHash, out existingInfo);
                    if (existingInfo == null)
                    {
                        ContentDirectory.TryAdd(contentHash, updateInfo);
                    }
                    else if (existingInfo.ReplicaCount != updateInfo.ReplicaCount)
                    {
                        ContentDirectory[contentHash].ReplicaCount = updateInfo.ReplicaCount;
                    }
                }
            }
        }
Пример #2
0
        private void StartHttpServer()
        {
            var enableSecurity = ServerConfiguration.Value.Security?.Enabled ?? false;
            var http           = ServerConfiguration.Value.Http;

            var contentDir = new ContentDirectory {
                DirectoryPath = Configuration.HttpContentDirectory,
                UrlPath       = "/Content/",
            };

            var sharedContentDir = new ContentDirectory {
                DirectoryPath = Configuration.HttpSharedContentDirectory,
                UrlPath       = "/SharedContent/",
            };

            var context = new HttpReceiverContext {
                ListenerPath       = http.Path,
                ContentDirectories =
                {
                    contentDir,
                    sharedContentDir,
                },
            };

            if (enableSecurity)
            {
                var ldapAuth = new LdapAuthorization();

                context.SecurityMgr = new ServerHttpSecurity {
                    Authorization = ldapAuth,
                };
            }

            context.Views.AddFolderFromExternal(Configuration.HttpViewDirectory);

            var httpPrefix = $"http://{http.Host}:{http.Port}/";

            if (!string.IsNullOrEmpty(http.Path))
            {
                httpPrefix = NetPath.Combine(httpPrefix, http.Path);
            }

            if (!httpPrefix.EndsWith("/"))
            {
                httpPrefix += "/";
            }

            receiver = new HttpReceiver(context);
            receiver.Routes.Scan(Assembly.GetExecutingAssembly());
            receiver.AddPrefix(httpPrefix);

            try {
                receiver.Start();

                Log.Debug($"HTTP Server listening at {httpPrefix}");
            }
            catch (Exception error) {
                Log.Error("Failed to start HTTP Receiver!", error);
            }
        }
 /// <inheritdoc />
 public void UpdateContentWithLastAccessTime(ContentHash contentHash, DateTime lastAccess)
 {
     if (ContentDirectory.TryGetValue(contentHash, out var existingInfo))
     {
         existingInfo.UpdateLastAccessed(lastAccess);
     }
 }
Пример #4
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("No directory specified.");
            }
            else if (!Directory.Exists(args[0]))
            {
                Console.WriteLine("Directory not found.");
            }
            else
            {
                var path = args[0];

                ContentDirectory core = ContentDirectory.Create(path, true);

                GameResources resources = new GameResources();
                resources.LoadResources(core);

#if DEBUG
                resources.SerializeToFile(@".\ResourceManifest.xml");
#else
                resources.SerializeToFile(@"..\..\..\DredmorXmlValidation\ResourceManifest.xml");
#endif
            }

            Console.Beep();
        }
Пример #5
0
        private SearchResult Browse(string action, uint startIndex = 0u, uint requestedCount = 100u)
        {
            var arguments = new UPnPArgument[10];

            arguments[0] = new UPnPArgument("ObjectID", action);
            arguments[1] = new UPnPArgument("BrowseFlag", "BrowseDirectChildren");
            arguments[2] = new UPnPArgument("Filter", "");
            arguments[3] = new UPnPArgument("StartingIndex", startIndex);
            arguments[4] = new UPnPArgument("RequestedCount", requestedCount);
            arguments[5] = new UPnPArgument("SortCriteria", "");
            arguments[6] = new UPnPArgument("Result", "");
            arguments[7] = new UPnPArgument("NumberReturned", 0u);
            arguments[8] = new UPnPArgument("TotalMatches", 0u);
            arguments[9] = new UPnPArgument("UpdateID", 0u);

            ContentDirectory.InvokeSync("Browse", arguments);

            var result = arguments[6].DataValue as string;

            return(new SearchResult
            {
                Result = result,
                StartingIndex = startIndex,
                NumberReturned = (uint)arguments[7].DataValue,
                TotalMatches = (uint)arguments[8].DataValue
            });
        }
Пример #6
0
 public static void browse(ContentDirectory directory)
 {
     ContentBrowserWindow.currentDirectory = directory;
     if (ContentBrowserWindow.browsed != null)
     {
         ContentBrowserWindow.browsed(ContentBrowserWindow.currentDirectory);
     }
 }
Пример #7
0
 public Task <byte[]> CorruptWithBlobForNonexistentContentDirectoryEntry(
     Context context, DisposableDirectory tempDirectory)
 {
     return(CorruptStoreAsync(context, tempDirectory, async contentHash =>
     {
         await ContentDirectory.RemoveAsync(contentHash);
         (await ContentDirectory.GetCountAsync()).Should().Be(0);
     }));
 }
        // Token: 0x06001087 RID: 4231 RVA: 0x0006CCD4 File Offset: 0x0006B0D4
        public ContentBrowserDirectoryButton(ContentDirectory newDirectory)
        {
            this.directory = newDirectory;
            Sleek2Label sleek2Label = new Sleek2Label();

            sleek2Label.transform.reset();
            sleek2Label.textComponent.text  = "/" + this.directory.name;
            sleek2Label.textComponent.color = Sleek2Config.darkTextColor;
            this.addElement(sleek2Label);
        }
Пример #9
0
 public Task <byte[]> CorruptWithExtraReplicaAsync(Context context, MemoryClock clock, DisposableDirectory tempDirectory)
 {
     return(CorruptStoreWithReplicasAsync(context, clock, tempDirectory, async hash =>
                                          await ContentDirectory.UpdateAsync(hash, true, Clock, fileInfo =>
     {
         fileInfo.ReplicaCount.Should().Be(2);
         fileInfo.ReplicaCount--;
         return Task.FromResult(fileInfo);
     })));
 }
Пример #10
0
        public async Task <byte[]> CorruptWithContentDirectoryEntryForNonexistentBlobAsync()
        {
            var bytes       = ThreadSafeRandom.GetBytes(100);
            var contentHash = bytes.CalculateHash(ContentHashType);
            await ContentDirectory.UpdateAsync(contentHash, false, Clock, fileInfo =>
                                               Task.FromResult(new ContentFileInfo(Clock, 1, 100)));

            (await ContentDirectory.GetCountAsync()).Should().Be(1);
            return(bytes);
        }
Пример #11
0
        /// <inheritdoc />
        public Task <IReadOnlyList <ContentHashWithLastAccessTimeAndReplicaCount> > GetLruOrderedCacheContentWithTimeAsync()
        {
            // http://stackoverflow.com/questions/11692389/getting-argument-exception-in-concurrent-dictionary-when-sorting-and-displaying
            // LINQ assumes an immutable source.
            var snapshotContentDirectory = ContentDirectory.ToArray();

            return(Task.FromResult <IReadOnlyList <ContentHashWithLastAccessTimeAndReplicaCount> >(snapshotContentDirectory
                                                                                                   .OrderBy(fileInfoByHash => fileInfoByHash.Value.LastAccessedFileTimeUtc)
                                                                                                   .Select(fileInfoByHash => new ContentHashWithLastAccessTimeAndReplicaCount(fileInfoByHash.Key, DateTime.FromFileTimeUtc(fileInfoByHash.Value.LastAccessedFileTimeUtc)))
                                                                                                   .ToList()));
        }
Пример #12
0
        public async Task <ContentFileInfo> GetCacheFileInfo(ContentHash contentHash)
        {
            ContentFileInfo info = null;

            await ContentDirectory.UpdateAsync(contentHash, false, Clock, fileInfo =>
            {
                info = fileInfo;
                return(null);
            });

            return(info);
        }
Пример #13
0
        private void StartHttpServer()
        {
            var contentDir = new ContentDirectory {
                DirectoryPath = Configuration.HttpContentDirectory,
                UrlPath       = "/Content/",
            };

            var sharedContentDir = new ContentDirectory {
                DirectoryPath = Configuration.HttpSharedContentDirectory,
                UrlPath       = "/SharedContent/",
            };

            var context = new HttpReceiverContext {
                SecurityMgr        = new AgentHttpSecurity(),
                ListenerPath       = Definition.Http.Path,
                ContentDirectories =
                {
                    contentDir,
                    sharedContentDir,
                },
            };

            context.Views.AddFolderFromExternal(Configuration.HttpViewDirectory);

            var httpPrefix = $"http://{Definition.Http.Host}:{Definition.Http.Port}/";

            if (!string.IsNullOrEmpty(Definition.Http.Path))
            {
                httpPrefix = NetPath.Combine(httpPrefix, Definition.Http.Path);
            }

            if (!httpPrefix.EndsWith("/"))
            {
                httpPrefix += "/";
            }

            receiver = new HttpReceiver(context);
            receiver.Routes.Scan(Assembly.GetExecutingAssembly());
            receiver.AddPrefix(httpPrefix);

            try {
                receiver.Start();

                Log.Info($"HTTP Server listening at {httpPrefix}");
            }
            catch (Exception error) {
                Log.Error("Failed to start HTTP Receiver!", error);
            }
        }
Пример #14
0
        public static string Format(string path, ContentDirectory directory)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException(nameof(path));
            }

            string formattedPath = path.Replace('/', '\\');

            if (formattedPath.IndexOf(Options.Template(directory), StringComparison.OrdinalIgnoreCase) >= 0)
            {
                formattedPath = formattedPath.Replace(Options.Template(directory), GetPath(directory), StringComparison.OrdinalIgnoreCase);
            }

            return(Regex.Replace(formattedPath, "\\\\{2,}", @"\"));
        }
Пример #15
0
        public void Initialize()
        {
            var contentDir = new ContentDirectory {
                DirectoryPath = Configuration.HttpContentDirectory,
                UrlPath       = "/Content/",
            };

            Context.ContentDirectories.Add(contentDir);

            var sharedContentDir = new ContentDirectory {
                DirectoryPath = Configuration.HttpSharedContentDirectory,
                UrlPath       = "/SharedContent/",
            };

            Context.ContentDirectories.Add(sharedContentDir);

            Context.Views.AddFolderFromExternal(Configuration.HttpViewDirectory);
        }
        public static ContentDirectory LoadContentDirectory()
        {
            string[] contents = { "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede.", "Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim pellentesque felis.", "Morbi in sem quis dui placerat ornare. Pellentesque odio nisi, euismod in, pharetra a, ultricies in, diam. Sed arcu. Cras consequat.", "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede.", "Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim pellentesque felis.", "Morbi in sem quis dui placerat ornare. Pellentesque odio nisi, euismod in, pharetra a, ultricies in, diam. Sed arcu. Cras consequat.", "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede.", "Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim pellentesque felis.", "Morbi in sem quis dui placerat ornare. Pellentesque odio nisi, euismod in, pharetra a, ultricies in, diam. Sed arcu. Cras consequat.", "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede.", "Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim pellentesque felis.", "Morbi in sem quis dui placerat ornare. Pellentesque odio nisi, euismod in, pharetra a, ultricies in, diam. Sed arcu. Cras consequat.", "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede.", "Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim pellentesque felis.", "Morbi in sem quis dui placerat ornare. Pellentesque odio nisi, euismod in, pharetra a, ultricies in, diam. Sed arcu. Cras consequat.", "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede.", "Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim pellentesque felis.", "Morbi in sem quis dui placerat ornare. Pellentesque odio nisi, euismod in, pharetra a, ultricies in, diam. Sed arcu. Cras consequat." };

            ContentDirectory ContentDiretory           = new ContentDirectory();
            ObservableCollection <Content> contentList = new ObservableCollection <Content>();

            for (int i = 0; i < contents.Length; i++)
            {
                Content Content = new Content();
                Content.Position    = i + 1;
                Content.Value       = contents[i];
                Content.Description = contents[i];
                contentList.Add(Content);
            }

            ContentDiretory.ContentList = contentList;
            return(ContentDiretory);
        }
Пример #17
0
 protected void handleBrowsed(ContentDirectory directory)
 {
     this.pathPanel.clearElements();
     this.itemsPanel.clearElements();
     this.itemsPanel.transform.offsetMin = new Vector2(0f, 0f);
     this.itemsPanel.transform.offsetMax = new Vector2(0f, 0f);
     if (directory == null)
     {
         return;
     }
     for (int i = 0; i < directory.files.Count; i++)
     {
         ContentBrowserFileButton element = new ContentBrowserFileButton(directory.files[i]);
         this.itemsPanel.addElement(element);
     }
     foreach (KeyValuePair <string, ContentDirectory> keyValuePair in directory.directories)
     {
         ContentDirectory value = keyValuePair.Value;
         ContentBrowserDirectoryButton contentBrowserDirectoryButton = new ContentBrowserDirectoryButton(value);
         contentBrowserDirectoryButton.clicked += this.handleDirectoryButtonClicked;
         this.itemsPanel.addElement(contentBrowserDirectoryButton);
     }
     do
     {
         ContentBrowserDirectoryButton contentBrowserDirectoryButton2 = new ContentBrowserDirectoryButton(directory);
         contentBrowserDirectoryButton2.transform.anchorMin = new Vector2(0f, 0f);
         contentBrowserDirectoryButton2.transform.anchorMax = new Vector2(0f, 1f);
         contentBrowserDirectoryButton2.transform.pivot     = new Vector2(0f, 1f);
         contentBrowserDirectoryButton2.transform.sizeDelta = new Vector2(150f, 0f);
         contentBrowserDirectoryButton2.clicked            += this.handleDirectoryButtonClicked;
         this.pathPanel.addElement(contentBrowserDirectoryButton2, 0);
         if (directory.parent != null)
         {
             Sleek2Label sleek2Label = new Sleek2Label();
             sleek2Label.transform.anchorMin = new Vector2(0f, 0f);
             sleek2Label.transform.anchorMax = new Vector2(0f, 1f);
             sleek2Label.transform.pivot     = new Vector2(0f, 1f);
             sleek2Label.transform.sizeDelta = new Vector2(30f, 0f);
             sleek2Label.textComponent.text  = ">";
             this.pathPanel.addElement(sleek2Label, 0);
         }
     }while ((directory = directory.parent) != null);
 }
Пример #18
0
 public static string Content(this UrlHelper helper, ContentDirectory dir, string fileWithExt)
 {
     return helper.Content(String.Format("~/Content/{0}/{1}", dir.ToString(), fileWithExt));
 }
Пример #19
0
        /// <summary>
        /// Registers resources that classes will depend on
        /// </summary>
        /// <returns>Task.</returns>
        protected override async Task RegisterResources(IProgress <double> progress)
        {
            await base.RegisterResources(progress).ConfigureAwait(false);

            RegisterSingleInstance <IHttpResultFactory>(new HttpResultFactory(LogManager, FileSystemManager, JsonSerializer));

            RegisterSingleInstance <IServerApplicationHost>(this);
            RegisterSingleInstance <IServerApplicationPaths>(ApplicationPaths);

            RegisterSingleInstance(ServerConfigurationManager);

            LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager, JsonSerializer);
            RegisterSingleInstance(LocalizationManager);

            RegisterSingleInstance <IBlurayExaminer>(() => new BdInfoExaminer());

            UserDataManager = new UserDataManager(LogManager);
            RegisterSingleInstance(UserDataManager);

            UserRepository = await GetUserRepository().ConfigureAwait(false);

            RegisterSingleInstance(UserRepository);

            DisplayPreferencesRepository = new SqliteDisplayPreferencesRepository(ApplicationPaths, JsonSerializer, LogManager);
            RegisterSingleInstance(DisplayPreferencesRepository);

            ItemRepository = new SqliteItemRepository(ApplicationPaths, JsonSerializer, LogManager);
            RegisterSingleInstance(ItemRepository);

            ProviderRepository = new SqliteProviderInfoRepository(ApplicationPaths, LogManager);
            RegisterSingleInstance(ProviderRepository);

            FileOrganizationRepository = await GetFileOrganizationRepository().ConfigureAwait(false);

            RegisterSingleInstance(FileOrganizationRepository);

            AuthenticationRepository = await GetAuthenticationRepository().ConfigureAwait(false);

            RegisterSingleInstance(AuthenticationRepository);

            //SyncRepository = await GetSyncRepository().ConfigureAwait(false);
            //RegisterSingleInstance(SyncRepository);

            UserManager = new UserManager(LogManager.GetLogger("UserManager"), ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, () => ConnectManager);
            RegisterSingleInstance(UserManager);

            LibraryManager = new LibraryManager(Logger, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager);
            RegisterSingleInstance(LibraryManager);

            var musicManager = new MusicManager(LibraryManager);

            RegisterSingleInstance <IMusicManager>(new MusicManager(LibraryManager));

            LibraryMonitor = new LibraryMonitor(LogManager, TaskManager, LibraryManager, ServerConfigurationManager, FileSystemManager);
            RegisterSingleInstance(LibraryMonitor);

            ProviderManager = new ProviderManager(HttpClient, ServerConfigurationManager, LibraryMonitor, LogManager, FileSystemManager);
            RegisterSingleInstance(ProviderManager);

            SeriesOrderManager = new SeriesOrderManager();
            RegisterSingleInstance(SeriesOrderManager);

            RegisterSingleInstance <ISearchEngine>(() => new SearchEngine(LogManager, LibraryManager, UserManager));

            HttpServer = ServerFactory.CreateServer(this, LogManager, "Media Browser", WebApplicationName, "dashboard/index.html", _supportsNativeWebSocket);
            RegisterSingleInstance(HttpServer, false);
            progress.Report(10);

            ServerManager = new ServerManager(this, JsonSerializer, LogManager.GetLogger("ServerManager"), ServerConfigurationManager);
            RegisterSingleInstance(ServerManager);

            var innerProgress = new ActionableProgress <double>();

            innerProgress.RegisterAction(p => progress.Report((.75 * p) + 15));

            await RegisterMediaEncoder(innerProgress).ConfigureAwait(false);

            progress.Report(90);

            ImageProcessor = new ImageProcessor(LogManager.GetLogger("ImageProcessor"), ServerConfigurationManager.ApplicationPaths, FileSystemManager, JsonSerializer, MediaEncoder);
            RegisterSingleInstance(ImageProcessor);

            SyncManager = new SyncManager(LibraryManager, SyncRepository, ImageProcessor, LogManager.GetLogger("SyncManager"));
            RegisterSingleInstance(SyncManager);

            DtoService = new DtoService(Logger, LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ServerConfigurationManager, FileSystemManager, ProviderManager, () => ChannelManager, SyncManager);
            RegisterSingleInstance(DtoService);

            var encryptionManager = new EncryptionManager();

            RegisterSingleInstance <IEncryptionManager>(encryptionManager);

            ConnectManager = new ConnectManager(LogManager.GetLogger("Connect"), ApplicationPaths, JsonSerializer, encryptionManager, HttpClient, this, ServerConfigurationManager, UserManager, ProviderManager);
            RegisterSingleInstance(ConnectManager);

            DeviceManager = new DeviceManager(new DeviceRepository(ApplicationPaths, JsonSerializer), UserManager, FileSystemManager, LibraryMonitor, ConfigurationManager, LogManager.GetLogger("DeviceManager"));
            RegisterSingleInstance(DeviceManager);

            SessionManager = new SessionManager(UserDataManager, ServerConfigurationManager, Logger, UserRepository, LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, ItemRepository, JsonSerializer, this, HttpClient, AuthenticationRepository, DeviceManager);
            RegisterSingleInstance(SessionManager);

            var newsService = new Server.Implementations.News.NewsService(ApplicationPaths, JsonSerializer);

            RegisterSingleInstance <INewsService>(newsService);

            var fileOrganizationService = new FileOrganizationService(TaskManager, FileOrganizationRepository, LogManager.GetLogger("FileOrganizationService"), LibraryMonitor, LibraryManager, ServerConfigurationManager, FileSystemManager, ProviderManager);

            RegisterSingleInstance <IFileOrganizationService>(fileOrganizationService);

            progress.Report(15);

            ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, Logger, ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, LocalizationManager, HttpClient);
            RegisterSingleInstance(ChannelManager);

            TVSeriesManager = new TVSeriesManager(UserManager, UserDataManager, LibraryManager);
            RegisterSingleInstance(TVSeriesManager);

            var appThemeManager = new AppThemeManager(ApplicationPaths, FileSystemManager, JsonSerializer, Logger);

            RegisterSingleInstance <IAppThemeManager>(appThemeManager);

            var dlnaManager = new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LogManager.GetLogger("Dlna"), JsonSerializer);

            RegisterSingleInstance <IDlnaManager>(dlnaManager);

            var connectionManager = new ConnectionManager(dlnaManager, ServerConfigurationManager, LogManager.GetLogger("UpnpConnectionManager"), HttpClient);

            RegisterSingleInstance <IConnectionManager>(connectionManager);

            CollectionManager = new CollectionManager(LibraryManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("CollectionManager"));
            RegisterSingleInstance(CollectionManager);

            var playlistManager = new PlaylistManager(LibraryManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("PlaylistManager"), UserManager);

            RegisterSingleInstance <IPlaylistManager>(playlistManager);

            LiveTvManager = new LiveTvManager(ServerConfigurationManager, FileSystemManager, Logger, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer);
            RegisterSingleInstance(LiveTvManager);

            UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, FileSystemManager, UserManager, ChannelManager, LiveTvManager, ApplicationPaths, playlistManager);
            RegisterSingleInstance(UserViewManager);

            var contentDirectory = new ContentDirectory(dlnaManager, UserDataManager, ImageProcessor, LibraryManager, ServerConfigurationManager, UserManager, LogManager.GetLogger("UpnpContentDirectory"), HttpClient, LocalizationManager);

            RegisterSingleInstance <IContentDirectory>(contentDirectory);

            NotificationManager = new NotificationManager(LogManager, UserManager, ServerConfigurationManager);
            RegisterSingleInstance(NotificationManager);

            SubtitleManager = new SubtitleManager(LogManager.GetLogger("SubtitleManager"), FileSystemManager, LibraryMonitor, LibraryManager, ItemRepository);
            RegisterSingleInstance(SubtitleManager);

            ChapterManager = new ChapterManager(LibraryManager, LogManager.GetLogger("ChapterManager"), ServerConfigurationManager, ItemRepository);
            RegisterSingleInstance(ChapterManager);

            EncodingManager = new EncodingManager(FileSystemManager, Logger,
                                                  MediaEncoder, ChapterManager);
            RegisterSingleInstance(EncodingManager);

            var activityLogRepo = await GetActivityLogRepository().ConfigureAwait(false);

            RegisterSingleInstance(activityLogRepo);
            RegisterSingleInstance <IActivityManager>(new ActivityManager(LogManager.GetLogger("ActivityManager"), activityLogRepo, UserManager));

            var authContext = new AuthorizationContext();

            RegisterSingleInstance <IAuthorizationContext>(authContext);
            RegisterSingleInstance <ISessionContext>(new SessionContext(UserManager, authContext, SessionManager));
            RegisterSingleInstance <IAuthService>(new AuthService(UserManager, SessionManager, authContext, ServerConfigurationManager));

            RegisterSingleInstance <ISubtitleEncoder>(new SubtitleEncoder(LibraryManager, LogManager.GetLogger("SubtitleEncoder"), ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer));

            var displayPreferencesTask = Task.Run(async() => await ConfigureDisplayPreferencesRepositories().ConfigureAwait(false));
            var itemsTask    = Task.Run(async() => await ConfigureItemRepositories().ConfigureAwait(false));
            var userdataTask = Task.Run(async() => await ConfigureUserDataRepositories().ConfigureAwait(false));

            await ConfigureNotificationsRepository().ConfigureAwait(false);

            progress.Report(92);

            await Task.WhenAll(itemsTask, displayPreferencesTask, userdataTask).ConfigureAwait(false);

            progress.Report(100);

            SetStaticProperties();

            await((UserManager)UserManager).Initialize().ConfigureAwait(false);

            SetKernelProperties();
        }
Пример #20
0
        private void MoveToContentDirectoryPage(ContentDirectory selectedContentDirectory)
        {
            var parameters = new NavigationParameters(mediaServer.Id, selectedContentDirectory.Id);

            navigationService.Navigate(PageTokens.Directory.ToString(), parameters.ToString());
        }
Пример #21
0
        static void ThreadFunc()
        {
            string     masterBedroom = "uuid:RINCON_000E5810848C01400";
            ZonePlayer zonePlayer    = new ZonePlayer(masterBedroom);

            Console.WriteLine(zonePlayer.DeviceProperties.Icon);
            //UPnPDevice mediaServer = zonePlayer.MediaServer;
            //UPnPDevice mediaRenderer = zonePlayer.MediaRenderer;
            //AudioIn audioIn = zonePlayer.AudioIn;
            DeviceProperties deviceProperties = zonePlayer.DeviceProperties;
            RenderingControl renderingControl = zonePlayer.RenderingControl;
            AVTransport      avTransport      = zonePlayer.AVTransport;
            ContentDirectory contentDirectory = zonePlayer.ContentDirectory;
            GroupManagement  groupManagement  = zonePlayer.GroupManagement;

            //ZoneGroupTopology zoneGroupTopology = zonePlayer.ZoneGroupTopology;
            //ConnectionManager connectionManager = zonePlayer.ConnectionManager;

            foreach (XPathNavigator node in contentDirectory.Browse("0", BrowseFlags.BrowseDirectChildren, "*", ""))
            {
                Console.WriteLine(node.OuterXml);

#if FOO
                string path = HttpUtility.UrlDecode(node.SelectSingleNode("@id", Sonority.XPath.Globals.Manager).Value);
                path = path.Replace(@"S://", @"\\");
                path = path.Replace('/', '\\');
                string destination = Path.Combine(@"c:\temp\nuevo", Path.GetFileName(path));
                Console.WriteLine("{0}", path);

                File.Copy(path, destination);
#endif
            }

            foreach (QueueItem node in zonePlayer.Queue)
            {
                Console.WriteLine(node);
            }
            zonePlayer.Queue.ToString();

            avTransport.PropertyChanged      += new PropertyChangedEventHandler(OnPropertyChanged);
            contentDirectory.PropertyChanged += new PropertyChangedEventHandler(OnPropertyChanged);
            renderingControl.PropertyChanged += new PropertyChangedEventHandler(OnPropertyChanged);

#if FOO
            using (foo bar = new foo())
            {
                // check updateIDs first
                Queue <string> queue = new Queue <string>();
                queue.Enqueue("S:");
                queue.Enqueue("0");

                while (queue.Count > 0)
                {
                    string currentObject = queue.Dequeue();
                    // box is down, ignore for now.
                    if (currentObject.StartsWith("S://13CFB6DD7F03432", StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    foreach (XPathNavigator node in contentDirectory.Browse(currentObject, BrowseFlags.BrowseDirectChildren, "*", ""))
                    {
                        if (node.LocalName == "container")
                        {
                            // recurse into container
                            queue.Enqueue(node.SelectSingleNode("@id").Value);
                        }

                        bar.AddRecord(
                            node.SelectSingleNode("@id", XPath.Globals.Manager).Value,
                            node.SelectSingleNode("@parentID", XPath.Globals.Manager).Value,
                            0,
                            node);
                    }
                }
            }

            Thread.Sleep(Timeout.Infinite);

            Console.WriteLine(contentDirectory.ToString());
            Console.WriteLine(avTransport.ToString());


            // avTransport.Play("1");
#endif

            while (true)
            {
                Thread.Sleep(30000);

                foreach (ZoneGroup zp in disc.Topology)
                {
                    Console.WriteLine("{0} -> {1}", zp.Coordinator.UniqueDeviceName, zp.Coordinator.DeviceProperties.ZoneName);
                }
            }
        }
Пример #22
0
 /// <inheritdoc />
 public Task <ContentFileInfo> RemoveAsync(ContentHash contentHash)
 {
     ContentDirectory.TryRemove(contentHash, out var info);
     return(Task.FromResult(info));
 }
Пример #23
0
 /// <summary>
 /// For testing purposes only.
 /// Attempts to add the given file info for the hash.
 /// </summary>
 internal bool TryAdd(ContentHash hash, ContentFileInfo fileInfo)
 {
     return(ContentDirectory.TryAdd(hash, fileInfo));
 }
Пример #24
0
        private HttpHandlerResult ProcessContent(HttpListenerContext context, string localPath, ContentDirectory directory)
        {
            if (Path.DirectorySeparatorChar != '/')
            {
                localPath = localPath.Replace('/', Path.DirectorySeparatorChar);
            }

            var localFilename = Path.Combine(directory.DirectoryPath, localPath);

            // Ensure requested content is within the specified directory
            // IE, prevent relative path hacking
            var fullRootPath      = Path.GetFullPath(directory.DirectoryPath);
            var fullLocalFilename = Path.GetFullPath(localFilename);

            if (!fullLocalFilename.StartsWith(fullRootPath))
            {
                return(HttpHandlerResult.NotFound()
                       .SetText($"Requested file is outisde of the content directory! [{fullLocalFilename}]"));
            }

            var localFile = new FileInfo(fullLocalFilename);

            // Ensure file exists
            if (!localFile.Exists)
            {
                return(HttpHandlerResult.NotFound()
                       .SetText($"File not found! [{fullLocalFilename}]"));
            }

            // HTTP Caching - Last-Modified
            var ifModifiedSince = context.Request.Headers.Get("If-Modified-Since");

            if (DateTime.TryParse(ifModifiedSince, out var ifModifiedSinceValue))
            {
                if (localFile.LastWriteTime.TrimMilliseconds() <= ifModifiedSinceValue)
                {
                    return(HttpHandlerResult.Status(HttpStatusCode.NotModified));
                }
            }

            return(HttpHandlerResult.File(Context, fullLocalFilename)
                   .SetHeader("Last-Modified", localFile.LastWriteTimeUtc.ToString("r")));
        }
Пример #25
0
 public long ContentDirectorySize() => ContentDirectory.GetSizeAsync().GetAwaiter().GetResult();
Пример #26
0
        private async Task SerializeAsync()
        {
            if (ContentDirectory == null || ContentDirectory.Count == 0)
            {
                return;
            }

            var openTask         = _fileSystem.OpenSafeAsync(FilePath, FileAccess.Write, FileMode.Create, FileShare.Delete);
            var sync             = new object();
            var writeHeader      = true;
            var entries          = ContentDirectory.ToArray();
            var entriesRemaining = entries.Length;
            var startIndex       = 0;
            var tasks            = new List <Task>();

            GetSizeAndReplicaCount(out var contentSize, out var replicaCount);

            using (var stream = await openTask)
            {
                Action <int, int> writeChunk = (index, count) =>
                {
                    var endIndexExclusive = index + count;
                    var entryCount        = endIndexExclusive - index;
                    var bufferLength      = entryCount * BinaryEntrySize;
                    var partitionBuffer   = new byte[bufferLength];
                    var partitionContext  = new BufferSerializeContext(partitionBuffer);

                    for (var i = index; i < endIndexExclusive; i++)
                    {
                        ContentFileInfo entry = entries[i].Value;
                        partitionContext.SerializeFull(entries[i].Key);
                        partitionContext.Serialize(entry.FileSize);
                        partitionContext.Serialize(entry.LastAccessedFileTimeUtc);
                        partitionContext.Serialize(UnusedAccessCount);
                        partitionContext.Serialize(entry.ReplicaCount);
                    }

                    lock (sync)
                    {
                        if (writeHeader)
                        {
                            writeHeader = false;
                            var headerBuffer  = new byte[22];
                            var headerContext = new BufferSerializeContext(headerBuffer);
                            headerContext.Serialize(BinaryFormatMagicFlag);
                            headerContext.Serialize(BinaryFormatVersion);
                            headerContext.Serialize(entries.Length);
                            headerContext.Serialize(contentSize);
                            headerContext.Serialize(replicaCount);
                            stream.Write(headerBuffer, 0, headerBuffer.Length);
                        }

                        stream.Write(partitionBuffer, 0, partitionContext.Offset);
                    }
                };

                while (startIndex < entries.Length)
                {
                    var i          = startIndex;
                    var chunkCount = Math.Min(entriesRemaining, BinaryMaxEntriesPerChunk);
                    tasks.Add(Task.Run(() => writeChunk(i, chunkCount)));
                    startIndex       += chunkCount;
                    entriesRemaining -= chunkCount;
                }

                await TaskSafetyHelpers.WhenAll(tasks);

                Contract.Assert(startIndex == entries.Length);
            }
        }
Пример #27
0
        /// <inheritdoc />
        public Task <IReadOnlyList <ContentInfo> > EnumerateContentInfoAsync()
        {
            var snapshot = ContentDirectory.ToArray();

            return(Task.FromResult <IReadOnlyList <ContentInfo> >(snapshot.Select(x => new ContentInfo(x.Key, x.Value.FileSize, DateTime.FromFileTimeUtc(x.Value.LastAccessedFileTimeUtc))).ToList()));
        }
Пример #28
0
 public static string Content(this UrlHelper helper, ContentDirectory dir, string fileWithExt)
 {
     return(helper.Content(String.Format("~/Content/{0}/{1}", dir.ToString(), fileWithExt)));
 }
        public object Get(GetContentDirectory request)
        {
            var xml = ContentDirectory.GetServiceXml(Request.Headers.ToDictionary());

            return(_resultFactory.GetResult(Request, xml, XMLContentType));
        }
Пример #30
0
 public SearchService(IContextFactory factory, ContentDirectory contentDirectory)
 {
     _factory          = factory;
     _contentDirectory = contentDirectory;
 }
Пример #31
0
 /// <inheritdoc />
 public bool TryGetFileInfo(ContentHash contentHash, out ContentFileInfo fileInfo)
 {
     return(ContentDirectory.TryGetValue(contentHash, out fileInfo));
 }