public ImageRefreshOptions(IDirectoryService directoryService)
        {
            ImageRefreshMode = ImageRefreshMode.Default;
            DirectoryService = directoryService;

            ReplaceImages = new List<ImageType>();
        }
        public List<LocalImageInfo> GetImages(IHasImages item, IDirectoryService directoryService)
        {
            var parentPath = Path.GetDirectoryName(item.Path);

            var parentPathFiles = directoryService.GetFileSystemEntries(parentPath)
                .ToList();

            var nameWithoutExtension = _fileSystem.GetFileNameWithoutExtension(item.Path);

            var files = GetFilesFromParentFolder(nameWithoutExtension, parentPathFiles);

            if (files.Count > 0)
            {
                return files;
            }

            var metadataPath = Path.Combine(parentPath, "metadata");

            if (parentPathFiles.Any(i => string.Equals(i.FullName, metadataPath, StringComparison.OrdinalIgnoreCase)))
            {
                return GetFilesFromParentFolder(nameWithoutExtension, directoryService.GetFiles(metadataPath));
            }

            return new List<LocalImageInfo>();
        }
		public LoginViewModel (IDirectoryService service)
		{
			this.service = service;

			Username = "";
			Password = "";
		}
Example #4
0
        public LoginViewModel(IDirectoryService service)
        {
            this.service = service;

            Username = string.Empty;
            Password = string.Empty;
        }
Example #5
0
        /// <summary>
        /// Sets the initial item values.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="parent">The parent.</param>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="libraryManager">The library manager.</param>
        /// <param name="directoryService">The directory service.</param>
        /// <exception cref="System.ArgumentException">Item must have a path</exception>
        public static void SetInitialItemValues(BaseItem item, Folder parent, IFileSystem fileSystem, ILibraryManager libraryManager, IDirectoryService directoryService)
        {
            // This version of the below method has no ItemResolveArgs, so we have to require the path already being set
            if (string.IsNullOrWhiteSpace(item.Path))
            {
                throw new ArgumentException("Item must have a Path");
            }

            // If the resolver didn't specify this
            if (parent != null)
            {
                item.Parent = parent;
            }

            item.Id = libraryManager.GetNewItemId(item.Path, item.GetType());

            item.IsLocked = item.Path.IndexOf("[dontfetchmeta]", StringComparison.OrdinalIgnoreCase) != -1 ||
                item.Parents.Any(i => i.IsLocked);

            // Make sure DateCreated and DateModified have values
            var fileInfo = directoryService.GetFile(item.Path);
            item.DateModified = fileSystem.GetLastWriteTimeUtc(fileInfo);
            SetDateCreated(item, fileSystem, fileInfo);

            EnsureName(item, fileInfo);
        }
Example #6
0
        public RibbonViewModel(INavigationService navigationService, IUIVisualizerService uiVisualizerService,
            ICommandManager commandManager, IRecentlyUsedItemsService recentlyUsedItemsService, IProcessService processService,
            IMessageService messageService, ISelectDirectoryService selectDirectoryService, IDirectoryService directoryService)
        {
            Argument.IsNotNull(() => navigationService);
            Argument.IsNotNull(() => uiVisualizerService);
            Argument.IsNotNull(() => commandManager);
            Argument.IsNotNull(() => recentlyUsedItemsService);
            Argument.IsNotNull(() => processService);
            Argument.IsNotNull(() => messageService);
            Argument.IsNotNull(() => selectDirectoryService);
            Argument.IsNotNull(() => directoryService);

            _navigationService = navigationService;
            _uiVisualizerService = uiVisualizerService;
            _recentlyUsedItemsService = recentlyUsedItemsService;
            _processService = processService;
            _messageService = messageService;
            _selectDirectoryService = selectDirectoryService;
            _directoryService = directoryService;

            OpenProject = new Command(OnOpenProjectExecute);
            OpenRecentlyUsedItem = new Command<string>(OnOpenRecentlyUsedItemExecute);
            OpenInExplorer = new Command<string>(OnOpenInExplorerExecute);
            UnpinItem = new Command<string>(OnUnpinItemExecute);
            PinItem = new Command<string>(OnPinItemExecute);

            ShowKeyboardMappings = new Command(OnShowKeyboardMappingsExecute);

            commandManager.RegisterCommand("File.Open", OpenProject, this);

            var assembly = AssemblyHelper.GetEntryAssembly();
            Title = assembly.Title();
        }
Example #7
0
        public AppDataService(IMessageService messageService, ISaveFileService saveFileService, 
            IProcessService processService, IDirectoryService directoryService, IFileService fileService)
        {
            Argument.IsNotNull(() => messageService);
            Argument.IsNotNull(() => saveFileService);
            Argument.IsNotNull(() => processService);
            Argument.IsNotNull(() => directoryService);
            Argument.IsNotNull(() => fileService);

            _messageService = messageService;
            _saveFileService = saveFileService;
            _processService = processService;
            _directoryService = directoryService;
            _fileService = fileService;

            ExclusionFilters = new List<string>(new []
            {
                "licenseinfo.xml",
                "*.log"
            });

            var applicationDataDirectory = Catel.IO.Path.GetApplicationDataDirectory();

            _directoryService.Create(applicationDataDirectory);

            ApplicationDataDirectory = applicationDataDirectory;
        }
 public EndpointResolverService(IDirectoryService directoryService, IDefaultEndpointConfiguration defaultEndpointConfiguration, IUrlBuilder urlBuilder, IDirectoryRepository directoryRepository, ILogger logger)
 {
     _directoryService = directoryService;
     _defaultEndpointConfiguration = defaultEndpointConfiguration;
     _urlBuilder = urlBuilder;
     _directoryRepository = directoryRepository;
     _logger = logger;
 }
 public DirectoryController(IEndpointResolverService endpointResolverService, IAccountSettings accountSettings, ICallService callService, ILogger logger, IDirectoryService directoryService)
 {
     _endpointResolverService = endpointResolverService;
     _accountSettings = accountSettings;
     _callService = callService;
     _logger = logger;
     _directoryService = directoryService;
 }
		public override bool FinishedLaunching (UIApplication app, NSDictionary options)
		{
			if(!UIDevice.CurrentDevice.CheckSystemVersion(7,0))
				Theme.Apply ();

			//
			// Create the service
			//

			// Local CSV file
			service = MemoryDirectoryService.FromCsv ("Data/XamarinDirectory.csv");

			// LDAP service - uncomment to try it out.
			//service = new LdapDirectoryService {
			//	Host = "ldap.mit.edu",
			//	SearchBase = "dc=mit,dc=edu",
			//};

			//
			// Load the favorites
			//
			var favoritesRepository = XmlFavoritesRepository.OpenIsolatedStorage ("Favorites.xml");

			if (favoritesRepository.GetAll ().Count () == 0) {
				favoritesRepository = XmlFavoritesRepository.OpenFile ("Data/XamarinFavorites.xml");
				favoritesRepository.IsolatedStorageName = "Favorites.xml";
			}

			//
			// Load the last search
			//
			Search search = null;
			try {
				search = Search.Open ("Search.xml");
			}
			catch (Exception) {
				search = new Search ("Search.xml");
			}

			//
			// Build the UI
			//
			favoritesViewController = new FavoritesViewController (favoritesRepository, service, search);

			window = new UIWindow (UIScreen.MainScreen.Bounds);
			window.RootViewController = new UINavigationController (favoritesViewController);
			window.MakeKeyAndVisible ();

			//
			// Show the login screen at startup
			//
			var login = new LoginViewController (service);
			favoritesViewController.PresentViewController (login, false, null);

			return true;
		}
        public CodeGenerationService(IEntityPluralService entityPluralService, IFileService fileService, IDirectoryService directoryService)
        {
            Argument.IsNotNull(() => entityPluralService);
            Argument.IsNotNull(() => fileService);
            Argument.IsNotNull(() => directoryService);

            _entityPluralService = entityPluralService;
            _fileService = fileService;
            _directoryService = directoryService;
        }
		public SearchViewModel (IDirectoryService service, Search search)
		{
			if (service == null) throw new ArgumentNullException ("service");
			this.service = service;

			if (search == null) throw new ArgumentNullException ("search");
			this.search = search;

			SetGroupedPeople ();
		}
        public List<LocalImageInfo> GetImages(IHasImages item, IDirectoryService directoryService)
        {
            var files = GetFiles(item, true, directoryService).ToList();

            var list = new List<LocalImageInfo>();

            PopulateImages(item, list, files, true, directoryService);

            return list;
        }
Example #14
0
        public bool HasChanged(IHasMetadata item, IDirectoryService directoryService)
        {
            var liveTvItem = item as ILiveTvRecording;

            if (liveTvItem != null)
            {
                return !liveTvItem.HasImage(ImageType.Primary);
            }
            return false;
        }
        public bool HasChanged(IHasMetadata item, MetadataStatus status, IDirectoryService directoryService)
        {
            var liveTvItem = item as LiveTvProgram;

            if (liveTvItem != null)
            {
                return !liveTvItem.HasImage(ImageType.Primary);
            }
            return false;
        }
        public bool HasChanged(IHasMetadata item, IDirectoryService directoryService, DateTime date)
        {
            var channelItem = item as IChannelItem;

            if (channelItem != null)
            {
                return !channelItem.HasImage(ImageType.Primary) && !string.IsNullOrWhiteSpace(channelItem.OriginalImageUrl);
            }
            return false;
        }
        public List<LocalImageInfo> GetImages(IHasImages item, IDirectoryService directoryService)
        {
            var path = item.GetInternalMetadataPath();

            try
            {
                return new LocalImageProvider(_fileSystem).GetImages(item, path, true, directoryService);
            }
            catch (DirectoryNotFoundException)
            {
                return new List<LocalImageInfo>();
            }
        }
        public List<LocalImageInfo> GetImages(IHasImages item, IDirectoryService directoryService)
        {
            var path = _config.ApplicationPaths.GetInternalMetadataPath(item.Id);

            try
            {
                return new LocalImageProvider().GetImages(item, path, directoryService);
            }
            catch (DirectoryNotFoundException)
            {
                return new List<LocalImageInfo>();
            }
        }
        public ImageRepository(HttpServerUtilityBase server, IDirectoryService directory, string rootPath)
        {
            string path = server.MapPath(rootPath);
            var files = directory.EnumerateFiles(path, "*.jpg");

            foreach (var file in files) {

                string imageUrl = VirtualPathUtility.Combine(VirtualPathUtility.AppendTrailingSlash(rootPath), Path.GetFileName(file));
                string metaPath = file + ".meta";
                using (var reader = directory.GetReader(metaPath)) {
                    _images.Add(new ImageMetadata(imageUrl, reader));
                }
            }
        }
        public List<LocalImageInfo> GetImages(IHasImages item, IDirectoryService directoryService)
        {
            var name = _fileSystem.GetValidFilename(item.Name);

            var path = Path.Combine(_config.ApplicationPaths.GeneralPath, name);

            try
            {
                return new LocalImageProvider(_fileSystem).GetImages(item, path, directoryService);
            }
            catch (DirectoryNotFoundException)
            {
                return new List<LocalImageInfo>();
            }
        }
Example #21
0
        public bool ValidateImages(IHasImages item, IEnumerable<IImageProvider> providers, IDirectoryService directoryService)
        {
            var hasChanges = item.ValidateImages(directoryService);

            foreach (var provider in providers.OfType<ILocalImageFileProvider>())
            {
                var images = provider.GetImages(item, directoryService);

                if (MergeImages(item, images))
                {
                    hasChanges = true;
                }
            }

            return hasChanges;
        }
Example #22
0
        protected override async Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
        {
            await base.ValidateChildrenInternal(progress, cancellationToken, recursive, refreshChildMetadata, refreshOptions, directoryService)
                .ConfigureAwait(false);

            // Not the best way to handle this, but it solves an issue
            // CollectionFolders aren't always getting saved after changes
            // This means that grabbing the item by Id may end up returning the old one
            // Fix is in two places - make sure the folder gets saved
            // And here to remedy it for affected users.
            // In theory this can be removed eventually.
            foreach (var item in Children)
            {
                LibraryManager.RegisterItem(item);
            }
        }
Example #23
0
        public bool ValidateImages(IHasImages item, IEnumerable<IImageProvider> providers, IDirectoryService directoryService)
        {
            var hasChanges = false;

            if (!(item is Photo))
            {
                var images = providers.OfType<ILocalImageFileProvider>()
                    .SelectMany(i => i.GetImages(item, directoryService))
                    .ToList();

                if (MergeImages(item, images))
                {
                    hasChanges = true;
                }
            }

            return hasChanges;
        }
        private IEnumerable<FileSystemInfo> GetFiles(IHasImages item, bool includeDirectories, IDirectoryService directoryService)
        {
            if (item.LocationType != LocationType.FileSystem)
            {
                return new List<FileSystemInfo>();
            }

            var path = item.ContainingFolderPath;

            if (includeDirectories)
            {
                return directoryService.GetFileSystemEntries(path)
                .Where(i => BaseItem.SupportedImageExtensions.Contains(i.Extension, StringComparer.OrdinalIgnoreCase) ||
                (i.Attributes & FileAttributes.Directory) == FileAttributes.Directory);
            }

            return directoryService.GetFiles(path)
                .Where(i => BaseItem.SupportedImageExtensions.Contains(i.Extension, StringComparer.OrdinalIgnoreCase));
        }
        public FavoritesViewController(IFavoritesRepository favoritesRepository, IDirectoryService service, Search savedSearch)
        {
            this.favoritesRepository = favoritesRepository;

            Title = "Favorites";

            viewModel = new FavoritesViewModel (favoritesRepository, groupByLastName: true);
            viewModel.PropertyChanged += HandleViewModelPropertyChanged;

            searchViewModel = new SearchViewModel (service, savedSearch);

            //
            // Configure this view
            //
            var favoritesDelegate = new PeopleGroupsDelegate (TableView);
            favoritesDelegate.PersonSelected += HandlePersonSelected;

            TableView.DataSource = new PeopleGroupsDataSource (viewModel.Groups);
            TableView.Delegate = favoritesDelegate;
            TableView.SectionIndexMinimumDisplayRowCount = 10;

            //
            // Configure the search bar
            //
            searchBar = new UISearchBar (new CGRect (0f, 0f, 320f, 44f)) {
                ShowsScopeBar = true,
            };

            searchBar.ScopeButtonTitles = new[] { "Name", "Title", "Dept", "All" };
            searchBar.SelectedScopeButtonIndex = (int)savedSearch.Property;
            searchController = new UISearchDisplayController (searchBar, this) {
                SearchResultsDataSource = new PeopleGroupsDataSource (searchViewModel.Groups),
                Delegate = new SearchDisplayDelegate (searchViewModel)
            };

            var searchDelegate = new PeopleGroupsDelegate (searchController.SearchResultsTableView);
            searchController.SearchResultsTableView.SectionIndexMinimumDisplayRowCount = 10;
            searchDelegate.PersonSelected += HandleSearchPersonSelected;
            searchController.SearchResultsDelegate = searchDelegate;

            TableView.TableHeaderView = searchBar;
        }
Example #26
0
        private IEnumerable<FileSystemMetadata> GetFiles(IHasImages item, bool includeDirectories, IDirectoryService directoryService)
        {
            if (item.LocationType != LocationType.FileSystem)
            {
                return new List<FileSystemMetadata>();
            }

            var path = item.ContainingFolderPath;

            if (includeDirectories)
            {
                return directoryService.GetFileSystemEntries(path)
                .Where(i => BaseItem.SupportedImageExtensions.Contains(i.Extension, StringComparer.OrdinalIgnoreCase) || i.IsDirectory)

                .OrderBy(i => BaseItem.SupportedImageExtensionsList.IndexOf(i.Extension ?? string.Empty));
            }

            return directoryService.GetFiles(path)
                .Where(i => BaseItem.SupportedImageExtensions.Contains(i.Extension, StringComparer.OrdinalIgnoreCase))
                .OrderBy(i => BaseItem.SupportedImageExtensionsList.IndexOf(i.Extension ?? string.Empty));
        }
Example #27
0
        private ItemResolveArgs CreateResolveArgs(IDirectoryService directoryService)
        {
            var path = ContainingFolderPath;

            var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths, LibraryManager, directoryService)
            {
                FileInfo = new DirectoryInfo(path),
                Path = path,
                Parent = Parent,
                CollectionType = CollectionType
            };

            // Gather child folder and files
            if (args.IsDirectory)
            {
                var isPhysicalRoot = args.IsPhysicalRoot;

                // When resolving the root, we need it's grandchildren (children of user views)
                var flattenFolderDepth = isPhysicalRoot ? 2 : 0;

                var fileSystemDictionary = FileData.GetFilteredFileSystemEntries(directoryService, args.Path, FileSystem, Logger, args, flattenFolderDepth: flattenFolderDepth, resolveShortcuts: isPhysicalRoot || args.IsVf);

                // Need to remove subpaths that may have been resolved from shortcuts
                // Example: if \\server\movies exists, then strip out \\server\movies\action
                if (isPhysicalRoot)
                {
                    var paths = LibraryManager.NormalizeRootPathList(fileSystemDictionary.Keys);

                    fileSystemDictionary = paths.Select(i => (FileSystemInfo)new DirectoryInfo(i)).ToDictionary(i => i.FullName);
                }

                args.FileSystemDictionary = fileSystemDictionary;
            }

            PhysicalLocationsList = args.PhysicalLocations.ToList();

            return args;
        }
Example #28
0
		public static Page GetMainPage ()
		{
			//
			// Create the service
			//

			//
			// Local CSV file
			Service = MemoryDirectoryService.FromCsv ("XamarinDirectory.csv").Result;

			//
			// LDAP service - uncomment to try it out.
			//Service = new LdapDirectoryService {
			//	Host = "ldap.mit.edu",
			//	SearchBase = "dc=mit,dc=edu",
			//};

			var employeeList = new EmployeeListXaml ();

			var mainNav = new NavigationPage (employeeList);

			return mainNav;
		}
Example #29
0
        private MultiItemResolverResult ResolveVideos <T>(Folder parent, IEnumerable <FileSystemMetadata> fileSystemEntries, IDirectoryService directoryService, bool suppportMultiEditions)
            where T : Video, new()
        {
            var files    = new List <FileSystemMetadata>();
            var videos   = new List <BaseItem>();
            var leftOver = new List <FileSystemMetadata>();

            // Loop through each child file/folder and see if we find a video
            foreach (var child in fileSystemEntries)
            {
                if ((child.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
                {
                    leftOver.Add(child);
                }
                else if (IsIgnored(child.Name))
                {
                }
                else
                {
                    files.Add(child);
                }
            }

            var namingOptions = ((LibraryManager)LibraryManager).GetNamingOptions();

            var resolver       = new VideoListResolver(namingOptions, new PatternsLogger());
            var resolverResult = resolver.Resolve(files.Select(i => new FileMetadata
            {
                Id       = i.FullName,
                IsFolder = i.IsDirectory
            }).ToList(), suppportMultiEditions).ToList();

            var result = new MultiItemResolverResult
            {
                ExtraFiles = leftOver,
                Items      = videos
            };

            var isInMixedFolder = resolverResult.Count > 1;

            foreach (var video in resolverResult)
            {
                var firstVideo = video.Files.First();

                var videoItem = new T
                {
                    Path                   = video.Files[0].Path,
                    IsInMixedFolder        = isInMixedFolder,
                    ProductionYear         = video.Year,
                    Name                   = video.Name,
                    AdditionalParts        = video.Files.Skip(1).Select(i => i.Path).ToList(),
                    LocalAlternateVersions = video.AlternateVersions.Select(i => i.Path).ToList()
                };

                SetVideoType(videoItem, firstVideo);
                Set3DFormat(videoItem, firstVideo);

                result.Items.Add(videoItem);
            }

            result.ExtraFiles.AddRange(files.Where(i => !ContainsFile(resolverResult, i)));

            return(result);
        }
Example #30
0
        public List <LocalImageInfo> GetImages(BaseItem item, IEnumerable <string> paths, bool arePathsInMediaFolders, IDirectoryService directoryService)
        {
            IEnumerable <FileSystemMetadata> files = paths.SelectMany(i => _fileSystem.GetFiles(i, BaseItem.SupportedImageExtensions, true, false));

            files = files
                    .OrderBy(i => BaseItem.SupportedImageExtensionsList.IndexOf(i.Extension ?? string.Empty));

            var list = new List <LocalImageInfo>();

            PopulateImages(item, list, files.ToList(), false, directoryService);

            return(list);
        }
Example #31
0
        /// <summary>
        /// Finds a movie based on a child file system entries
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path">The path.</param>
        /// <param name="parent">The parent.</param>
        /// <param name="fileSystemEntries">The file system entries.</param>
        /// <param name="directoryService">The directory service.</param>
        /// <param name="collectionType">Type of the collection.</param>
        /// <returns>Movie.</returns>
        private T FindMovie <T>(string path, Folder parent, List <FileSystemMetadata> fileSystemEntries, IDirectoryService directoryService, string collectionType)
            where T : Video, new()
        {
            var multiDiscFolders = new List <FileSystemMetadata>();

            // Search for a folder rip
            foreach (var child in fileSystemEntries)
            {
                var filename = child.Name;

                if ((child.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
                {
                    if (IsDvdDirectory(filename))
                    {
                        var movie = new T
                        {
                            Path      = path,
                            VideoType = VideoType.Dvd
                        };
                        Set3DFormat(movie);
                        return(movie);
                    }
                    if (IsBluRayDirectory(filename))
                    {
                        var movie = new T
                        {
                            Path      = path,
                            VideoType = VideoType.BluRay
                        };
                        Set3DFormat(movie);
                        return(movie);
                    }

                    multiDiscFolders.Add(child);
                }
                else if (IsDvdFile(filename))
                {
                    var movie = new T
                    {
                        Path      = path,
                        VideoType = VideoType.Dvd
                    };
                    Set3DFormat(movie);
                    return(movie);
                }
            }

            var supportsMultiVersion = !string.Equals(collectionType, CollectionType.HomeVideos) &&
                                       !string.Equals(collectionType, CollectionType.Photos) &&
                                       !string.Equals(collectionType, CollectionType.MusicVideos);

            var result = ResolveVideos <T>(parent, fileSystemEntries, directoryService, supportsMultiVersion);

            if (result.Items.Count == 1)
            {
                var movie = (T)result.Items[0];
                movie.IsInMixedFolder = false;
                movie.Name            = Path.GetFileName(movie.ContainingFolderPath);
                return(movie);
            }

            if (result.Items.Count == 0 && multiDiscFolders.Count > 0)
            {
                return(GetMultiDiscMovie <T>(multiDiscFolders, directoryService));
            }

            return(null);
        }
Example #32
0
        private MultiItemResolverResult ResolveVideos <T>(
            Folder parent,
            IEnumerable <FileSystemMetadata> fileSystemEntries,
            IDirectoryService directoryService,
            bool suppportMultiEditions,
            string collectionType,
            bool parseName)
            where T : Video, new()
        {
            var files    = new List <FileSystemMetadata>();
            var videos   = new List <BaseItem>();
            var leftOver = new List <FileSystemMetadata>();

            // Loop through each child file/folder and see if we find a video
            foreach (var child in fileSystemEntries)
            {
                // This is a hack but currently no better way to resolve a sometimes ambiguous situation
                if (string.IsNullOrEmpty(collectionType))
                {
                    if (string.Equals(child.Name, "tvshow.nfo", StringComparison.OrdinalIgnoreCase) ||
                        string.Equals(child.Name, "season.nfo", StringComparison.OrdinalIgnoreCase))
                    {
                        return(null);
                    }
                }

                if (child.IsDirectory)
                {
                    leftOver.Add(child);
                }
                else if (!IsIgnored(child.Name))
                {
                    files.Add(child);
                }
            }

            var namingOptions = ((LibraryManager)LibraryManager).GetNamingOptions();

            var resolver       = new VideoListResolver(namingOptions);
            var resolverResult = resolver.Resolve(files, suppportMultiEditions).ToList();

            var result = new MultiItemResolverResult
            {
                ExtraFiles = leftOver,
                Items      = videos
            };

            var isInMixedFolder = resolverResult.Count > 1 || (parent != null && parent.IsTopParent);

            foreach (var video in resolverResult)
            {
                var firstVideo = video.Files[0];

                var videoItem = new T
                {
                    Path            = video.Files[0].Path,
                    IsInMixedFolder = isInMixedFolder,
                    ProductionYear  = video.Year,
                    Name            = parseName ?
                                      video.Name :
                                      Path.GetFileNameWithoutExtension(video.Files[0].Path),
                    AdditionalParts        = video.Files.Skip(1).Select(i => i.Path).ToArray(),
                    LocalAlternateVersions = video.AlternateVersions.Select(i => i.Path).ToArray()
                };

                SetVideoType(videoItem, firstVideo);
                Set3DFormat(videoItem, firstVideo);

                result.Items.Add(videoItem);
            }

            result.ExtraFiles.AddRange(files.Where(i => !ContainsFile(resolverResult, i)));

            return(result);
        }
Example #33
0
 public List <LocalImageInfo> GetImages(BaseItem item, string path, bool isPathInMediaFolder, IDirectoryService directoryService)
 {
     return(GetImages(item, new[] { path }, isPathInMediaFolder, directoryService));
 }
Example #34
0
        public RoomsController(IBookingRepository bookingRepository, ILocationRepository locationRepository, IRoomRepository roomRepository, IDirectoryService directoryService)
        {
            _logger = NLog.LogManager.GetCurrentClassLogger();

            _directoryService = directoryService;

            _locationRepository = locationRepository;
            _roomRepository     = roomRepository;
            _bookingRepository  = bookingRepository;
        }
Example #35
0
        /// <summary>
        /// Adds the external subtitles.
        /// </summary>
        /// <param name="video">The video.</param>
        /// <param name="currentStreams">The current streams.</param>
        private void AddExternalSubtitles(Video video, List <MediaStream> currentStreams, IDirectoryService directoryService)
        {
            var files = GetSubtitleFiles(video, directoryService);

            var startIndex = currentStreams.Count;
            var streams    = new List <MediaStream>();

            var videoFileNameWithoutExtension = Path.GetFileNameWithoutExtension(video.Path);

            foreach (var file in files)
            {
                var fullName = file.FullName;

                var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fullName);

                // If the subtitle file matches the video file name
                if (string.Equals(videoFileNameWithoutExtension, fileNameWithoutExtension, StringComparison.OrdinalIgnoreCase))
                {
                    streams.Add(new MediaStream
                    {
                        Index      = startIndex++,
                        Type       = MediaStreamType.Subtitle,
                        IsExternal = true,
                        Path       = fullName,
                        Codec      = Path.GetExtension(fullName).ToLower().TrimStart('.')
                    });
                }
                else if (fileNameWithoutExtension.StartsWith(videoFileNameWithoutExtension + ".", StringComparison.OrdinalIgnoreCase))
                {
                    // Support xbmc naming conventions - 300.spanish.srt
                    var language = fileNameWithoutExtension.Split('.').LastOrDefault();

                    // Try to translate to three character code
                    // Be flexible and check against both the full and three character versions
                    var culture = _localization.GetCultures()
                                  .FirstOrDefault(i => string.Equals(i.DisplayName, language, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Name, language, StringComparison.OrdinalIgnoreCase) || string.Equals(i.ThreeLetterISOLanguageName, language, StringComparison.OrdinalIgnoreCase) || string.Equals(i.TwoLetterISOLanguageName, language, StringComparison.OrdinalIgnoreCase));

                    if (culture != null)
                    {
                        language = culture.ThreeLetterISOLanguageName;
                    }

                    streams.Add(new MediaStream
                    {
                        Index      = startIndex++,
                        Type       = MediaStreamType.Subtitle,
                        IsExternal = true,
                        Path       = fullName,
                        Codec      = Path.GetExtension(fullName).ToLower().TrimStart('.'),
                        Language   = language
                    });
                }
            }

            video.SubtitleFiles = streams.Select(i => i.Path).OrderBy(i => i).ToList();

            currentStreams.AddRange(streams);
        }
Example #36
0
        protected async Task Fetch(Video video, CancellationToken cancellationToken, InternalMediaInfoResult data, IIsoMount isoMount, BlurayDiscInfo blurayInfo, IDirectoryService directoryService)
        {
            var mediaInfo    = MediaEncoderHelpers.GetMediaInfo(data);
            var mediaStreams = mediaInfo.MediaStreams;

            video.TotalBitrate = mediaInfo.TotalBitrate;
            video.FormatName   = (mediaInfo.Format ?? string.Empty)
                                 .Replace("matroska", "mkv", StringComparison.OrdinalIgnoreCase);

            if (data.format != null)
            {
                // For dvd's this may not always be accurate, so don't set the runtime if the item already has one
                var needToSetRuntime = video.VideoType != VideoType.Dvd || video.RunTimeTicks == null || video.RunTimeTicks.Value == 0;

                if (needToSetRuntime && !string.IsNullOrEmpty(data.format.duration))
                {
                    video.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(data.format.duration, _usCulture)).Ticks;
                }

                if (video.VideoType == VideoType.VideoFile)
                {
                    var extension = (Path.GetExtension(video.Path) ?? string.Empty).TrimStart('.');

                    video.Container = extension;
                }
                else
                {
                    video.Container = null;
                }

                if (!string.IsNullOrEmpty(data.format.size))
                {
                    video.Size = long.Parse(data.format.size, _usCulture);
                }
                else
                {
                    video.Size = null;
                }
            }

            var mediaChapters = (data.Chapters ?? new MediaChapter[] { }).ToList();
            var chapters      = mediaChapters.Select(GetChapterInfo).ToList();

            if (video.VideoType == VideoType.BluRay || (video.IsoType.HasValue && video.IsoType.Value == IsoType.BluRay))
            {
                FetchBdInfo(video, chapters, mediaStreams, blurayInfo);
            }

            AddExternalSubtitles(video, mediaStreams, directoryService);

            FetchWtvInfo(video, data);

            video.IsHD = mediaStreams.Any(i => i.Type == MediaStreamType.Video && i.Width.HasValue && i.Width.Value >= 1270);

            if (chapters.Count == 0 && mediaStreams.Any(i => i.Type == MediaStreamType.Video))
            {
                AddDummyChapters(video, chapters);
            }

            var videoStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);

            video.VideoBitRate            = videoStream == null ? null : videoStream.BitRate;
            video.DefaultVideoStreamIndex = videoStream == null ? (int?)null : videoStream.Index;

            video.HasSubtitles = mediaStreams.Any(i => i.Type == MediaStreamType.Subtitle);

            ExtractTimestamp(video);

            await _encodingManager.RefreshChapterImages(new ChapterImageRefreshOptions
            {
                Chapters      = chapters,
                Video         = video,
                ExtractImages = false,
                SaveChapters  = false
            }, cancellationToken).ConfigureAwait(false);

            await _itemRepo.SaveMediaStreams(video.Id, mediaStreams, cancellationToken).ConfigureAwait(false);

            await _itemRepo.SaveChapters(video.Id, chapters, cancellationToken).ConfigureAwait(false);
        }
Example #37
0
        private void PopulateBackdrops(BaseItem item, List <LocalImageInfo> images, List <FileSystemMetadata> files, string imagePrefix, bool isInMixedFolder, IDirectoryService directoryService)
        {
            if (!string.IsNullOrEmpty(item.Path))
            {
                var name = item.FileNameWithoutExtension;

                if (!string.IsNullOrEmpty(name))
                {
                    AddImage(files, images, imagePrefix + name + "-fanart", ImageType.Backdrop);

                    // Support without the prefix if it's in it's own folder
                    if (!isInMixedFolder)
                    {
                        AddImage(files, images, name + "-fanart", ImageType.Backdrop);
                    }
                }
            }

            PopulateBackdrops(images, files, imagePrefix, "fanart", "fanart-", isInMixedFolder, ImageType.Backdrop);
            PopulateBackdrops(images, files, imagePrefix, "background", "background-", isInMixedFolder, ImageType.Backdrop);
            PopulateBackdrops(images, files, imagePrefix, "art", "art-", isInMixedFolder, ImageType.Backdrop);

            var extraFanartFolder = files
                                    .FirstOrDefault(i => string.Equals(i.Name, "extrafanart", StringComparison.OrdinalIgnoreCase));

            if (extraFanartFolder != null)
            {
                PopulateBackdropsFromExtraFanart(extraFanartFolder.FullName, images, directoryService);
            }

            PopulateBackdrops(images, files, imagePrefix, "backdrop", "backdrop", isInMixedFolder, ImageType.Backdrop);
        }
Example #38
0
        private void PopulateBackdropsFromExtraFanart(string path, List <LocalImageInfo> images, IDirectoryService directoryService)
        {
            var imageFiles = _fileSystem.GetFiles(path, BaseItem.SupportedImageExtensions, false, false);

            images.AddRange(imageFiles.Where(i => i.Length > 0).Select(i => new LocalImageInfo
            {
                FileInfo = i,
                Type     = ImageType.Backdrop
            }));
        }
Example #39
0
        public IEnumerable <MediaStream> GetExternalSubtitleStreams(Video video,
                                                                    int startIndex,
                                                                    IDirectoryService directoryService,
                                                                    bool clearCache)
        {
            var files = GetSubtitleFiles(video, directoryService, _fileSystem, clearCache);

            var streams = new List <MediaStream>();

            var videoFileNameWithoutExtension = _fileSystem.GetFileNameWithoutExtension(video.Path);

            videoFileNameWithoutExtension = NormalizeFilenameForSubtitleComparison(videoFileNameWithoutExtension);

            foreach (var fullName in files)
            {
                var fileNameWithoutExtension = _fileSystem.GetFileNameWithoutExtension(fullName);
                fileNameWithoutExtension = NormalizeFilenameForSubtitleComparison(fileNameWithoutExtension);

                var codec = Path.GetExtension(fullName).ToLower().TrimStart('.');

                if (string.Equals(codec, "txt", StringComparison.OrdinalIgnoreCase))
                {
                    codec = "srt";
                }

                // If the subtitle file matches the video file name
                if (string.Equals(videoFileNameWithoutExtension, fileNameWithoutExtension, StringComparison.OrdinalIgnoreCase))
                {
                    streams.Add(new MediaStream
                    {
                        Index      = startIndex++,
                        Type       = MediaStreamType.Subtitle,
                        IsExternal = true,
                        Path       = fullName,
                        Codec      = codec
                    });
                }
                else if (fileNameWithoutExtension.StartsWith(videoFileNameWithoutExtension + ".", StringComparison.OrdinalIgnoreCase))
                {
                    var isForced = fullName.IndexOf(".forced.", StringComparison.OrdinalIgnoreCase) != -1 ||
                                   fullName.IndexOf(".foreign.", StringComparison.OrdinalIgnoreCase) != -1;

                    var isDefault = fullName.IndexOf(".default.", StringComparison.OrdinalIgnoreCase) != -1;

                    // Support xbmc naming conventions - 300.spanish.srt
                    var language = fileNameWithoutExtension
                                   .Replace(".forced", string.Empty, StringComparison.OrdinalIgnoreCase)
                                   .Replace(".foreign", string.Empty, StringComparison.OrdinalIgnoreCase)
                                   .Split('.')
                                   .LastOrDefault();

                    // Try to translate to three character code
                    // Be flexible and check against both the full and three character versions
                    var culture = _localization.GetCultures()
                                  .FirstOrDefault(i => string.Equals(i.DisplayName, language, StringComparison.OrdinalIgnoreCase) ||
                                                  string.Equals(i.Name, language, StringComparison.OrdinalIgnoreCase) ||
                                                  string.Equals(i.ThreeLetterISOLanguageName, language, StringComparison.OrdinalIgnoreCase) ||
                                                  string.Equals(i.TwoLetterISOLanguageName, language, StringComparison.OrdinalIgnoreCase));

                    if (culture != null)
                    {
                        language = culture.ThreeLetterISOLanguageName;
                    }

                    streams.Add(new MediaStream
                    {
                        Index      = startIndex++,
                        Type       = MediaStreamType.Subtitle,
                        IsExternal = true,
                        Path       = fullName,
                        Codec      = codec,
                        Language   = language,
                        IsForced   = isForced,
                        IsDefault  = isDefault
                    });
                }
            }

            return(streams);
        }
Example #40
0
 public bool HasChanged(IHasMetadata item, MetadataStatus status, IDirectoryService directoryService)
 {
     return GetSupportedImages(item).Any(i => !item.HasImage(i));
 }
Example #41
0
        /// <summary>
        /// Finds a movie based on a child file system entries.
        /// </summary>
        /// <returns>Movie.</returns>
        private T FindMovie <T>(ItemResolveArgs args, string path, Folder parent, List <FileSystemMetadata> fileSystemEntries, IDirectoryService directoryService, string collectionType, bool parseName)
            where T : Video, new()
        {
            var multiDiscFolders = new List <FileSystemMetadata>();

            var libraryOptions = args.GetLibraryOptions();
            var supportPhotos  = string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase) && libraryOptions.EnablePhotos;
            var photos         = new List <FileSystemMetadata>();

            // Search for a folder rip
            foreach (var child in fileSystemEntries)
            {
                var filename = child.Name;

                if (child.IsDirectory)
                {
                    if (IsDvdDirectory(child.FullName, filename, directoryService))
                    {
                        var movie = new T
                        {
                            Path      = path,
                            VideoType = VideoType.Dvd
                        };
                        Set3DFormat(movie);
                        return(movie);
                    }

                    if (IsBluRayDirectory(child.FullName, filename, directoryService))
                    {
                        var movie = new T
                        {
                            Path      = path,
                            VideoType = VideoType.BluRay
                        };
                        Set3DFormat(movie);
                        return(movie);
                    }

                    multiDiscFolders.Add(child);
                }
                else if (IsDvdFile(filename))
                {
                    var movie = new T
                    {
                        Path      = path,
                        VideoType = VideoType.Dvd
                    };
                    Set3DFormat(movie);
                    return(movie);
                }
                else if (supportPhotos && PhotoResolver.IsImageFile(child.FullName, _imageProcessor))
                {
                    photos.Add(child);
                }
            }

            // TODO: Allow GetMultiDiscMovie in here
            const bool SupportsMultiVersion = true;

            var result = ResolveVideos <T>(parent, fileSystemEntries, directoryService, SupportsMultiVersion, collectionType, parseName) ??
                         new MultiItemResolverResult();

            if (result.Items.Count == 1)
            {
                var videoPath = result.Items[0].Path;
                var hasPhotos = photos.Any(i => !PhotoResolver.IsOwnedByResolvedMedia(LibraryManager, videoPath, i.Name));

                if (!hasPhotos)
                {
                    var movie = (T)result.Items[0];
                    movie.IsInMixedFolder = false;
                    movie.Name            = Path.GetFileName(movie.ContainingFolderPath);
                    return(movie);
                }
            }
            else if (result.Items.Count == 0 && multiDiscFolders.Count > 0)
            {
                return(GetMultiDiscMovie <T>(multiDiscFolders, directoryService));
            }

            return(null);
        }
Example #42
0
 /// <summary>
 /// Determine if the supplied file data points to a music album
 /// </summary>
 public bool IsMusicAlbum(string path, IDirectoryService directoryService, LibraryOptions libraryOptions)
 {
     return(ContainsMusic(directoryService.GetFileSystemEntries(path), true, directoryService, _logger, _fileSystem, libraryOptions, _libraryManager));
 }
Example #43
0
        /// <summary>
        /// Gets the filtered file system entries.
        /// </summary>
        /// <param name="directoryService">The directory service.</param>
        /// <param name="path">The path.</param>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="logger">The logger.</param>
        /// <param name="args">The args.</param>
        /// <param name="flattenFolderDepth">The flatten folder depth.</param>
        /// <param name="resolveShortcuts">if set to <c>true</c> [resolve shortcuts].</param>
        /// <returns>Dictionary{System.StringFileSystemInfo}.</returns>
        /// <exception cref="System.ArgumentNullException">path</exception>
        public static Dictionary <string, FileSystemMetadata> GetFilteredFileSystemEntries(IDirectoryService directoryService,
                                                                                           string path,
                                                                                           IFileSystem fileSystem,
                                                                                           ILogger logger,
                                                                                           ItemResolveArgs args,
                                                                                           int flattenFolderDepth = 0,
                                                                                           bool resolveShortcuts  = true)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException("path");
            }
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }

            if (!resolveShortcuts && flattenFolderDepth == 0)
            {
                return(directoryService.GetFileSystemDictionary(path));
            }

            var entries = directoryService.GetFileSystemEntries(path);

            var dict = new Dictionary <string, FileSystemMetadata>(StringComparer.OrdinalIgnoreCase);

            foreach (var entry in entries)
            {
                var isDirectory = entry.IsDirectory;

                var fullName = entry.FullName;

                if (resolveShortcuts && fileSystem.IsShortcut(fullName))
                {
                    try
                    {
                        var newPath = fileSystem.ResolveShortcut(fullName);

                        if (string.IsNullOrWhiteSpace(newPath))
                        {
                            //invalid shortcut - could be old or target could just be unavailable
                            logger.Warn("Encountered invalid shortcut: " + fullName);
                            continue;
                        }

                        // Don't check if it exists here because that could return false for network shares.
                        var data = fileSystem.GetDirectoryInfo(newPath);

                        // add to our physical locations
                        args.AddAdditionalLocation(newPath);

                        dict[newPath] = data;
                    }
                    catch (Exception ex)
                    {
                        logger.ErrorException("Error resolving shortcut from {0}", ex, fullName);
                    }
                }
                else if (flattenFolderDepth > 0 && isDirectory)
                {
                    foreach (var child in GetFilteredFileSystemEntries(directoryService, fullName, fileSystem, logger, args, flattenFolderDepth: flattenFolderDepth - 1, resolveShortcuts: resolveShortcuts))
                    {
                        dict[child.Key] = child.Value;
                    }
                }
                else
                {
                    dict[fullName] = entry;
                }
            }

            return(dict);
        }
Example #44
0
        /// <summary>
        /// Gets the multi disc movie.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="multiDiscFolders">The folders.</param>
        /// <param name="directoryService">The directory service.</param>
        /// <returns>``0.</returns>
        private T GetMultiDiscMovie <T>(List <FileSystemMetadata> multiDiscFolders, IDirectoryService directoryService)
            where T : Video, new()
        {
            var videoTypes = new List <VideoType>();

            var folderPaths = multiDiscFolders.Select(i => i.FullName).Where(i =>
            {
                var subFileEntries = directoryService.GetFileSystemEntries(i)
                                     .ToList();

                var subfolders = subFileEntries
                                 .Where(e => (e.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
                                 .Select(d => d.Name)
                                 .ToList();

                if (subfolders.Any(IsDvdDirectory))
                {
                    videoTypes.Add(VideoType.Dvd);
                    return(true);
                }
                if (subfolders.Any(IsBluRayDirectory))
                {
                    videoTypes.Add(VideoType.BluRay);
                    return(true);
                }

                var subFiles = subFileEntries
                               .Where(e => (e.Attributes & FileAttributes.Directory) != FileAttributes.Directory)
                               .Select(d => d.Name);

                if (subFiles.Any(IsDvdFile))
                {
                    videoTypes.Add(VideoType.Dvd);
                    return(true);
                }

                return(false);
            }).OrderBy(i => i).ToList();

            // If different video types were found, don't allow this
            if (videoTypes.Distinct().Count() > 1)
            {
                return(null);
            }

            if (folderPaths.Count == 0)
            {
                return(null);
            }

            var namingOptions = ((LibraryManager)LibraryManager).GetNamingOptions();
            var resolver      = new StackResolver(namingOptions, new PatternsLogger());

            var result = resolver.ResolveDirectories(folderPaths);

            if (result.Stacks.Count != 1)
            {
                return(null);
            }

            var returnVideo = new T
            {
                Path = folderPaths[0],

                AdditionalParts = folderPaths.Skip(1).ToList(),

                VideoType = videoTypes[0],

                Name = result.Stacks[0].Name
            };

            SetIsoType(returnVideo);

            return(returnVideo);
        }
Example #45
0
 protected override IEnumerable <BaseItem> GetNonCachedChildren(IDirectoryService directoryService)
 {
     return(new List <BaseItem>());
 }
Example #46
0
        private IEnumerable <FileSystemMetadata> GetFiles(BaseItem item, bool includeDirectories, IDirectoryService directoryService)
        {
            if (!item.IsFileProtocol)
            {
                return(new List <FileSystemMetadata>());
            }

            var path = item.ContainingFolderPath;

            if (includeDirectories)
            {
                return(directoryService.GetFileSystemEntries(path)
                       .Where(i => BaseItem.SupportedImageExtensions.Contains(i.Extension, StringComparer.OrdinalIgnoreCase) || i.IsDirectory)

                       .OrderBy(i => BaseItem.SupportedImageExtensionsList.IndexOf(i.Extension ?? string.Empty)));
            }

            return(directoryService.GetFiles(path)
                   .Where(i => BaseItem.SupportedImageExtensions.Contains(i.Extension, StringComparer.OrdinalIgnoreCase))
                   .OrderBy(i => BaseItem.SupportedImageExtensionsList.IndexOf(i.Extension ?? string.Empty)));
        }
Example #47
0
 protected override Task ValidateChildrenInternal(IProgress <double> progress, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService, CancellationToken cancellationToken)
 {
     return(Task.CompletedTask);
 }
Example #48
0
        private void PopulateImages(BaseItem item, List <LocalImageInfo> images, List <FileSystemMetadata> files, bool supportParentSeriesFiles, IDirectoryService directoryService)
        {
            if (supportParentSeriesFiles)
            {
                var season = item as Season;

                if (season != null)
                {
                    PopulateSeasonImagesFromSeriesFolder(season, images, directoryService);
                }
            }

            var imagePrefix     = item.FileNameWithoutExtension + "-";
            var isInMixedFolder = item.IsInMixedFolder;

            PopulatePrimaryImages(item, images, files, imagePrefix, isInMixedFolder);

            var added     = false;
            var isEpisode = item is Episode;
            var isSong    = item.GetType() == typeof(Audio);
            var isGame    = item is Game;
            var isPerson  = item is Person;

            // Logo
            if (!isEpisode && !isSong && !isPerson)
            {
                added = AddImage(files, images, "logo", imagePrefix, isInMixedFolder, ImageType.Logo);
                if (!added)
                {
                    added = AddImage(files, images, "clearlogo", imagePrefix, isInMixedFolder, ImageType.Logo);
                }
            }

            // Art
            if (!isEpisode && !isSong && !isPerson)
            {
                AddImage(files, images, "clearart", imagePrefix, isInMixedFolder, ImageType.Art);
            }

            // For music albums, prefer cdart before disc
            if (item is MusicAlbum)
            {
                added = AddImage(files, images, "cdart", imagePrefix, isInMixedFolder, ImageType.Disc);

                if (!added)
                {
                    added = AddImage(files, images, "disc", imagePrefix, isInMixedFolder, ImageType.Disc);
                }
            }
            else if (isGame || item is Video || item is BoxSet)
            {
                added = AddImage(files, images, "disc", imagePrefix, isInMixedFolder, ImageType.Disc);

                if (!added)
                {
                    added = AddImage(files, images, "cdart", imagePrefix, isInMixedFolder, ImageType.Disc);
                }

                if (!added)
                {
                    added = AddImage(files, images, "discart", imagePrefix, isInMixedFolder, ImageType.Disc);
                }
            }

            if (isGame)
            {
                AddImage(files, images, "box", imagePrefix, isInMixedFolder, ImageType.Box);
                AddImage(files, images, "menu", imagePrefix, isInMixedFolder, ImageType.Menu);

                added = AddImage(files, images, "back", imagePrefix, isInMixedFolder, ImageType.BoxRear);

                if (!added)
                {
                    added = AddImage(files, images, "boxrear", imagePrefix, isInMixedFolder, ImageType.BoxRear);
                }
            }

            // Banner
            if (!isEpisode && !isSong && !isPerson)
            {
                AddImage(files, images, "banner", imagePrefix, isInMixedFolder, ImageType.Banner);
            }

            // Thumb
            if (!isEpisode && !isSong && !isPerson)
            {
                added = AddImage(files, images, "landscape", imagePrefix, isInMixedFolder, ImageType.Thumb);
                if (!added)
                {
                    added = AddImage(files, images, "thumb", imagePrefix, isInMixedFolder, ImageType.Thumb);
                }
            }

            if (!isEpisode && !isSong && !isPerson)
            {
                PopulateBackdrops(item, images, files, imagePrefix, isInMixedFolder, directoryService);
            }

            if (item is IHasScreenshots)
            {
                PopulateScreenshots(images, files, imagePrefix, isInMixedFolder);
            }
        }
Example #49
0
 protected override FileSystemMetadata GetXmlFile(ItemInfo info, IDirectoryService directoryService)
 {
     return(directoryService.GetFile(Path.Combine(info.Path, "gamesystem.xml")));
 }
 public DirectoriesController(IDirectoryService directoryService)
 {
     _directoryService = directoryService;
 }
Example #51
0
        /// <summary>
        /// Finds a movie based on a child file system entries
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path">The path.</param>
        /// <param name="parent">The parent.</param>
        /// <param name="fileSystemEntries">The file system entries.</param>
        /// <param name="directoryService">The directory service.</param>
        /// <param name="supportMultiFileItems">if set to <c>true</c> [support multi file items].</param>
        /// <returns>Movie.</returns>
        private T FindMovie <T>(string path, Folder parent, IEnumerable <FileSystemInfo> fileSystemEntries, IDirectoryService directoryService, bool supportMultiFileItems, bool supportsMultipleSources)
            where T : Video, new()
        {
            var movies = new List <T>();

            var multiDiscFolders = new List <FileSystemInfo>();

            // Loop through each child file/folder and see if we find a video
            foreach (var child in fileSystemEntries)
            {
                var filename = child.Name;

                if ((child.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
                {
                    if (IsDvdDirectory(filename))
                    {
                        return(new T
                        {
                            Path = path,
                            VideoType = VideoType.Dvd
                        });
                    }
                    if (IsBluRayDirectory(filename))
                    {
                        return(new T
                        {
                            Path = path,
                            VideoType = VideoType.BluRay
                        });
                    }

                    if (EntityResolutionHelper.IsMultiPartFolder(filename))
                    {
                        multiDiscFolders.Add(child);
                    }

                    continue;
                }

                // Don't misidentify xbmc trailers as a movie
                if (filename.IndexOf(BaseItem.XbmcTrailerFileSuffix, StringComparison.OrdinalIgnoreCase) != -1)
                {
                    continue;
                }

                var childArgs = new ItemResolveArgs(_applicationPaths, _libraryManager, directoryService)
                {
                    FileInfo = child,
                    Path     = child.FullName,
                    Parent   = parent
                };

                var item = ResolveVideo <T>(childArgs);

                if (item != null)
                {
                    item.IsInMixedFolder = false;
                    movies.Add(item);
                }
            }

            if (movies.Count > 1)
            {
                if (supportMultiFileItems)
                {
                    var result = GetMultiFileMovie(movies);

                    if (result != null)
                    {
                        return(result);
                    }
                }
                if (supportsMultipleSources)
                {
                    var result = GetMovieWithMultipleSources(movies);

                    if (result != null)
                    {
                        return(result);
                    }
                }
                return(null);
            }

            if (movies.Count == 1)
            {
                return(movies[0]);
            }

            if (multiDiscFolders.Count > 0)
            {
                var folders = fileSystemEntries.Where(child => (child.Attributes & FileAttributes.Directory) == FileAttributes.Directory);

                return(GetMultiDiscMovie <T>(multiDiscFolders, folders));
            }

            return(null);
        }
Example #52
0
 public AliasesRepository(ILogger logger, IAliasesService aliasesService, IDirectoryService directoryService)
 {
     _logger           = logger;
     _aliasesService   = aliasesService;
     _directoryService = directoryService;
 }
 protected override FileSystemMetadata GetJsonFile(ItemInfo info, IDirectoryService directoryService)
 {
     return(directoryService.GetFile(
                Path.ChangeExtension(info.Path, ".json")
                ));
 }
Example #54
0
        private void PopulateSeasonImagesFromSeriesFolder(Season season, List <LocalImageInfo> images, IDirectoryService directoryService)
        {
            var seasonNumber = season.IndexNumber;

            var series = season.Series;

            if (!seasonNumber.HasValue || !series.IsFileProtocol)
            {
                return;
            }

            var seriesFiles = GetFiles(series, false, directoryService).ToList();

            // Try using the season name
            var prefix = season.Name.ToLower().Replace(" ", string.Empty);

            var filenamePrefixes = new List <string> {
                prefix
            };

            var seasonMarker = seasonNumber.Value == 0
                                   ? "-specials"
                                   : seasonNumber.Value.ToString("00", _usCulture);

            // Get this one directly from the file system since we have to go up a level
            if (!string.Equals(prefix, seasonMarker, StringComparison.OrdinalIgnoreCase))
            {
                filenamePrefixes.Add("season" + seasonMarker);
            }

            foreach (var filename in filenamePrefixes)
            {
                AddImage(seriesFiles, images, filename + "-poster", ImageType.Primary);
                AddImage(seriesFiles, images, filename + "-fanart", ImageType.Backdrop);
                AddImage(seriesFiles, images, filename + "-banner", ImageType.Banner);
                AddImage(seriesFiles, images, filename + "-landscape", ImageType.Thumb);
            }
        }
Example #55
0
        protected override Task ValidateChildrenInternal(IProgress <double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
        {
            if (IsAccessedByName)
            {
                // Should never get in here anyway
                return(Task.CompletedTask);
            }

            return(base.ValidateChildrenInternal(progress, cancellationToken, recursive, refreshChildMetadata, refreshOptions, directoryService));
        }
Example #56
0
 protected override FileSystemMetadata GetXmlFile(ItemInfo info, IDirectoryService directoryService)
 {
     return(MovieXmlProvider.GetXmlFileInfo(info, FileSystem));
 }
Example #57
0
        /// <summary>
        /// Gets the multi disc movie.
        /// </summary>
        /// <param name="multiDiscFolders">The folders.</param>
        /// <param name="directoryService">The directory service.</param>
        /// <returns>``0.</returns>
        private T GetMultiDiscMovie <T>(List <FileSystemMetadata> multiDiscFolders, IDirectoryService directoryService)
            where T : Video, new()
        {
            var videoTypes = new List <VideoType>();

            var folderPaths = multiDiscFolders.Select(i => i.FullName).Where(i =>
            {
                var subFileEntries = directoryService.GetFileSystemEntries(i);

                var subfolders = subFileEntries
                                 .Where(e => e.IsDirectory)
                                 .ToList();

                if (subfolders.Any(s => IsDvdDirectory(s.FullName, s.Name, directoryService)))
                {
                    videoTypes.Add(VideoType.Dvd);
                    return(true);
                }

                if (subfolders.Any(s => IsBluRayDirectory(s.FullName, s.Name, directoryService)))
                {
                    videoTypes.Add(VideoType.BluRay);
                    return(true);
                }

                var subFiles = subFileEntries
                               .Where(e => !e.IsDirectory)
                               .Select(d => d.Name);

                if (subFiles.Any(IsDvdFile))
                {
                    videoTypes.Add(VideoType.Dvd);
                    return(true);
                }

                return(false);
            }).OrderBy(i => i).ToList();

            // If different video types were found, don't allow this
            if (videoTypes.Distinct().Count() > 1)
            {
                return(null);
            }

            if (folderPaths.Count == 0)
            {
                return(null);
            }

            var namingOptions = ((LibraryManager)LibraryManager).GetNamingOptions();

            var result = new StackResolver(namingOptions).ResolveDirectories(folderPaths).ToList();

            if (result.Count != 1)
            {
                return(null);
            }

            int additionalPartsLen = folderPaths.Count - 1;
            var additionalParts    = new string[additionalPartsLen];

            folderPaths.CopyTo(1, additionalParts, 0, additionalPartsLen);

            var returnVideo = new T
            {
                Path            = folderPaths[0],
                AdditionalParts = additionalParts,
                VideoType       = videoTypes[0],
                Name            = result[0].Name
            };

            SetIsoType(returnVideo);

            return(returnVideo);
        }
Example #58
0
 public MetadataRefreshOptions(IDirectoryService directoryService)
     : base(directoryService)
 {
     MetadataRefreshMode = MetadataRefreshMode.Default;
 }
        public bool HasChanged(IHasMetadata item, IDirectoryService directoryService, DateTime date)
        {
            if (!_config.Configuration.EnableFanArtUpdates)
            {
                return false;
            }

            var tvdbId = item.GetProviderId(MetadataProviders.Tvdb);

            if (!String.IsNullOrEmpty(tvdbId))
            {
                // Process images
                var imagesXmlPath = GetFanartXmlPath(tvdbId);

                var fileInfo = new FileInfo(imagesXmlPath);

                return !fileInfo.Exists || _fileSystem.GetLastWriteTimeUtc(fileInfo) > date;
            }

            return false;
        }
Example #60
0
        public List <LocalImageInfo> GetImages(BaseItem item, IDirectoryService directoryService)
        {
            var collectionFolder = (CollectionFolder)item;

            return(new LocalImageProvider(_fileSystem).GetImages(item, collectionFolder.PhysicalLocations, true, directoryService));
        }