Merge branch 'master' into locale

This commit is contained in:
Bond-009 2019-01-31 18:44:36 +01:00 committed by GitHub
commit 2a1f6361a5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
137 changed files with 647 additions and 956 deletions

View file

@ -8,23 +8,23 @@ assignees: ''
--- ---
**Describe the bug** **Describe the bug**
A clear and concise description of what the bug is. <!-- A clear and concise description of what the bug is. -->
**To Reproduce** **To Reproduce**
Steps to reproduce the behavior: <!-- Steps to reproduce the behavior: -->
1. Go to '...' 1. Go to '...'
2. Click on '....' 2. Click on '....'
3. Scroll down to '....' 3. Scroll down to '....'
4. See error 4. See error
**Expected behavior** **Expected behavior**
A clear and concise description of what you expected to happen. <!-- A clear and concise description of what you expected to happen. -->
**Logs** **Logs**
Please paste any log errors. <!-- Please paste any log errors. -->
**Screenshots** **Screenshots**
If applicable, add screenshots to help explain your problem. <!-- If applicable, add screenshots to help explain your problem. -->
**System (please complete the following information):** **System (please complete the following information):**
- OS: [e.g. Docker, Debian, Windows] - OS: [e.g. Docker, Debian, Windows]
@ -32,4 +32,4 @@ If applicable, add screenshots to help explain your problem.
- Jellyfin Version: [e.g. 10.0.1] - Jellyfin Version: [e.g. 10.0.1]
**Additional context** **Additional context**
Add any other context about the problem here. <!-- Add any other context about the problem here. -->

View file

@ -8,13 +8,13 @@ assignees: ''
--- ---
**Is your feature request related to a problem? Please describe.** **Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] <!-- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] -->
**Describe the solution you'd like** **Describe the solution you'd like**
A clear and concise description of what you want to happen. <!-- A clear and concise description of what you want to happen. -->
**Describe alternatives you've considered** **Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered. <!-- A clear and concise description of any alternative solutions or features you've considered. -->
**Additional context** **Additional context**
Add any other context or screenshots about the feature request here. <!-- Add any other context or screenshots about the feature request here. -->

View file

@ -8,7 +8,7 @@ assignees: ''
--- ---
**Describe the feature you'd like** **Describe the feature you'd like**
A clear and concise description of what you want to happen. <!-- A clear and concise description of what you want to happen. -->
**Additional context** **Additional context**
Add any other context or screenshots about the feature request here. <!-- Add any other context or screenshots about the feature request here. -->

View file

@ -1,9 +1,11 @@
<!--
Ensure your title is short, descriptive, and in the imperative mood (Fix X, Change Y, instead of Fixed X, Changed Y). Ensure your title is short, descriptive, and in the imperative mood (Fix X, Change Y, instead of Fixed X, Changed Y).
For a good inspiration of what to write in commit messages and PRs please review https://chris.beams.io/posts/git-commit/ and our https://jellyfin.readthedocs.io/en/latest/developer-docs/contributing/ page. For a good inspiration of what to write in commit messages and PRs please review https://chris.beams.io/posts/git-commit/ and our https://jellyfin.readthedocs.io/en/latest/developer-docs/contributing/ page.
-->
**Changes** **Changes**
Describe your changes here in 1-5 sentences. <!-- Describe your changes here in 1-5 sentences. -->
**Issues** **Issues**
Tag any issues that this PR solves here. <!-- Tag any issues that this PR solves here.
Fixes # ex. Fixes # -->

View file

@ -92,7 +92,7 @@ namespace BDInfo
} }
DirectoryRoot = DirectoryRoot =
_fileSystem.GetDirectoryInfo(_fileSystem.GetDirectoryName(DirectoryBDMV.FullName)); _fileSystem.GetDirectoryInfo(Path.GetDirectoryName(DirectoryBDMV.FullName));
DirectoryBDJO = DirectoryBDJO =
GetDirectory("BDJO", DirectoryBDMV, 0); GetDirectory("BDJO", DirectoryBDMV, 0);
DirectoryCLIPINF = DirectoryCLIPINF =
@ -150,7 +150,7 @@ namespace BDInfo
Is3D = true; Is3D = true;
} }
if (_fileSystem.FileExists(Path.Combine(DirectoryRoot.FullName, "FilmIndex.xml"))) if (File.Exists(Path.Combine(DirectoryRoot.FullName, "FilmIndex.xml")))
{ {
IsDBOX = true; IsDBOX = true;
} }
@ -345,7 +345,7 @@ namespace BDInfo
{ {
return dir; return dir;
} }
var parentFolder = _fileSystem.GetDirectoryName(dir.FullName); var parentFolder = Path.GetDirectoryName(dir.FullName);
if (string.IsNullOrEmpty(parentFolder)) if (string.IsNullOrEmpty(parentFolder))
{ {
dir = null; dir = null;

View file

@ -1,4 +1,4 @@
//============================================================================ //============================================================================
// BDInfo - Blu-ray Video and Audio Analysis Tool // BDInfo - Blu-ray Video and Audio Analysis Tool
// Copyright © 2010 Cinema Squid // Copyright © 2010 Cinema Squid
// //
@ -231,7 +231,7 @@ namespace BDInfo
Streams.Clear(); Streams.Clear();
StreamClips.Clear(); StreamClips.Clear();
fileStream = _fileSystem.OpenRead(FileInfo.FullName); fileStream = File.OpenRead(FileInfo.FullName);
fileReader = new BinaryReader(fileStream); fileReader = new BinaryReader(fileStream);
byte[] data = new byte[fileStream.Length]; byte[] data = new byte[fileStream.Length];

View file

@ -1,4 +1,4 @@
//============================================================================ //============================================================================
// BDInfo - Blu-ray Video and Audio Analysis Tool // BDInfo - Blu-ray Video and Audio Analysis Tool
// Copyright © 2010 Cinema Squid // Copyright © 2010 Cinema Squid
// //
@ -57,7 +57,7 @@ namespace BDInfo
#endif #endif
Streams.Clear(); Streams.Clear();
fileStream = _fileSystem.OpenRead(FileInfo.FullName); fileStream = File.OpenRead(FileInfo.FullName);
fileReader = new BinaryReader(fileStream); fileReader = new BinaryReader(fileStream);
byte[] data = new byte[fileStream.Length]; byte[] data = new byte[fileStream.Length];

View file

@ -16,6 +16,7 @@
- [wtayl0r](https://github.com/wtayl0r) - [wtayl0r](https://github.com/wtayl0r)
- [TtheCreator](https://github.com/Tthecreator) - [TtheCreator](https://github.com/Tthecreator)
- [LogicalPhallacy](https://github.com/LogicalPhallacy/) - [LogicalPhallacy](https://github.com/LogicalPhallacy/)
- [RazeLighter777](https://github.com/RazeLighter777)
# Emby Contributors # Emby Contributors

View file

@ -1,15 +1,5 @@
ARG DOTNET_VERSION=2 ARG DOTNET_VERSION=2
# Download ffmpeg first to allow quicker rebuild of other layers
FROM alpine as ffmpeg
ARG FFMPEG_URL=https://www.johnvansickle.com/ffmpeg/old-releases/ffmpeg-4.0.3-64bit-static.tar.xz
RUN wget ${FFMPEG_URL} -O - | tar Jxf - \
&& mkdir ffmpeg-bin \
&& mv ffmpeg*/ffmpeg ffmpeg-bin \
&& mv ffmpeg*/ffprobe ffmpeg-bin
FROM microsoft/dotnet:${DOTNET_VERSION}-sdk as builder FROM microsoft/dotnet:${DOTNET_VERSION}-sdk as builder
WORKDIR /repo WORKDIR /repo
COPY . . COPY . .
@ -20,7 +10,7 @@ RUN export DOTNET_CLI_TELEMETRY_OPTOUT=1 \
--output /jellyfin \ --output /jellyfin \
Jellyfin.Server Jellyfin.Server
FROM jrottenberg/ffmpeg:4.0-scratch as ffmpeg
FROM microsoft/dotnet:${DOTNET_VERSION}-runtime FROM microsoft/dotnet:${DOTNET_VERSION}-runtime
# libfontconfig1 is required for Skia # libfontconfig1 is required for Skia
RUN apt-get update \ RUN apt-get update \
@ -29,8 +19,8 @@ RUN apt-get update \
&& apt-get clean autoclean \ && apt-get clean autoclean \
&& apt-get autoremove \ && apt-get autoremove \
&& rm -rf /var/lib/{apt,dpkg,cache,log} && rm -rf /var/lib/{apt,dpkg,cache,log}
COPY --from=ffmpeg / /
COPY --from=builder /jellyfin /jellyfin COPY --from=builder /jellyfin /jellyfin
COPY --from=ffmpeg /ffmpeg-bin/* /usr/bin/
EXPOSE 8096 EXPOSE 8096
VOLUME /config /media VOLUME /config /media
ENTRYPOINT dotnet /jellyfin/jellyfin.dll -programdata /config ENTRYPOINT dotnet /jellyfin/jellyfin.dll -programdata /config

View file

@ -932,7 +932,7 @@ namespace Emby.Dlna.Didl
private void AddCover(BaseItem item, BaseItem context, StubType? stubType, XmlWriter writer) private void AddCover(BaseItem item, BaseItem context, StubType? stubType, XmlWriter writer)
{ {
ImageDownloadInfo imageInfo = GetImageInfo(item);; ImageDownloadInfo imageInfo = GetImageInfo(item);
if (imageInfo == null) if (imageInfo == null)
{ {

View file

@ -379,7 +379,7 @@ namespace Emby.Dlna
if (!fileInfo.Exists || fileInfo.Length != stream.Length) if (!fileInfo.Exists || fileInfo.Length != stream.Length)
{ {
_fileSystem.CreateDirectory(systemProfilesPath); Directory.CreateDirectory(systemProfilesPath);
using (var fileStream = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read)) using (var fileStream = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
{ {
@ -390,7 +390,7 @@ namespace Emby.Dlna
} }
// Not necessary, but just to make it easy to find // Not necessary, but just to make it easy to find
_fileSystem.CreateDirectory(UserProfilesPath); Directory.CreateDirectory(UserProfilesPath);
} }
public void DeleteProfile(string id) public void DeleteProfile(string id)

View file

@ -5,12 +5,6 @@
<GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="SkiaSharp" Version="1.68.0" />
<PackageReference Include="SkiaSharp.NativeAssets.Linux" Version="1.68.0" />
<PackageReference Include="Jellyfin.SkiaSharp.NativeAssets.LinuxArm" Version="1.68.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj" /> <ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj" />
<ProjectReference Include="..\MediaBrowser.Controller\MediaBrowser.Controller.csproj" /> <ProjectReference Include="..\MediaBrowser.Controller\MediaBrowser.Controller.csproj" />

View file

@ -244,7 +244,7 @@ namespace Emby.Drawing
try try
{ {
if (!_fileSystem.FileExists(cacheFilePath)) if (!File.Exists(cacheFilePath))
{ {
if (options.CropWhiteSpace && !SupportsTransparency(originalImagePath)) if (options.CropWhiteSpace && !SupportsTransparency(originalImagePath))
{ {
@ -626,12 +626,12 @@ namespace Emby.Drawing
try try
{ {
// Check again in case of contention // Check again in case of contention
if (_fileSystem.FileExists(enhancedImagePath)) if (File.Exists(enhancedImagePath))
{ {
return (enhancedImagePath, treatmentRequiresTransparency); return (enhancedImagePath, treatmentRequiresTransparency);
} }
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(enhancedImagePath)); Directory.CreateDirectory(Path.GetDirectoryName(enhancedImagePath));
await ExecuteImageEnhancers(supportedEnhancers, originalImagePath, enhancedImagePath, item, imageType, imageIndex).ConfigureAwait(false); await ExecuteImageEnhancers(supportedEnhancers, originalImagePath, enhancedImagePath, item, imageType, imageIndex).ConfigureAwait(false);

View file

@ -39,7 +39,7 @@ namespace IsoMounter
_logger = logger; _logger = logger;
ProcessFactory = processFactory; ProcessFactory = processFactory;
MountPointRoot = FileSystem.DirectorySeparatorChar + "tmp" + FileSystem.DirectorySeparatorChar + "Emby"; MountPointRoot = Path.DirectorySeparatorChar + "tmp" + Path.DirectorySeparatorChar + "Emby";
_logger.LogDebug( _logger.LogDebug(
"[{0}] System PATH is currently set to [{1}].", "[{0}] System PATH is currently set to [{1}].",
@ -214,9 +214,9 @@ namespace IsoMounter
{ {
string path = test.Trim(); string path = test.Trim();
if (!string.IsNullOrEmpty(path) && FileSystem.FileExists(path = Path.Combine(path, name))) if (!string.IsNullOrEmpty(path) && File.Exists(path = Path.Combine(path, name)))
{ {
return FileSystem.GetFullPath(path); return Path.GetFullPath(path);
} }
} }
@ -327,7 +327,7 @@ namespace IsoMounter
try try
{ {
FileSystem.CreateDirectory(mountPoint); Directory.CreateDirectory(mountPoint);
} }
catch (UnauthorizedAccessException) catch (UnauthorizedAccessException)
{ {
@ -377,7 +377,7 @@ namespace IsoMounter
try try
{ {
FileSystem.DeleteDirectory(mountPoint, false); Directory.Delete(mountPoint, false);
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -455,7 +455,7 @@ namespace IsoMounter
try try
{ {
FileSystem.DeleteDirectory(mount.MountedPath, false); Directory.Delete(mount.MountedPath, false);
} }
catch (Exception ex) catch (Exception ex)
{ {

View file

@ -175,71 +175,23 @@ namespace Emby.Naming.Video
return videos; return videos;
} }
var list = new List<VideoInfo>();
var folderName = Path.GetFileName(Path.GetDirectoryName(videos[0].Files[0].Path)); var folderName = Path.GetFileName(Path.GetDirectoryName(videos[0].Files[0].Path));
if (!string.IsNullOrEmpty(folderName) && folderName.Length > 1) if (!string.IsNullOrEmpty(folderName) && folderName.Length > 1)
{ {
if (videos.All(i => i.Files.Count == 1 && IsEligibleForMultiVersion(folderName, i.Files[0].Path))) var ordered = videos.OrderBy(i => i.Name);
return ordered.GroupBy(v => new {v.Name, v.Year}).Select(group => new VideoInfo
{ {
// Enforce the multi-version limit Name = folderName,
if (videos.Count <= 8 && HaveSameYear(videos)) Year = group.First().Year,
{ Files = group.First().Files,
var ordered = videos.OrderBy(i => i.Name).ToList(); AlternateVersions = group.Skip(1).Select(i => i.Files[0]).ToList(),
Extras = group.First().Extras.Concat(group.Skip(1).SelectMany(i => i.Extras)).ToList()
list.Add(ordered[0]); });
list[0].AlternateVersions = ordered.Skip(1).Select(i => i.Files[0]).ToList();
list[0].Name = folderName;
list[0].Extras.AddRange(ordered.Skip(1).SelectMany(i => i.Extras));
return list;
}
}
} }
return videos; return videos;
//foreach (var video in videos.OrderBy(i => i.Name))
//{
// var match = list
// .FirstOrDefault(i => string.Equals(i.Name, video.Name, StringComparison.OrdinalIgnoreCase));
// if (match != null && video.Files.Count == 1 && match.Files.Count == 1)
// {
// match.AlternateVersions.Add(video.Files[0]);
// match.Extras.AddRange(video.Extras);
// }
// else
// {
// list.Add(video);
// }
//}
//return list;
}
private bool HaveSameYear(List<VideoInfo> videos)
{
return videos.Select(i => i.Year ?? -1).Distinct().Count() < 2;
}
private bool IsEligibleForMultiVersion(string folderName, string testFilename)
{
testFilename = Path.GetFileNameWithoutExtension(testFilename);
if (string.Equals(folderName, testFilename, StringComparison.OrdinalIgnoreCase))
{
return true;
}
if (testFilename.StartsWith(folderName, StringComparison.OrdinalIgnoreCase))
{
testFilename = testFilename.Substring(folderName.Length).Trim();
return testFilename.StartsWith("-", StringComparison.OrdinalIgnoreCase) || Regex.Replace(testFilename, @"\[([^]]*)\]", "").Trim() == string.Empty;
}
return false;
} }
private List<VideoFileInfo> GetExtras(IEnumerable<VideoFileInfo> remainingFiles, List<string> baseNames) private List<VideoFileInfo> GetExtras(IEnumerable<VideoFileInfo> remainingFiles, List<string> baseNames)

View file

@ -501,7 +501,6 @@ namespace Emby.Server.Implementations.Activity
_sessionManager.PlaybackStart -= _sessionManager_PlaybackStart; _sessionManager.PlaybackStart -= _sessionManager_PlaybackStart;
_sessionManager.PlaybackStopped -= _sessionManager_PlaybackStopped; _sessionManager.PlaybackStopped -= _sessionManager_PlaybackStopped;
_subManager.SubtitlesDownloaded -= _subManager_SubtitlesDownloaded;
_subManager.SubtitleDownloadFailure -= _subManager_SubtitleDownloadFailure; _subManager.SubtitleDownloadFailure -= _subManager_SubtitleDownloadFailure;
_userManager.UserCreated -= _userManager_UserCreated; _userManager.UserCreated -= _userManager_UserCreated;

View file

@ -127,7 +127,7 @@ namespace Emby.Server.Implementations.AppBase
Logger.LogInformation("Saving system configuration"); Logger.LogInformation("Saving system configuration");
var path = CommonApplicationPaths.SystemConfigurationFilePath; var path = CommonApplicationPaths.SystemConfigurationFilePath;
FileSystem.CreateDirectory(FileSystem.GetDirectoryName(path)); Directory.CreateDirectory(Path.GetDirectoryName(path));
lock (_configurationSyncLock) lock (_configurationSyncLock)
{ {
@ -197,7 +197,7 @@ namespace Emby.Server.Implementations.AppBase
&& !string.Equals(CommonConfiguration.CachePath ?? string.Empty, newPath)) && !string.Equals(CommonConfiguration.CachePath ?? string.Empty, newPath))
{ {
// Validate // Validate
if (!FileSystem.DirectoryExists(newPath)) if (!Directory.Exists(newPath))
{ {
throw new FileNotFoundException(string.Format("{0} does not exist.", newPath)); throw new FileNotFoundException(string.Format("{0} does not exist.", newPath));
} }
@ -209,8 +209,7 @@ namespace Emby.Server.Implementations.AppBase
protected void EnsureWriteAccess(string path) protected void EnsureWriteAccess(string path)
{ {
var file = Path.Combine(path, Guid.NewGuid().ToString()); var file = Path.Combine(path, Guid.NewGuid().ToString());
File.WriteAllText(file, string.Empty);
FileSystem.WriteAllText(file, string.Empty);
FileSystem.DeleteFile(file); FileSystem.DeleteFile(file);
} }
@ -246,14 +245,15 @@ namespace Emby.Server.Implementations.AppBase
private object LoadConfiguration(string path, Type configurationType) private object LoadConfiguration(string path, Type configurationType)
{ {
if (!File.Exists(path))
{
return Activator.CreateInstance(configurationType);
}
try try
{ {
return XmlSerializer.DeserializeFromFile(configurationType, path); return XmlSerializer.DeserializeFromFile(configurationType, path);
} }
catch (FileNotFoundException)
{
return Activator.CreateInstance(configurationType);
}
catch (IOException) catch (IOException)
{ {
return Activator.CreateInstance(configurationType); return Activator.CreateInstance(configurationType);
@ -293,7 +293,7 @@ namespace Emby.Server.Implementations.AppBase
_configurations.AddOrUpdate(key, configuration, (k, v) => configuration); _configurations.AddOrUpdate(key, configuration, (k, v) => configuration);
var path = GetConfigurationFile(key); var path = GetConfigurationFile(key);
FileSystem.CreateDirectory(FileSystem.GetDirectoryName(path)); Directory.CreateDirectory(Path.GetDirectoryName(path));
lock (_configurationSyncLock) lock (_configurationSyncLock)
{ {

View file

@ -29,7 +29,7 @@ namespace Emby.Server.Implementations.AppBase
// Use try/catch to avoid the extra file system lookup using File.Exists // Use try/catch to avoid the extra file system lookup using File.Exists
try try
{ {
buffer = fileSystem.ReadAllBytes(path); buffer = File.ReadAllBytes(path);
configuration = xmlSerializer.DeserializeFromBytes(type, buffer); configuration = xmlSerializer.DeserializeFromBytes(type, buffer);
} }
@ -48,10 +48,10 @@ namespace Emby.Server.Implementations.AppBase
// If the file didn't exist before, or if something has changed, re-save // If the file didn't exist before, or if something has changed, re-save
if (buffer == null || !buffer.SequenceEqual(newBytes)) if (buffer == null || !buffer.SequenceEqual(newBytes))
{ {
fileSystem.CreateDirectory(fileSystem.GetDirectoryName(path)); Directory.CreateDirectory(Path.GetDirectoryName(path));
// Save it after load in case we got new items // Save it after load in case we got new items
fileSystem.WriteAllBytes(path, newBytes); File.WriteAllBytes(path, newBytes);
} }
return configuration; return configuration;

View file

@ -879,7 +879,7 @@ namespace Emby.Server.Implementations
MediaSourceManager = new MediaSourceManager(ItemRepository, ApplicationPaths, LocalizationManager, UserManager, LibraryManager, LoggerFactory, JsonSerializer, FileSystemManager, UserDataManager, TimerFactory, () => MediaEncoder); MediaSourceManager = new MediaSourceManager(ItemRepository, ApplicationPaths, LocalizationManager, UserManager, LibraryManager, LoggerFactory, JsonSerializer, FileSystemManager, UserDataManager, TimerFactory, () => MediaEncoder);
RegisterSingleInstance(MediaSourceManager); RegisterSingleInstance(MediaSourceManager);
SubtitleManager = new SubtitleManager(LoggerFactory, FileSystemManager, LibraryMonitor, MediaSourceManager, ServerConfigurationManager, LocalizationManager); SubtitleManager = new SubtitleManager(LoggerFactory, FileSystemManager, LibraryMonitor, MediaSourceManager, LocalizationManager);
RegisterSingleInstance(SubtitleManager); RegisterSingleInstance(SubtitleManager);
ProviderManager = new ProviderManager(HttpClient, SubtitleManager, ServerConfigurationManager, LibraryMonitor, LoggerFactory, FileSystemManager, ApplicationPaths, () => LibraryManager, JsonSerializer); ProviderManager = new ProviderManager(HttpClient, SubtitleManager, ServerConfigurationManager, LibraryMonitor, LoggerFactory, FileSystemManager, ApplicationPaths, () => LibraryManager, JsonSerializer);
@ -1006,7 +1006,7 @@ namespace Emby.Server.Implementations
try try
{ {
if (!FileSystemManager.FileExists(certificateLocation)) if (!File.Exists(certificateLocation))
{ {
return null; return null;
} }
@ -1432,7 +1432,7 @@ namespace Emby.Server.Implementations
//if (generateCertificate) //if (generateCertificate)
//{ //{
// if (!FileSystemManager.FileExists(certPath)) // if (!File.Exists(certPath))
// { // {
// FileSystemManager.CreateDirectory(FileSystemManager.GetDirectoryName(certPath)); // FileSystemManager.CreateDirectory(FileSystemManager.GetDirectoryName(certPath));
@ -1562,7 +1562,7 @@ namespace Emby.Server.Implementations
/// <returns>IEnumerable{Assembly}.</returns> /// <returns>IEnumerable{Assembly}.</returns>
protected List<Tuple<Assembly, string>> GetComposablePartAssemblies() protected List<Tuple<Assembly, string>> GetComposablePartAssemblies()
{ {
var list = GetPluginAssemblies(); var list = GetPluginAssemblies(ApplicationPaths.PluginsPath);
// Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
// This will prevent the .dll file from getting locked, and allow us to replace it when needed // This will prevent the .dll file from getting locked, and allow us to replace it when needed
@ -1613,79 +1613,6 @@ namespace Emby.Server.Implementations
protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal(); protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
/// <summary>
/// Gets the plugin assemblies.
/// </summary>
/// <returns>IEnumerable{Assembly}.</returns>
private List<Tuple<Assembly, string>> GetPluginAssemblies()
{
// Copy pre-installed plugins
var sourcePath = Path.Combine(ApplicationPaths.ApplicationResourcesPath, "plugins");
CopyPlugins(sourcePath, ApplicationPaths.PluginsPath);
return GetPluginAssemblies(ApplicationPaths.PluginsPath);
}
private void CopyPlugins(string source, string target)
{
List<string> files;
try
{
files = Directory.EnumerateFiles(source, "*.dll", SearchOption.TopDirectoryOnly)
.ToList();
}
catch (DirectoryNotFoundException)
{
return;
}
if (files.Count == 0)
{
return;
}
foreach (var sourceFile in files)
{
var filename = Path.GetFileName(sourceFile);
var targetFile = Path.Combine(target, filename);
var targetFileExists = File.Exists(targetFile);
if (!targetFileExists && ServerConfigurationManager.Configuration.UninstalledPlugins.Contains(filename, StringComparer.OrdinalIgnoreCase))
{
continue;
}
if (targetFileExists && GetDllVersion(targetFile) >= GetDllVersion(sourceFile))
{
continue;
}
Directory.CreateDirectory(target);
File.Copy(sourceFile, targetFile, true);
}
}
private Version GetDllVersion(string path)
{
try
{
var result = Version.Parse(FileVersionInfo.GetVersionInfo(path).FileVersion);
Logger.LogInformation("File {Path} has version {Version}", path, result);
return result;
}
catch (Exception ex)
{
Logger.LogError(ex, "Error getting version number from {Path}", path);
return new Version(1, 0);
}
}
private List<Tuple<Assembly, string>> GetPluginAssemblies(string path) private List<Tuple<Assembly, string>> GetPluginAssemblies(string path)
{ {
try try

View file

@ -29,7 +29,7 @@ namespace Emby.Server.Implementations.Archiving
/// <param name="overwriteExistingFiles">if set to <c>true</c> [overwrite existing files].</param> /// <param name="overwriteExistingFiles">if set to <c>true</c> [overwrite existing files].</param>
public void ExtractAll(string sourceFile, string targetPath, bool overwriteExistingFiles) public void ExtractAll(string sourceFile, string targetPath, bool overwriteExistingFiles)
{ {
using (var fileStream = _fileSystem.OpenRead(sourceFile)) using (var fileStream = File.OpenRead(sourceFile))
{ {
ExtractAll(fileStream, targetPath, overwriteExistingFiles); ExtractAll(fileStream, targetPath, overwriteExistingFiles);
} }
@ -115,7 +115,7 @@ namespace Emby.Server.Implementations.Archiving
/// <param name="overwriteExistingFiles">if set to <c>true</c> [overwrite existing files].</param> /// <param name="overwriteExistingFiles">if set to <c>true</c> [overwrite existing files].</param>
public void ExtractAllFrom7z(string sourceFile, string targetPath, bool overwriteExistingFiles) public void ExtractAllFrom7z(string sourceFile, string targetPath, bool overwriteExistingFiles)
{ {
using (var fileStream = _fileSystem.OpenRead(sourceFile)) using (var fileStream = File.OpenRead(sourceFile))
{ {
ExtractAllFrom7z(fileStream, targetPath, overwriteExistingFiles); ExtractAllFrom7z(fileStream, targetPath, overwriteExistingFiles);
} }
@ -155,7 +155,7 @@ namespace Emby.Server.Implementations.Archiving
/// <param name="overwriteExistingFiles">if set to <c>true</c> [overwrite existing files].</param> /// <param name="overwriteExistingFiles">if set to <c>true</c> [overwrite existing files].</param>
public void ExtractAllFromTar(string sourceFile, string targetPath, bool overwriteExistingFiles) public void ExtractAllFromTar(string sourceFile, string targetPath, bool overwriteExistingFiles)
{ {
using (var fileStream = _fileSystem.OpenRead(sourceFile)) using (var fileStream = File.OpenRead(sourceFile))
{ {
ExtractAllFromTar(fileStream, targetPath, overwriteExistingFiles); ExtractAllFromTar(fileStream, targetPath, overwriteExistingFiles);
} }

View file

@ -355,7 +355,7 @@ namespace Emby.Server.Implementations.Channels
return; return;
} }
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path)); Directory.CreateDirectory(Path.GetDirectoryName(path));
_jsonSerializer.SerializeToFile(mediaSources, path); _jsonSerializer.SerializeToFile(mediaSources, path);
} }
@ -834,7 +834,7 @@ namespace Emby.Server.Implementations.Channels
{ {
try try
{ {
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path)); Directory.CreateDirectory(Path.GetDirectoryName(path));
_jsonSerializer.SerializeToFile(result, path); _jsonSerializer.SerializeToFile(result, path);
} }

View file

@ -76,7 +76,7 @@ namespace Emby.Server.Implementations.Collections
return null; return null;
} }
_fileSystem.CreateDirectory(path); Directory.CreateDirectory(path);
var libraryOptions = new LibraryOptions var libraryOptions = new LibraryOptions
{ {
@ -133,7 +133,7 @@ namespace Emby.Server.Implementations.Collections
try try
{ {
_fileSystem.CreateDirectory(path); Directory.CreateDirectory(path);
var collection = new BoxSet var collection = new BoxSet
{ {
@ -359,7 +359,7 @@ namespace Emby.Server.Implementations.Collections
{ {
var path = _collectionManager.GetCollectionsFolderPath(); var path = _collectionManager.GetCollectionsFolderPath();
if (_fileSystem.DirectoryExists(path)) if (Directory.Exists(path))
{ {
try try
{ {

View file

@ -148,7 +148,7 @@ namespace Emby.Server.Implementations.Configuration
&& !string.Equals(Configuration.CertificatePath ?? string.Empty, newPath)) && !string.Equals(Configuration.CertificatePath ?? string.Empty, newPath))
{ {
// Validate // Validate
if (!FileSystem.FileExists(newPath)) if (!File.Exists(newPath))
{ {
throw new FileNotFoundException(string.Format("Certificate file '{0}' does not exist.", newPath)); throw new FileNotFoundException(string.Format("Certificate file '{0}' does not exist.", newPath));
} }
@ -168,7 +168,7 @@ namespace Emby.Server.Implementations.Configuration
&& !string.Equals(Configuration.MetadataPath ?? string.Empty, newPath)) && !string.Equals(Configuration.MetadataPath ?? string.Empty, newPath))
{ {
// Validate // Validate
if (!FileSystem.DirectoryExists(newPath)) if (!Directory.Exists(newPath))
{ {
throw new FileNotFoundException(string.Format("{0} does not exist.", newPath)); throw new FileNotFoundException(string.Format("{0} does not exist.", newPath));
} }

View file

@ -208,6 +208,7 @@ namespace Emby.Server.Implementations.Data
AddColumn(db, "TypedBaseItems", "OwnerId", "Text", existingColumnNames); AddColumn(db, "TypedBaseItems", "OwnerId", "Text", existingColumnNames);
AddColumn(db, "TypedBaseItems", "Width", "INT", existingColumnNames); AddColumn(db, "TypedBaseItems", "Width", "INT", existingColumnNames);
AddColumn(db, "TypedBaseItems", "Height", "INT", existingColumnNames); AddColumn(db, "TypedBaseItems", "Height", "INT", existingColumnNames);
AddColumn(db, "TypedBaseItems", "Size", "BIGINT", existingColumnNames);
existingColumnNames = GetColumnNames(db, "ItemValues"); existingColumnNames = GetColumnNames(db, "ItemValues");
AddColumn(db, "ItemValues", "CleanValue", "Text", existingColumnNames); AddColumn(db, "ItemValues", "CleanValue", "Text", existingColumnNames);
@ -347,6 +348,7 @@ namespace Emby.Server.Implementations.Data
"OfficialRating", "OfficialRating",
"ForcedSortName", "ForcedSortName",
"RunTimeTicks", "RunTimeTicks",
"Size",
"DateCreated", "DateCreated",
"DateModified", "DateModified",
"guid", "guid",
@ -459,6 +461,7 @@ namespace Emby.Server.Implementations.Data
"SortName", "SortName",
"ForcedSortName", "ForcedSortName",
"RunTimeTicks", "RunTimeTicks",
"Size",
"DateCreated", "DateCreated",
"DateModified", "DateModified",
"PreferredMetadataLanguage", "PreferredMetadataLanguage",
@ -755,6 +758,7 @@ namespace Emby.Server.Implementations.Data
saveItemStatement.TryBind("@ForcedSortName", item.ForcedSortName); saveItemStatement.TryBind("@ForcedSortName", item.ForcedSortName);
saveItemStatement.TryBind("@RunTimeTicks", item.RunTimeTicks); saveItemStatement.TryBind("@RunTimeTicks", item.RunTimeTicks);
saveItemStatement.TryBind("@Size", item.Size);
saveItemStatement.TryBind("@DateCreated", item.DateCreated); saveItemStatement.TryBind("@DateCreated", item.DateCreated);
saveItemStatement.TryBind("@DateModified", item.DateModified); saveItemStatement.TryBind("@DateModified", item.DateModified);
@ -1523,6 +1527,12 @@ namespace Emby.Server.Implementations.Data
} }
index++; index++;
if (!reader.IsDBNull(index))
{
item.Size = reader.GetInt64(index);
}
index++;
if (HasField(query, ItemFields.DateCreated)) if (HasField(query, ItemFields.DateCreated))
{ {
if (!reader.IsDBNull(index)) if (!reader.IsDBNull(index))

View file

@ -53,11 +53,11 @@ namespace Emby.Server.Implementations.Devices
{ {
var path = CachePath; var path = CachePath;
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path)); Directory.CreateDirectory(Path.GetDirectoryName(path));
lock (_syncLock) lock (_syncLock)
{ {
_fileSystem.WriteAllText(path, id, Encoding.UTF8); File.WriteAllText(path, id, Encoding.UTF8);
} }
} }
catch (Exception ex) catch (Exception ex)

View file

@ -76,7 +76,7 @@ namespace Emby.Server.Implementations.Devices
public void SaveCapabilities(string deviceId, ClientCapabilities capabilities) public void SaveCapabilities(string deviceId, ClientCapabilities capabilities)
{ {
var path = Path.Combine(GetDevicePath(deviceId), "capabilities.json"); var path = Path.Combine(GetDevicePath(deviceId), "capabilities.json");
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path)); Directory.CreateDirectory(Path.GetDirectoryName(path));
lock (_capabilitiesSyncLock) lock (_capabilitiesSyncLock)
{ {
@ -239,7 +239,7 @@ namespace Emby.Server.Implementations.Devices
path = Path.Combine(path, file.Name); path = Path.Combine(path, file.Name);
path = Path.ChangeExtension(path, MimeTypes.ToExtension(file.MimeType) ?? "jpg"); path = Path.ChangeExtension(path, MimeTypes.ToExtension(file.MimeType) ?? "jpg");
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path)); Directory.CreateDirectory(Path.GetDirectoryName(path));
await EnsureLibraryFolder(uploadPathInfo.Item2, uploadPathInfo.Item3).ConfigureAwait(false); await EnsureLibraryFolder(uploadPathInfo.Item2, uploadPathInfo.Item3).ConfigureAwait(false);
@ -275,7 +275,7 @@ namespace Emby.Server.Implementations.Devices
private void AddCameraUpload(string deviceId, LocalFileInfo file) private void AddCameraUpload(string deviceId, LocalFileInfo file)
{ {
var path = Path.Combine(GetDevicePath(deviceId), "camerauploads.json"); var path = Path.Combine(GetDevicePath(deviceId), "camerauploads.json");
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path)); Directory.CreateDirectory(Path.GetDirectoryName(path));
lock (_cameraUploadSyncLock) lock (_cameraUploadSyncLock)
{ {
@ -317,7 +317,7 @@ namespace Emby.Server.Implementations.Devices
return Task.CompletedTask; return Task.CompletedTask;
} }
_fileSystem.CreateDirectory(path); Directory.CreateDirectory(path);
var libraryOptions = new LibraryOptions var libraryOptions = new LibraryOptions
{ {
@ -431,7 +431,7 @@ namespace Emby.Server.Implementations.Devices
{ {
var path = _deviceManager.GetUploadsPath(); var path = _deviceManager.GetUploadsPath();
if (_fileSystem.DirectoryExists(path)) if (Directory.Exists(path))
{ {
try try
{ {

View file

@ -48,7 +48,7 @@ namespace Emby.Server.Implementations.FFMpeg
var prebuiltFolder = _appPaths.ProgramSystemPath; var prebuiltFolder = _appPaths.ProgramSystemPath;
var prebuiltffmpeg = Path.Combine(prebuiltFolder, downloadInfo.FFMpegFilename); var prebuiltffmpeg = Path.Combine(prebuiltFolder, downloadInfo.FFMpegFilename);
var prebuiltffprobe = Path.Combine(prebuiltFolder, downloadInfo.FFProbeFilename); var prebuiltffprobe = Path.Combine(prebuiltFolder, downloadInfo.FFProbeFilename);
if (_fileSystem.FileExists(prebuiltffmpeg) && _fileSystem.FileExists(prebuiltffprobe)) if (File.Exists(prebuiltffmpeg) && File.Exists(prebuiltffprobe))
{ {
return new FFMpegInfo return new FFMpegInfo
{ {
@ -75,11 +75,11 @@ namespace Emby.Server.Implementations.FFMpeg
Version = version Version = version
}; };
_fileSystem.CreateDirectory(versionedDirectoryPath); Directory.CreateDirectory(versionedDirectoryPath);
var excludeFromDeletions = new List<string> { versionedDirectoryPath }; var excludeFromDeletions = new List<string> { versionedDirectoryPath };
if (!_fileSystem.FileExists(info.ProbePath) || !_fileSystem.FileExists(info.EncoderPath)) if (!File.Exists(info.ProbePath) || !File.Exists(info.EncoderPath))
{ {
// ffmpeg not present. See if there's an older version we can start with // ffmpeg not present. See if there's an older version we can start with
var existingVersion = GetExistingVersion(info, rootEncoderPath); var existingVersion = GetExistingVersion(info, rootEncoderPath);
@ -92,7 +92,7 @@ namespace Emby.Server.Implementations.FFMpeg
else else
{ {
info = existingVersion; info = existingVersion;
versionedDirectoryPath = _fileSystem.GetDirectoryName(info.EncoderPath); versionedDirectoryPath = Path.GetDirectoryName(info.EncoderPath);
excludeFromDeletions.Add(versionedDirectoryPath); excludeFromDeletions.Add(versionedDirectoryPath);
} }
} }
@ -130,7 +130,7 @@ namespace Emby.Server.Implementations.FFMpeg
{ {
EncoderPath = encoder, EncoderPath = encoder,
ProbePath = probe, ProbePath = probe,
Version = Path.GetFileName(_fileSystem.GetDirectoryName(probe)) Version = Path.GetFileName(Path.GetDirectoryName(probe))
}; };
} }
} }

View file

@ -286,28 +286,18 @@ namespace Emby.Server.Implementations.HttpClientManager
private HttpResponseInfo GetCachedResponse(string responseCachePath, TimeSpan cacheLength, string url) private HttpResponseInfo GetCachedResponse(string responseCachePath, TimeSpan cacheLength, string url)
{ {
try if (File.Exists(responseCachePath)
&& _fileSystem.GetLastWriteTimeUtc(responseCachePath).Add(cacheLength) > DateTime.UtcNow)
{ {
if (_fileSystem.GetLastWriteTimeUtc(responseCachePath).Add(cacheLength) > DateTime.UtcNow) var stream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read, true);
return new HttpResponseInfo
{ {
var stream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read, true); ResponseUrl = url,
Content = stream,
return new HttpResponseInfo StatusCode = HttpStatusCode.OK,
{ ContentLength = stream.Length
ResponseUrl = url, };
Content = stream,
StatusCode = HttpStatusCode.OK,
ContentLength = stream.Length
};
}
}
catch (FileNotFoundException) // REVIEW: @bond Is this really faster?
{
}
catch (DirectoryNotFoundException)
{
} }
return null; return null;
@ -315,7 +305,7 @@ namespace Emby.Server.Implementations.HttpClientManager
private async Task CacheResponse(HttpResponseInfo response, string responseCachePath) private async Task CacheResponse(HttpResponseInfo response, string responseCachePath)
{ {
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(responseCachePath)); Directory.CreateDirectory(Path.GetDirectoryName(responseCachePath));
using (var fileStream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None, true)) using (var fileStream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None, true))
{ {
@ -523,7 +513,7 @@ namespace Emby.Server.Implementations.HttpClientManager
{ {
ValidateParams(options); ValidateParams(options);
_fileSystem.CreateDirectory(_appPaths.TempDirectory); Directory.CreateDirectory(_appPaths.TempDirectory);
var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp"); var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");

View file

@ -189,13 +189,13 @@ namespace Emby.Server.Implementations.IO
{ {
item = LibraryManager.FindByPath(path, null); item = LibraryManager.FindByPath(path, null);
path = _fileSystem.GetDirectoryName(path); path = System.IO.Path.GetDirectoryName(path);
} }
if (item != null) if (item != null)
{ {
// If the item has been deleted find the first valid parent that still exists // If the item has been deleted find the first valid parent that still exists
while (!_fileSystem.DirectoryExists(item.Path) && !_fileSystem.FileExists(item.Path)) while (!Directory.Exists(item.Path) && !File.Exists(item.Path))
{ {
item = item.GetOwner() ?? item.GetParent(); item = item.GetOwner() ?? item.GetParent();

View file

@ -277,7 +277,7 @@ namespace Emby.Server.Implementations.IO
/// <param name="path">The path.</param> /// <param name="path">The path.</param>
private void StartWatchingPath(string path) private void StartWatchingPath(string path)
{ {
if (!_fileSystem.DirectoryExists(path)) if (!Directory.Exists(path))
{ {
// Seeing a crash in the mono runtime due to an exception being thrown on a different thread // Seeing a crash in the mono runtime due to an exception being thrown on a different thread
Logger.LogInformation("Skipping realtime monitor for {0} because the path does not exist", path); Logger.LogInformation("Skipping realtime monitor for {0} because the path does not exist", path);
@ -483,7 +483,7 @@ namespace Emby.Server.Implementations.IO
} }
// Go up a level // Go up a level
var parent = _fileSystem.GetDirectoryName(i); var parent = Path.GetDirectoryName(i);
if (!string.IsNullOrEmpty(parent)) if (!string.IsNullOrEmpty(parent))
{ {
if (_fileSystem.AreEqual(parent, path)) if (_fileSystem.AreEqual(parent, path))
@ -509,7 +509,7 @@ namespace Emby.Server.Implementations.IO
private void CreateRefresher(string path) private void CreateRefresher(string path)
{ {
var parentPath = _fileSystem.GetDirectoryName(path); var parentPath = Path.GetDirectoryName(path);
lock (_activeRefreshers) lock (_activeRefreshers)
{ {
@ -538,7 +538,7 @@ namespace Emby.Server.Implementations.IO
} }
// They are siblings. Rebase the refresher to the parent folder. // They are siblings. Rebase the refresher to the parent folder.
if (string.Equals(parentPath, _fileSystem.GetDirectoryName(refresher.Path), StringComparison.Ordinal)) if (string.Equals(parentPath, Path.GetDirectoryName(refresher.Path), StringComparison.Ordinal))
{ {
refresher.ResetPath(parentPath, path); refresher.ResetPath(parentPath, path);
return; return;

View file

@ -50,7 +50,7 @@ namespace Emby.Server.Implementations.IO
_isEnvironmentCaseInsensitive = environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows; _isEnvironmentCaseInsensitive = environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows;
} }
public string DefaultDirectory public virtual string DefaultDirectory
{ {
get get
{ {
@ -60,7 +60,7 @@ namespace Emby.Server.Implementations.IO
{ {
try try
{ {
if (DirectoryExists(value)) if (Directory.Exists(value))
{ {
return value; return value;
} }
@ -75,7 +75,7 @@ namespace Emby.Server.Implementations.IO
} }
} }
public void AddShortcutHandler(IShortcutHandler handler) public virtual void AddShortcutHandler(IShortcutHandler handler)
{ {
_shortcutHandlers.Add(handler); _shortcutHandlers.Add(handler);
} }
@ -94,13 +94,6 @@ namespace Emby.Server.Implementations.IO
} }
} }
public char DirectorySeparatorChar => Path.DirectorySeparatorChar;
public string GetFullPath(string path)
{
return Path.GetFullPath(path);
}
/// <summary> /// <summary>
/// Determines whether the specified filename is shortcut. /// Determines whether the specified filename is shortcut.
/// </summary> /// </summary>
@ -142,7 +135,7 @@ namespace Emby.Server.Implementations.IO
return null; return null;
} }
public string MakeAbsolutePath(string folderPath, string filePath) public virtual string MakeAbsolutePath(string folderPath, string filePath)
{ {
if (string.IsNullOrWhiteSpace(filePath)) return filePath; if (string.IsNullOrWhiteSpace(filePath)) return filePath;
@ -195,7 +188,7 @@ namespace Emby.Server.Implementations.IO
/// or /// or
/// target /// target
/// </exception> /// </exception>
public void CreateShortcut(string shortcutPath, string target) public virtual void CreateShortcut(string shortcutPath, string target)
{ {
if (string.IsNullOrEmpty(shortcutPath)) if (string.IsNullOrEmpty(shortcutPath))
{ {
@ -227,7 +220,7 @@ namespace Emby.Server.Implementations.IO
/// <returns>A <see cref="FileSystemMetadata"/> object.</returns> /// <returns>A <see cref="FileSystemMetadata"/> object.</returns>
/// <remarks>If the specified path points to a directory, the returned <see cref="FileSystemMetadata"/> object's /// <remarks>If the specified path points to a directory, the returned <see cref="FileSystemMetadata"/> object's
/// <see cref="FileSystemMetadata.IsDirectory"/> property will be set to true and all other properties will reflect the properties of the directory.</remarks> /// <see cref="FileSystemMetadata.IsDirectory"/> property will be set to true and all other properties will reflect the properties of the directory.</remarks>
public FileSystemMetadata GetFileSystemInfo(string path) public virtual FileSystemMetadata GetFileSystemInfo(string path)
{ {
// Take a guess to try and avoid two file system hits, but we'll double-check by calling Exists // Take a guess to try and avoid two file system hits, but we'll double-check by calling Exists
if (Path.HasExtension(path)) if (Path.HasExtension(path))
@ -262,7 +255,7 @@ namespace Emby.Server.Implementations.IO
/// <remarks><para>If the specified path points to a directory, the returned <see cref="FileSystemMetadata"/> object's /// <remarks><para>If the specified path points to a directory, the returned <see cref="FileSystemMetadata"/> object's
/// <see cref="FileSystemMetadata.IsDirectory"/> property and the <see cref="FileSystemMetadata.Exists"/> property will both be set to false.</para> /// <see cref="FileSystemMetadata.IsDirectory"/> property and the <see cref="FileSystemMetadata.Exists"/> property will both be set to false.</para>
/// <para>For automatic handling of files <b>and</b> directories, use <see cref="GetFileSystemInfo"/>.</para></remarks> /// <para>For automatic handling of files <b>and</b> directories, use <see cref="GetFileSystemInfo"/>.</para></remarks>
public FileSystemMetadata GetFileInfo(string path) public virtual FileSystemMetadata GetFileInfo(string path)
{ {
var fileInfo = new FileInfo(path); var fileInfo = new FileInfo(path);
@ -277,7 +270,7 @@ namespace Emby.Server.Implementations.IO
/// <remarks><para>If the specified path points to a file, the returned <see cref="FileSystemMetadata"/> object's /// <remarks><para>If the specified path points to a file, the returned <see cref="FileSystemMetadata"/> object's
/// <see cref="FileSystemMetadata.IsDirectory"/> property will be set to true and the <see cref="FileSystemMetadata.Exists"/> property will be set to false.</para> /// <see cref="FileSystemMetadata.IsDirectory"/> property will be set to true and the <see cref="FileSystemMetadata.Exists"/> property will be set to false.</para>
/// <para>For automatic handling of files <b>and</b> directories, use <see cref="GetFileSystemInfo"/>.</para></remarks> /// <para>For automatic handling of files <b>and</b> directories, use <see cref="GetFileSystemInfo"/>.</para></remarks>
public FileSystemMetadata GetDirectoryInfo(string path) public virtual FileSystemMetadata GetDirectoryInfo(string path)
{ {
var fileInfo = new DirectoryInfo(path); var fileInfo = new DirectoryInfo(path);
@ -339,24 +332,19 @@ namespace Emby.Server.Implementations.IO
return result; return result;
} }
/// <summary>
/// The space char
/// </summary>
private const char SpaceChar = ' ';
/// <summary> /// <summary>
/// Takes a filename and removes invalid characters /// Takes a filename and removes invalid characters
/// </summary> /// </summary>
/// <param name="filename">The filename.</param> /// <param name="filename">The filename.</param>
/// <returns>System.String.</returns> /// <returns>System.String.</returns>
/// <exception cref="ArgumentNullException">filename</exception> /// <exception cref="ArgumentNullException">filename</exception>
public string GetValidFilename(string filename) public virtual string GetValidFilename(string filename)
{ {
var builder = new StringBuilder(filename); var builder = new StringBuilder(filename);
foreach (var c in _invalidFileNameChars) foreach (var c in _invalidFileNameChars)
{ {
builder = builder.Replace(c, SpaceChar); builder = builder.Replace(c, ' ');
} }
return builder.ToString(); return builder.ToString();
@ -386,17 +374,17 @@ namespace Emby.Server.Implementations.IO
/// </summary> /// </summary>
/// <param name="path">The path.</param> /// <param name="path">The path.</param>
/// <returns>DateTime.</returns> /// <returns>DateTime.</returns>
public DateTime GetCreationTimeUtc(string path) public virtual DateTime GetCreationTimeUtc(string path)
{ {
return GetCreationTimeUtc(GetFileSystemInfo(path)); return GetCreationTimeUtc(GetFileSystemInfo(path));
} }
public DateTime GetCreationTimeUtc(FileSystemMetadata info) public virtual DateTime GetCreationTimeUtc(FileSystemMetadata info)
{ {
return info.CreationTimeUtc; return info.CreationTimeUtc;
} }
public DateTime GetLastWriteTimeUtc(FileSystemMetadata info) public virtual DateTime GetLastWriteTimeUtc(FileSystemMetadata info)
{ {
return info.LastWriteTimeUtc; return info.LastWriteTimeUtc;
} }
@ -425,7 +413,7 @@ namespace Emby.Server.Implementations.IO
/// </summary> /// </summary>
/// <param name="path">The path.</param> /// <param name="path">The path.</param>
/// <returns>DateTime.</returns> /// <returns>DateTime.</returns>
public DateTime GetLastWriteTimeUtc(string path) public virtual DateTime GetLastWriteTimeUtc(string path)
{ {
return GetLastWriteTimeUtc(GetFileSystemInfo(path)); return GetLastWriteTimeUtc(GetFileSystemInfo(path));
} }
@ -439,7 +427,7 @@ namespace Emby.Server.Implementations.IO
/// <param name="share">The share.</param> /// <param name="share">The share.</param>
/// <param name="isAsync">if set to <c>true</c> [is asynchronous].</param> /// <param name="isAsync">if set to <c>true</c> [is asynchronous].</param>
/// <returns>FileStream.</returns> /// <returns>FileStream.</returns>
public Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, bool isAsync = false) public virtual Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, bool isAsync = false)
{ {
if (_supportsAsyncFileStreams && isAsync) if (_supportsAsyncFileStreams && isAsync)
{ {
@ -449,7 +437,7 @@ namespace Emby.Server.Implementations.IO
return GetFileStream(path, mode, access, share, FileOpenOptions.None); return GetFileStream(path, mode, access, share, FileOpenOptions.None);
} }
public Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, FileOpenOptions fileOpenOptions) public virtual Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, FileOpenOptions fileOpenOptions)
=> new FileStream(path, GetFileMode(mode), GetFileAccess(access), GetFileShare(share), 4096, GetFileOptions(fileOpenOptions)); => new FileStream(path, GetFileMode(mode), GetFileAccess(access), GetFileShare(share), 4096, GetFileOptions(fileOpenOptions));
private static FileOptions GetFileOptions(FileOpenOptions mode) private static FileOptions GetFileOptions(FileOpenOptions mode)
@ -511,7 +499,7 @@ namespace Emby.Server.Implementations.IO
} }
} }
public void SetHidden(string path, bool isHidden) public virtual void SetHidden(string path, bool isHidden)
{ {
if (_environmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows) if (_environmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows)
{ {
@ -535,7 +523,7 @@ namespace Emby.Server.Implementations.IO
} }
} }
public void SetReadOnly(string path, bool isReadOnly) public virtual void SetReadOnly(string path, bool isReadOnly)
{ {
if (_environmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows) if (_environmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows)
{ {
@ -559,7 +547,7 @@ namespace Emby.Server.Implementations.IO
} }
} }
public void SetAttributes(string path, bool isHidden, bool isReadOnly) public virtual void SetAttributes(string path, bool isHidden, bool isReadOnly)
{ {
if (_environmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows) if (_environmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows)
{ {
@ -611,7 +599,7 @@ namespace Emby.Server.Implementations.IO
/// </summary> /// </summary>
/// <param name="file1">The file1.</param> /// <param name="file1">The file1.</param>
/// <param name="file2">The file2.</param> /// <param name="file2">The file2.</param>
public void SwapFiles(string file1, string file2) public virtual void SwapFiles(string file1, string file2)
{ {
if (string.IsNullOrEmpty(file1)) if (string.IsNullOrEmpty(file1))
{ {
@ -630,18 +618,13 @@ namespace Emby.Server.Implementations.IO
SetHidden(file2, false); SetHidden(file2, false);
Directory.CreateDirectory(_tempPath); Directory.CreateDirectory(_tempPath);
CopyFile(file1, temp1, true); File.Copy(file1, temp1, true);
CopyFile(file2, file1, true); File.Copy(file2, file1, true);
CopyFile(temp1, file2, true); File.Copy(temp1, file2, true);
} }
private static char GetDirectorySeparatorChar(string path) public virtual bool ContainsSubPath(string parentPath, string path)
{
return Path.DirectorySeparatorChar;
}
public bool ContainsSubPath(string parentPath, string path)
{ {
if (string.IsNullOrEmpty(parentPath)) if (string.IsNullOrEmpty(parentPath))
{ {
@ -653,19 +636,19 @@ namespace Emby.Server.Implementations.IO
throw new ArgumentNullException(nameof(path)); throw new ArgumentNullException(nameof(path));
} }
var separatorChar = GetDirectorySeparatorChar(parentPath); var separatorChar = Path.DirectorySeparatorChar;
return path.IndexOf(parentPath.TrimEnd(separatorChar) + separatorChar, StringComparison.OrdinalIgnoreCase) != -1; return path.IndexOf(parentPath.TrimEnd(separatorChar) + separatorChar, StringComparison.OrdinalIgnoreCase) != -1;
} }
public bool IsRootPath(string path) public virtual bool IsRootPath(string path)
{ {
if (string.IsNullOrEmpty(path)) if (string.IsNullOrEmpty(path))
{ {
throw new ArgumentNullException(nameof(path)); throw new ArgumentNullException(nameof(path));
} }
var parent = GetDirectoryName(path); var parent = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(parent)) if (!string.IsNullOrEmpty(parent))
{ {
@ -675,12 +658,7 @@ namespace Emby.Server.Implementations.IO
return true; return true;
} }
public string GetDirectoryName(string path) public virtual string NormalizePath(string path)
{
return Path.GetDirectoryName(path);
}
public string NormalizePath(string path)
{ {
if (string.IsNullOrEmpty(path)) if (string.IsNullOrEmpty(path))
{ {
@ -692,10 +670,10 @@ namespace Emby.Server.Implementations.IO
return path; return path;
} }
return path.TrimEnd(GetDirectorySeparatorChar(path)); return path.TrimEnd(Path.DirectorySeparatorChar);
} }
public bool AreEqual(string path1, string path2) public virtual bool AreEqual(string path1, string path2)
{ {
if (path1 == null && path2 == null) if (path1 == null && path2 == null)
{ {
@ -710,7 +688,7 @@ namespace Emby.Server.Implementations.IO
return string.Equals(NormalizePath(path1), NormalizePath(path2), StringComparison.OrdinalIgnoreCase); return string.Equals(NormalizePath(path1), NormalizePath(path2), StringComparison.OrdinalIgnoreCase);
} }
public string GetFileNameWithoutExtension(FileSystemMetadata info) public virtual string GetFileNameWithoutExtension(FileSystemMetadata info)
{ {
if (info.IsDirectory) if (info.IsDirectory)
{ {
@ -720,12 +698,7 @@ namespace Emby.Server.Implementations.IO
return Path.GetFileNameWithoutExtension(info.FullName); return Path.GetFileNameWithoutExtension(info.FullName);
} }
public string GetFileNameWithoutExtension(string path) public virtual bool IsPathFile(string path)
{
return Path.GetFileNameWithoutExtension(path);
}
public bool IsPathFile(string path)
{ {
// Cannot use Path.IsPathRooted because it returns false under mono when using windows-based paths, e.g. C:\\ // Cannot use Path.IsPathRooted because it returns false under mono when using windows-based paths, e.g. C:\\
@ -740,23 +713,13 @@ namespace Emby.Server.Implementations.IO
//return Path.IsPathRooted(path); //return Path.IsPathRooted(path);
} }
public void DeleteFile(string path) public virtual void DeleteFile(string path)
{ {
SetAttributes(path, false, false); SetAttributes(path, false, false);
File.Delete(path); File.Delete(path);
} }
public void DeleteDirectory(string path, bool recursive) public virtual List<FileSystemMetadata> GetDrives()
{
Directory.Delete(path, recursive);
}
public void CreateDirectory(string path)
{
Directory.CreateDirectory(path);
}
public List<FileSystemMetadata> GetDrives()
{ {
// Only include drives in the ready state or this method could end up being very slow, waiting for drives to timeout // Only include drives in the ready state or this method could end up being very slow, waiting for drives to timeout
return DriveInfo.GetDrives().Where(d => d.IsReady).Select(d => new FileSystemMetadata return DriveInfo.GetDrives().Where(d => d.IsReady).Select(d => new FileSystemMetadata
@ -768,19 +731,19 @@ namespace Emby.Server.Implementations.IO
}).ToList(); }).ToList();
} }
public IEnumerable<FileSystemMetadata> GetDirectories(string path, bool recursive = false) public virtual IEnumerable<FileSystemMetadata> GetDirectories(string path, bool recursive = false)
{ {
var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
return ToMetadata(new DirectoryInfo(path).EnumerateDirectories("*", searchOption)); return ToMetadata(new DirectoryInfo(path).EnumerateDirectories("*", searchOption));
} }
public IEnumerable<FileSystemMetadata> GetFiles(string path, bool recursive = false) public virtual IEnumerable<FileSystemMetadata> GetFiles(string path, bool recursive = false)
{ {
return GetFiles(path, null, false, recursive); return GetFiles(path, null, false, recursive);
} }
public IEnumerable<FileSystemMetadata> GetFiles(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false) public virtual IEnumerable<FileSystemMetadata> GetFiles(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
{ {
var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
@ -809,7 +772,7 @@ namespace Emby.Server.Implementations.IO
return ToMetadata(files); return ToMetadata(files);
} }
public IEnumerable<FileSystemMetadata> GetFileSystemEntries(string path, bool recursive = false) public virtual IEnumerable<FileSystemMetadata> GetFileSystemEntries(string path, bool recursive = false)
{ {
var directoryInfo = new DirectoryInfo(path); var directoryInfo = new DirectoryInfo(path);
var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
@ -827,89 +790,19 @@ namespace Emby.Server.Implementations.IO
{ {
return infos.Select(GetFileSystemMetadata); return infos.Select(GetFileSystemMetadata);
} }
public string[] ReadAllLines(string path) public virtual IEnumerable<string> GetDirectoryPaths(string path, bool recursive = false)
{
return File.ReadAllLines(path);
}
public void WriteAllLines(string path, IEnumerable<string> lines)
{
File.WriteAllLines(path, lines);
}
public Stream OpenRead(string path)
{
return File.OpenRead(path);
}
public void CopyFile(string source, string target, bool overwrite)
{
File.Copy(source, target, overwrite);
}
public void MoveFile(string source, string target)
{
File.Move(source, target);
}
public void MoveDirectory(string source, string target)
{
Directory.Move(source, target);
}
public bool DirectoryExists(string path)
{
return Directory.Exists(path);
}
public bool FileExists(string path)
{
return File.Exists(path);
}
public string ReadAllText(string path)
{
return File.ReadAllText(path);
}
public byte[] ReadAllBytes(string path)
{
return File.ReadAllBytes(path);
}
public void WriteAllText(string path, string text, Encoding encoding)
{
File.WriteAllText(path, text, encoding);
}
public void WriteAllText(string path, string text)
{
File.WriteAllText(path, text);
}
public void WriteAllBytes(string path, byte[] bytes)
{
File.WriteAllBytes(path, bytes);
}
public string ReadAllText(string path, Encoding encoding)
{
return File.ReadAllText(path, encoding);
}
public IEnumerable<string> GetDirectoryPaths(string path, bool recursive = false)
{ {
var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
return Directory.EnumerateDirectories(path, "*", searchOption); return Directory.EnumerateDirectories(path, "*", searchOption);
} }
public IEnumerable<string> GetFilePaths(string path, bool recursive = false) public virtual IEnumerable<string> GetFilePaths(string path, bool recursive = false)
{ {
return GetFilePaths(path, null, false, recursive); return GetFilePaths(path, null, false, recursive);
} }
public IEnumerable<string> GetFilePaths(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false) public virtual IEnumerable<string> GetFilePaths(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
{ {
var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
@ -938,7 +831,7 @@ namespace Emby.Server.Implementations.IO
return files; return files;
} }
public IEnumerable<string> GetFileSystemEntryPaths(string path, bool recursive = false) public virtual IEnumerable<string> GetFileSystemEntryPaths(string path, bool recursive = false)
{ {
var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
return Directory.EnumerateFileSystemEntries(path, "*", searchOption); return Directory.EnumerateFileSystemEntries(path, "*", searchOption);
@ -948,7 +841,7 @@ namespace Emby.Server.Implementations.IO
{ {
if (_environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.OSX) if (_environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.OSX)
{ {
RunProcess("chmod", "+x \"" + path + "\"", GetDirectoryName(path)); RunProcess("chmod", "+x \"" + path + "\"", Path.GetDirectoryName(path));
} }
} }

View file

@ -24,7 +24,7 @@ namespace Emby.Server.Implementations.IO
if (string.Equals(Path.GetExtension(shortcutPath), ".mblink", StringComparison.OrdinalIgnoreCase)) if (string.Equals(Path.GetExtension(shortcutPath), ".mblink", StringComparison.OrdinalIgnoreCase))
{ {
var path = _fileSystem.ReadAllText(shortcutPath); var path = File.ReadAllText(shortcutPath);
return _fileSystem.NormalizePath(path); return _fileSystem.NormalizePath(path);
} }
@ -44,7 +44,7 @@ namespace Emby.Server.Implementations.IO
throw new ArgumentNullException(nameof(targetPath)); throw new ArgumentNullException(nameof(targetPath));
} }
_fileSystem.WriteAllText(shortcutPath, targetPath); File.WriteAllText(shortcutPath, targetPath);
} }
} }
} }

View file

@ -99,7 +99,7 @@ namespace Emby.Server.Implementations.Images
CancellationToken cancellationToken) CancellationToken cancellationToken)
{ {
var outputPathWithoutExtension = Path.Combine(ApplicationPaths.TempDirectory, Guid.NewGuid().ToString("N")); var outputPathWithoutExtension = Path.Combine(ApplicationPaths.TempDirectory, Guid.NewGuid().ToString("N"));
FileSystem.CreateDirectory(FileSystem.GetDirectoryName(outputPathWithoutExtension)); Directory.CreateDirectory(Path.GetDirectoryName(outputPathWithoutExtension));
string outputPath = CreateImage(item, itemsWithImages, outputPathWithoutExtension, imageType, 0); string outputPath = CreateImage(item, itemsWithImages, outputPathWithoutExtension, imageType, 0);
if (string.IsNullOrEmpty(outputPath)) if (string.IsNullOrEmpty(outputPath))
@ -165,7 +165,7 @@ namespace Emby.Server.Implementations.Images
private string CreateCollage(BaseItem primaryItem, List<BaseItem> items, string outputPath, int width, int height) private string CreateCollage(BaseItem primaryItem, List<BaseItem> items, string outputPath, int width, int height)
{ {
FileSystem.CreateDirectory(FileSystem.GetDirectoryName(outputPath)); Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
var options = new ImageCollageOptions var options = new ImageCollageOptions
{ {
@ -300,7 +300,7 @@ namespace Emby.Server.Implementations.Images
var ext = Path.GetExtension(image); var ext = Path.GetExtension(image);
var outputPath = Path.ChangeExtension(outputPathWithoutExtension, ext); var outputPath = Path.ChangeExtension(outputPathWithoutExtension, ext);
FileSystem.CopyFile(image, outputPath, true); File.Copy(image, outputPath, true);
return outputPath; return outputPath;
} }

View file

@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Linq; using System.Linq;
using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Library;
@ -146,7 +147,7 @@ namespace Emby.Server.Implementations.Library
if (parent != null) if (parent != null)
{ {
// Don't resolve these into audio files // Don't resolve these into audio files
if (string.Equals(_fileSystem.GetFileNameWithoutExtension(filename), BaseItem.ThemeSongFilename) && _libraryManager.IsAudioFile(filename)) if (string.Equals(Path.GetFileNameWithoutExtension(filename), BaseItem.ThemeSongFilename) && _libraryManager.IsAudioFile(filename))
{ {
return true; return true;
} }

View file

@ -375,7 +375,7 @@ namespace Emby.Server.Implementations.Library
try try
{ {
_fileSystem.DeleteDirectory(metadataPath, true); Directory.Delete(metadataPath, true);
} }
catch (IOException) catch (IOException)
{ {
@ -395,38 +395,33 @@ namespace Emby.Server.Implementations.Library
foreach (var fileSystemInfo in item.GetDeletePaths().ToList()) foreach (var fileSystemInfo in item.GetDeletePaths().ToList())
{ {
try if (File.Exists(fileSystemInfo.FullName))
{ {
_logger.LogDebug("Deleting path {path}", fileSystemInfo.FullName); try
if (fileSystemInfo.IsDirectory)
{ {
_fileSystem.DeleteDirectory(fileSystemInfo.FullName, true); _logger.LogDebug("Deleting path {path}", fileSystemInfo.FullName);
if (fileSystemInfo.IsDirectory)
{
Directory.Delete(fileSystemInfo.FullName, true);
}
else
{
File.Delete(fileSystemInfo.FullName);
}
} }
else catch (IOException)
{ {
_fileSystem.DeleteFile(fileSystemInfo.FullName); if (isRequiredForDelete)
{
throw;
}
} }
} catch (UnauthorizedAccessException)
catch (FileNotFoundException)
{
// may have already been deleted manually by user
}
catch (DirectoryNotFoundException)
{
// may have already been deleted manually by user
}
catch (IOException)
{
if (isRequiredForDelete)
{ {
throw; if (isRequiredForDelete)
} {
} throw;
catch (UnauthorizedAccessException) }
{
if (isRequiredForDelete)
{
throw;
} }
} }
@ -725,7 +720,7 @@ namespace Emby.Server.Implementations.Library
{ {
var rootFolderPath = ConfigurationManager.ApplicationPaths.RootFolderPath; var rootFolderPath = ConfigurationManager.ApplicationPaths.RootFolderPath;
_fileSystem.CreateDirectory(rootFolderPath); Directory.CreateDirectory(rootFolderPath);
var rootFolder = GetItemById(GetNewItemId(rootFolderPath, typeof(AggregateFolder))) as AggregateFolder ?? ((Folder)ResolvePath(_fileSystem.GetDirectoryInfo(rootFolderPath))).DeepCopy<Folder, AggregateFolder>(); var rootFolder = GetItemById(GetNewItemId(rootFolderPath, typeof(AggregateFolder))) as AggregateFolder ?? ((Folder)ResolvePath(_fileSystem.GetDirectoryInfo(rootFolderPath))).DeepCopy<Folder, AggregateFolder>();
@ -739,7 +734,7 @@ namespace Emby.Server.Implementations.Library
// Add in the plug-in folders // Add in the plug-in folders
var path = Path.Combine(ConfigurationManager.ApplicationPaths.DataPath, "playlists"); var path = Path.Combine(ConfigurationManager.ApplicationPaths.DataPath, "playlists");
_fileSystem.CreateDirectory(path); Directory.CreateDirectory(path);
Folder folder = new PlaylistsFolder Folder folder = new PlaylistsFolder
{ {
@ -790,7 +785,7 @@ namespace Emby.Server.Implementations.Library
{ {
var userRootPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath; var userRootPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath;
_fileSystem.CreateDirectory(userRootPath); Directory.CreateDirectory(userRootPath);
var tmpItem = GetItemById(GetNewItemId(userRootPath, typeof(UserRootFolder))) as UserRootFolder; var tmpItem = GetItemById(GetNewItemId(userRootPath, typeof(UserRootFolder))) as UserRootFolder;
@ -1004,7 +999,7 @@ namespace Emby.Server.Implementations.Library
public Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress) public Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress)
{ {
// Ensure the location is available. // Ensure the location is available.
_fileSystem.CreateDirectory(ConfigurationManager.ApplicationPaths.PeoplePath); Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.PeoplePath);
return new PeopleValidator(this, _logger, ConfigurationManager, _fileSystem).ValidatePeople(cancellationToken, progress); return new PeopleValidator(this, _logger, ConfigurationManager, _fileSystem).ValidatePeople(cancellationToken, progress);
} }
@ -1233,7 +1228,7 @@ namespace Emby.Server.Implementations.Library
private string GetCollectionType(string path) private string GetCollectionType(string path)
{ {
return _fileSystem.GetFilePaths(path, new[] { ".collection" }, true, false) return _fileSystem.GetFilePaths(path, new[] { ".collection" }, true, false)
.Select(i => _fileSystem.GetFileNameWithoutExtension(i)) .Select(i => Path.GetFileNameWithoutExtension(i))
.FirstOrDefault(i => !string.IsNullOrEmpty(i)); .FirstOrDefault(i => !string.IsNullOrEmpty(i));
} }
@ -2151,7 +2146,7 @@ namespace Emby.Server.Implementations.Library
if (item == null || !string.Equals(item.Path, path, StringComparison.OrdinalIgnoreCase)) if (item == null || !string.Equals(item.Path, path, StringComparison.OrdinalIgnoreCase))
{ {
_fileSystem.CreateDirectory(path); Directory.CreateDirectory(path);
item = new UserView item = new UserView
{ {
@ -2196,7 +2191,7 @@ namespace Emby.Server.Implementations.Library
if (item == null) if (item == null)
{ {
_fileSystem.CreateDirectory(path); Directory.CreateDirectory(path);
item = new UserView item = new UserView
{ {
@ -2261,7 +2256,7 @@ namespace Emby.Server.Implementations.Library
if (item == null) if (item == null)
{ {
_fileSystem.CreateDirectory(path); Directory.CreateDirectory(path);
item = new UserView item = new UserView
{ {
@ -2329,7 +2324,7 @@ namespace Emby.Server.Implementations.Library
if (item == null) if (item == null)
{ {
_fileSystem.CreateDirectory(path); Directory.CreateDirectory(path);
item = new UserView item = new UserView
{ {
@ -2868,7 +2863,7 @@ namespace Emby.Server.Implementations.Library
var rootFolderPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath; var rootFolderPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath;
var virtualFolderPath = Path.Combine(rootFolderPath, name); var virtualFolderPath = Path.Combine(rootFolderPath, name);
while (_fileSystem.DirectoryExists(virtualFolderPath)) while (Directory.Exists(virtualFolderPath))
{ {
name += "1"; name += "1";
virtualFolderPath = Path.Combine(rootFolderPath, name); virtualFolderPath = Path.Combine(rootFolderPath, name);
@ -2877,7 +2872,7 @@ namespace Emby.Server.Implementations.Library
var mediaPathInfos = options.PathInfos; var mediaPathInfos = options.PathInfos;
if (mediaPathInfos != null) if (mediaPathInfos != null)
{ {
var invalidpath = mediaPathInfos.FirstOrDefault(i => !_fileSystem.DirectoryExists(i.Path)); var invalidpath = mediaPathInfos.FirstOrDefault(i => !Directory.Exists(i.Path));
if (invalidpath != null) if (invalidpath != null)
{ {
throw new ArgumentException("The specified path does not exist: " + invalidpath.Path + "."); throw new ArgumentException("The specified path does not exist: " + invalidpath.Path + ".");
@ -2888,13 +2883,13 @@ namespace Emby.Server.Implementations.Library
try try
{ {
_fileSystem.CreateDirectory(virtualFolderPath); Directory.CreateDirectory(virtualFolderPath);
if (!string.IsNullOrEmpty(collectionType)) if (!string.IsNullOrEmpty(collectionType))
{ {
var path = Path.Combine(virtualFolderPath, collectionType + ".collection"); var path = Path.Combine(virtualFolderPath, collectionType + ".collection");
_fileSystem.WriteAllBytes(path, Array.Empty<byte>()); File.WriteAllBytes(path, Array.Empty<byte>());
} }
CollectionFolder.SaveLibraryOptions(virtualFolderPath, options); CollectionFolder.SaveLibraryOptions(virtualFolderPath, options);
@ -2940,7 +2935,7 @@ namespace Emby.Server.Implementations.Library
// // We can't validate protocol-based paths, so just allow them // // We can't validate protocol-based paths, so just allow them
// if (path.IndexOf("://", StringComparison.OrdinalIgnoreCase) == -1) // if (path.IndexOf("://", StringComparison.OrdinalIgnoreCase) == -1)
// { // {
// return _fileSystem.DirectoryExists(path); // return Directory.Exists(path);
// } // }
//} //}
@ -2968,7 +2963,7 @@ namespace Emby.Server.Implementations.Library
throw new ArgumentNullException(nameof(path)); throw new ArgumentNullException(nameof(path));
} }
if (!_fileSystem.DirectoryExists(path)) if (!Directory.Exists(path))
{ {
throw new FileNotFoundException("The path does not exist."); throw new FileNotFoundException("The path does not exist.");
} }
@ -2981,11 +2976,11 @@ namespace Emby.Server.Implementations.Library
var rootFolderPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath; var rootFolderPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath;
var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName); var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
var shortcutFilename = _fileSystem.GetFileNameWithoutExtension(path); var shortcutFilename = Path.GetFileNameWithoutExtension(path);
var lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension); var lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
while (_fileSystem.FileExists(lnk)) while (File.Exists(lnk))
{ {
shortcutFilename += "1"; shortcutFilename += "1";
lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension); lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
@ -3078,7 +3073,7 @@ namespace Emby.Server.Implementations.Library
var path = Path.Combine(rootFolderPath, name); var path = Path.Combine(rootFolderPath, name);
if (!_fileSystem.DirectoryExists(path)) if (!Directory.Exists(path))
{ {
throw new FileNotFoundException("The media folder does not exist"); throw new FileNotFoundException("The media folder does not exist");
} }
@ -3087,7 +3082,7 @@ namespace Emby.Server.Implementations.Library
try try
{ {
_fileSystem.DeleteDirectory(path, true); Directory.Delete(path, true);
} }
finally finally
{ {
@ -3150,7 +3145,7 @@ namespace Emby.Server.Implementations.Library
var rootFolderPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath; var rootFolderPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath;
var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName); var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
if (!_fileSystem.DirectoryExists(virtualFolderPath)) if (!Directory.Exists(virtualFolderPath))
{ {
throw new FileNotFoundException(string.Format("The media collection {0} does not exist", virtualFolderName)); throw new FileNotFoundException(string.Format("The media collection {0} does not exist", virtualFolderName));
} }

View file

@ -670,7 +670,7 @@ namespace Emby.Server.Implementations.Library
if (cacheFilePath != null) if (cacheFilePath != null)
{ {
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(cacheFilePath)); Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath));
_jsonSerializer.SerializeToFile(mediaInfo, cacheFilePath); _jsonSerializer.SerializeToFile(mediaInfo, cacheFilePath);
//_logger.LogDebug("Saved media info to {0}", cacheFilePath); //_logger.LogDebug("Saved media info to {0}", cacheFilePath);

View file

@ -43,7 +43,7 @@ namespace Emby.Server.Implementations.Library.Resolvers
var filename = Path.GetFileNameWithoutExtension(args.Path); var filename = Path.GetFileNameWithoutExtension(args.Path);
// Make sure the image doesn't belong to a video file // Make sure the image doesn't belong to a video file
var files = args.DirectoryService.GetFiles(_fileSystem.GetDirectoryName(args.Path)); var files = args.DirectoryService.GetFiles(Path.GetDirectoryName(args.Path));
var libraryOptions = args.GetLibraryOptions(); var libraryOptions = args.GetLibraryOptions();
foreach (var file in files) foreach (var file in files)

View file

@ -904,7 +904,7 @@ namespace Emby.Server.Implementations.Library
// Tuesday, 22 August 2006 06:30 AM // Tuesday, 22 August 2006 06:30 AM
text.AppendLine("The pin code will expire at " + localExpirationTime.ToString("f1", CultureInfo.CurrentCulture)); text.AppendLine("The pin code will expire at " + localExpirationTime.ToString("f1", CultureInfo.CurrentCulture));
_fileSystem.WriteAllText(path, text.ToString(), Encoding.UTF8); File.WriteAllText(path, text.ToString(), Encoding.UTF8);
var result = new PasswordPinCreationResult var result = new PasswordPinCreationResult
{ {
@ -1029,6 +1029,11 @@ namespace Emby.Server.Implementations.Library
{ {
var path = GetPolicyFilePath(user); var path = GetPolicyFilePath(user);
if (!File.Exists(path))
{
return GetDefaultPolicy(user);
}
try try
{ {
lock (_policySyncLock) lock (_policySyncLock)
@ -1036,10 +1041,6 @@ namespace Emby.Server.Implementations.Library
return (UserPolicy)_xmlSerializer.DeserializeFromFile(typeof(UserPolicy), path); return (UserPolicy)_xmlSerializer.DeserializeFromFile(typeof(UserPolicy), path);
} }
} }
catch (FileNotFoundException)
{
return GetDefaultPolicy(user);
}
catch (IOException) catch (IOException)
{ {
return GetDefaultPolicy(user); return GetDefaultPolicy(user);
@ -1079,7 +1080,7 @@ namespace Emby.Server.Implementations.Library
var path = GetPolicyFilePath(user); var path = GetPolicyFilePath(user);
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path)); Directory.CreateDirectory(Path.GetDirectoryName(path));
lock (_policySyncLock) lock (_policySyncLock)
{ {
@ -1128,6 +1129,11 @@ namespace Emby.Server.Implementations.Library
{ {
var path = GetConfigurationFilePath(user); var path = GetConfigurationFilePath(user);
if (!File.Exists(path))
{
return new UserConfiguration();
}
try try
{ {
lock (_configSyncLock) lock (_configSyncLock)
@ -1135,10 +1141,6 @@ namespace Emby.Server.Implementations.Library
return (UserConfiguration)_xmlSerializer.DeserializeFromFile(typeof(UserConfiguration), path); return (UserConfiguration)_xmlSerializer.DeserializeFromFile(typeof(UserConfiguration), path);
} }
} }
catch (FileNotFoundException)
{
return new UserConfiguration();
}
catch (IOException) catch (IOException)
{ {
return new UserConfiguration(); return new UserConfiguration();
@ -1174,7 +1176,7 @@ namespace Emby.Server.Implementations.Library
config = _jsonSerializer.DeserializeFromString<UserConfiguration>(json); config = _jsonSerializer.DeserializeFromString<UserConfiguration>(json);
} }
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path)); Directory.CreateDirectory(Path.GetDirectoryName(path));
lock (_configSyncLock) lock (_configSyncLock)
{ {

View file

@ -1,4 +1,5 @@
using System; using System;
using System.IO;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using MediaBrowser.Common.Net; using MediaBrowser.Common.Net;
@ -41,7 +42,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
private async Task RecordFromDirectStreamProvider(IDirectStreamProvider directStreamProvider, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken) private async Task RecordFromDirectStreamProvider(IDirectStreamProvider directStreamProvider, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
{ {
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(targetFile)); Directory.CreateDirectory(Path.GetDirectoryName(targetFile));
using (var output = _fileSystem.GetFileStream(targetFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read)) using (var output = _fileSystem.GetFileStream(targetFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
{ {
@ -77,7 +78,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{ {
_logger.LogInformation("Opened recording stream from tuner provider"); _logger.LogInformation("Opened recording stream from tuner provider");
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(targetFile)); Directory.CreateDirectory(Path.GetDirectoryName(targetFile));
using (var output = _fileSystem.GetFileStream(targetFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read)) using (var output = _fileSystem.GetFileStream(targetFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
{ {

View file

@ -1427,7 +1427,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
timer.RetryCount++; timer.RetryCount++;
_timerProvider.AddOrUpdate(timer); _timerProvider.AddOrUpdate(timer);
} }
else if (_fileSystem.FileExists(recordPath)) else if (File.Exists(recordPath))
{ {
timer.RecordingPath = recordPath; timer.RecordingPath = recordPath;
timer.Status = RecordingStatus.Completed; timer.Status = RecordingStatus.Completed;
@ -1489,7 +1489,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{ {
_logger.LogInformation("Triggering refresh on {path}", path); _logger.LogInformation("Triggering refresh on {path}", path);
var item = GetAffectedBaseItem(_fileSystem.GetDirectoryName(path)); var item = GetAffectedBaseItem(Path.GetDirectoryName(path));
if (item != null) if (item != null)
{ {
@ -1500,8 +1500,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
RefreshPaths = new string[] RefreshPaths = new string[]
{ {
path, path,
_fileSystem.GetDirectoryName(path), Path.GetDirectoryName(path),
_fileSystem.GetDirectoryName(_fileSystem.GetDirectoryName(path)) Path.GetDirectoryName(Path.GetDirectoryName(path))
} }
}, RefreshPriority.High); }, RefreshPriority.High);
@ -1512,13 +1512,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{ {
BaseItem item = null; BaseItem item = null;
var parentPath = _fileSystem.GetDirectoryName(path); var parentPath = Path.GetDirectoryName(path);
while (item == null && !string.IsNullOrEmpty(path)) while (item == null && !string.IsNullOrEmpty(path))
{ {
item = _libraryManager.FindByPath(path, null); item = _libraryManager.FindByPath(path, null);
path = _fileSystem.GetDirectoryName(path); path = Path.GetDirectoryName(path);
} }
if (item != null) if (item != null)
@ -1573,7 +1573,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
.Where(i => i.Status == RecordingStatus.Completed && !string.IsNullOrWhiteSpace(i.RecordingPath)) .Where(i => i.Status == RecordingStatus.Completed && !string.IsNullOrWhiteSpace(i.RecordingPath))
.Where(i => string.Equals(i.SeriesTimerId, seriesTimerId, StringComparison.OrdinalIgnoreCase)) .Where(i => string.Equals(i.SeriesTimerId, seriesTimerId, StringComparison.OrdinalIgnoreCase))
.OrderByDescending(i => i.EndDate) .OrderByDescending(i => i.EndDate)
.Where(i => _fileSystem.FileExists(i.RecordingPath)) .Where(i => File.Exists(i.RecordingPath))
.Skip(seriesTimer.KeepUpTo - 1) .Skip(seriesTimer.KeepUpTo - 1)
.ToList(); .ToList();
@ -1595,7 +1595,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
DtoOptions = new DtoOptions(true) DtoOptions = new DtoOptions(true)
})) }))
.Where(i => i.IsFileProtocol && _fileSystem.FileExists(i.Path)) .Where(i => i.IsFileProtocol && File.Exists(i.Path))
.Skip(seriesTimer.KeepUpTo - 1) .Skip(seriesTimer.KeepUpTo - 1)
.ToList(); .ToList();
@ -1676,7 +1676,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
while (FileExists(path, timerId)) while (FileExists(path, timerId))
{ {
var parent = _fileSystem.GetDirectoryName(originalPath); var parent = Path.GetDirectoryName(originalPath);
var name = Path.GetFileNameWithoutExtension(originalPath); var name = Path.GetFileNameWithoutExtension(originalPath);
name += " - " + index.ToString(CultureInfo.InvariantCulture); name += " - " + index.ToString(CultureInfo.InvariantCulture);
@ -1689,7 +1689,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
private bool FileExists(string path, string timerId) private bool FileExists(string path, string timerId)
{ {
if (_fileSystem.FileExists(path)) if (File.Exists(path))
{ {
return true; return true;
} }
@ -1822,12 +1822,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
return; return;
} }
var imageSavePath = Path.Combine(_fileSystem.GetDirectoryName(recordingPath), imageSaveFilenameWithoutExtension); var imageSavePath = Path.Combine(Path.GetDirectoryName(recordingPath), imageSaveFilenameWithoutExtension);
// preserve original image extension // preserve original image extension
imageSavePath = Path.ChangeExtension(imageSavePath, Path.GetExtension(image.Path)); imageSavePath = Path.ChangeExtension(imageSavePath, Path.GetExtension(image.Path));
_fileSystem.CopyFile(image.Path, imageSavePath, true); File.Copy(image.Path, imageSavePath, true);
} }
private async Task SaveRecordingImages(string recordingPath, LiveTvProgram program) private async Task SaveRecordingImages(string recordingPath, LiveTvProgram program)
@ -1961,7 +1961,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{ {
var nfoPath = Path.Combine(seriesPath, "tvshow.nfo"); var nfoPath = Path.Combine(seriesPath, "tvshow.nfo");
if (_fileSystem.FileExists(nfoPath)) if (File.Exists(nfoPath))
{ {
return; return;
} }
@ -2023,7 +2023,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{ {
var nfoPath = Path.ChangeExtension(recordingPath, ".nfo"); var nfoPath = Path.ChangeExtension(recordingPath, ".nfo");
if (_fileSystem.FileExists(nfoPath)) if (File.Exists(nfoPath))
{ {
return; return;
} }
@ -2688,7 +2688,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
var defaultFolder = RecordingPath; var defaultFolder = RecordingPath;
var defaultName = "Recordings"; var defaultName = "Recordings";
if (_fileSystem.DirectoryExists(defaultFolder)) if (Directory.Exists(defaultFolder))
{ {
list.Add(new VirtualFolderInfo list.Add(new VirtualFolderInfo
{ {
@ -2698,7 +2698,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
} }
var customPath = GetConfiguration().MovieRecordingPath; var customPath = GetConfiguration().MovieRecordingPath;
if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && _fileSystem.DirectoryExists(customPath)) if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && Directory.Exists(customPath))
{ {
list.Add(new VirtualFolderInfo list.Add(new VirtualFolderInfo
{ {
@ -2709,7 +2709,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
} }
customPath = GetConfiguration().SeriesRecordingPath; customPath = GetConfiguration().SeriesRecordingPath;
if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && _fileSystem.DirectoryExists(customPath)) if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && Directory.Exists(customPath))
{ {
list.Add(new VirtualFolderInfo list.Add(new VirtualFolderInfo
{ {

View file

@ -79,7 +79,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
private Task RecordFromFile(MediaSourceInfo mediaSource, string inputFile, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken) private Task RecordFromFile(MediaSourceInfo mediaSource, string inputFile, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
{ {
_targetPath = targetFile; _targetPath = targetFile;
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(targetFile)); Directory.CreateDirectory(Path.GetDirectoryName(targetFile));
var process = _processFactory.Create(new ProcessOptions var process = _processFactory.Create(new ProcessOptions
{ {
@ -105,7 +105,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
_logger.LogInformation(commandLineLogMessage); _logger.LogInformation(commandLineLogMessage);
var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "record-transcode-" + Guid.NewGuid() + ".txt"); var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "record-transcode-" + Guid.NewGuid() + ".txt");
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(logFilePath)); Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
// FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
_logFileStream = _fileSystem.GetFileStream(logFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true); _logFileStream = _fileSystem.GetFileStream(logFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true);

View file

@ -70,7 +70,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
} }
var file = _dataPath + ".json"; var file = _dataPath + ".json";
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(file)); Directory.CreateDirectory(Path.GetDirectoryName(file));
lock (_fileDataLock) lock (_fileDataLock)
{ {

View file

@ -61,7 +61,7 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings
string cacheFilename = DateTime.UtcNow.DayOfYear.ToString(CultureInfo.InvariantCulture) + "-" + DateTime.UtcNow.Hour.ToString(CultureInfo.InvariantCulture) + ".xml"; string cacheFilename = DateTime.UtcNow.DayOfYear.ToString(CultureInfo.InvariantCulture) + "-" + DateTime.UtcNow.Hour.ToString(CultureInfo.InvariantCulture) + ".xml";
string cacheFile = Path.Combine(_config.ApplicationPaths.CachePath, "xmltv", cacheFilename); string cacheFile = Path.Combine(_config.ApplicationPaths.CachePath, "xmltv", cacheFilename);
if (_fileSystem.FileExists(cacheFile)) if (File.Exists(cacheFile))
{ {
return UnzipIfNeeded(path, cacheFile); return UnzipIfNeeded(path, cacheFile);
} }
@ -83,9 +83,9 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings
}).ConfigureAwait(false); }).ConfigureAwait(false);
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(cacheFile)); Directory.CreateDirectory(Path.GetDirectoryName(cacheFile));
_fileSystem.CopyFile(tempFile, cacheFile, true); File.Copy(tempFile, cacheFile, true);
return UnzipIfNeeded(path, cacheFile); return UnzipIfNeeded(path, cacheFile);
} }
@ -122,10 +122,10 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings
private string ExtractFirstFileFromGz(string file) private string ExtractFirstFileFromGz(string file)
{ {
using (var stream = _fileSystem.OpenRead(file)) using (var stream = File.OpenRead(file))
{ {
string tempFolder = Path.Combine(_config.ApplicationPaths.TempDirectory, Guid.NewGuid().ToString()); string tempFolder = Path.Combine(_config.ApplicationPaths.TempDirectory, Guid.NewGuid().ToString());
_fileSystem.CreateDirectory(tempFolder); Directory.CreateDirectory(tempFolder);
_zipClient.ExtractFirstFileFromGz(stream, tempFolder, "data.xml"); _zipClient.ExtractFirstFileFromGz(stream, tempFolder, "data.xml");
@ -135,10 +135,10 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings
private string ExtractGz(string file) private string ExtractGz(string file)
{ {
using (var stream = _fileSystem.OpenRead(file)) using (var stream = File.OpenRead(file))
{ {
string tempFolder = Path.Combine(_config.ApplicationPaths.TempDirectory, Guid.NewGuid().ToString()); string tempFolder = Path.Combine(_config.ApplicationPaths.TempDirectory, Guid.NewGuid().ToString());
_fileSystem.CreateDirectory(tempFolder); Directory.CreateDirectory(tempFolder);
_zipClient.ExtractAllFromGz(stream, tempFolder, true); _zipClient.ExtractAllFromGz(stream, tempFolder, true);
@ -255,7 +255,7 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings
public Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings) public Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings)
{ {
// Assume all urls are valid. check files for existence // Assume all urls are valid. check files for existence
if (!info.Path.StartsWith("http", StringComparison.OrdinalIgnoreCase) && !_fileSystem.FileExists(info.Path)) if (!info.Path.StartsWith("http", StringComparison.OrdinalIgnoreCase) && !File.Exists(info.Path))
{ {
throw new FileNotFoundException("Could not find the XmlTv file specified:", info.Path); throw new FileNotFoundException("Could not find the XmlTv file specified:", info.Path);
} }

View file

@ -95,7 +95,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
{ {
try try
{ {
FileSystem.CreateDirectory(FileSystem.GetDirectoryName(channelCacheFile)); Directory.CreateDirectory(Path.GetDirectoryName(channelCacheFile));
JsonSerializer.SerializeToFile(channels, channelCacheFile); JsonSerializer.SerializeToFile(channels, channelCacheFile);
} }
catch (IOException) catch (IOException)

View file

@ -53,7 +53,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
var uri = new Uri(mediaSource.Path); var uri = new Uri(mediaSource.Path);
var localPort = _networkManager.GetRandomUnusedUdpPort(); var localPort = _networkManager.GetRandomUnusedUdpPort();
FileSystem.CreateDirectory(FileSystem.GetDirectoryName(TempFilePath)); Directory.CreateDirectory(Path.GetDirectoryName(TempFilePath));
Logger.LogInformation("Opening HDHR UDP Live stream from {host}", uri.Host); Logger.LogInformation("Opening HDHR UDP Live stream from {host}", uri.Host);

View file

@ -61,7 +61,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
UserAgent = _appHost.ApplicationUserAgent UserAgent = _appHost.ApplicationUserAgent
}); });
} }
return Task.FromResult(_fileSystem.OpenRead(url)); return Task.FromResult((Stream)File.OpenRead(url));
} }
const string ExtInfPrefix = "#EXTINF:"; const string ExtInfPrefix = "#EXTINF:";

View file

@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using MediaBrowser.Common.Net; using MediaBrowser.Common.Net;
@ -35,7 +36,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
var url = mediaSource.Path; var url = mediaSource.Path;
FileSystem.CreateDirectory(FileSystem.GetDirectoryName(TempFilePath)); Directory.CreateDirectory(Path.GetDirectoryName(TempFilePath));
var typeName = GetType().Name; var typeName = GetType().Name;
Logger.LogInformation("Opening " + typeName + " Live stream from {0}", url); Logger.LogInformation("Opening " + typeName + " Live stream from {0}", url);

View file

@ -62,7 +62,7 @@ namespace Emby.Server.Implementations.Localization
{ {
const string ratingsResource = "Emby.Server.Implementations.Ratings."; const string ratingsResource = "Emby.Server.Implementations.Ratings.";
Directory.CreateDirectory(LocalizationPath); Directory.CreateDirectory(localizationPath);
var existingFiles = GetRatingsFiles(LocalizationPath).Select(Path.GetFileName); var existingFiles = GetRatingsFiles(LocalizationPath).Select(Path.GetFileName);
@ -292,6 +292,7 @@ namespace Emby.Server.Implementations.Localization
private async Task LoadRatings(string file) private async Task LoadRatings(string file)
{ {
Dictionary<string, ParentalRating> dict = new Dictionary<string, ParentalRating>(StringComparer.OrdinalIgnoreCase); Dictionary<string, ParentalRating> dict = new Dictionary<string, ParentalRating>(StringComparer.OrdinalIgnoreCase);
using (var str = File.OpenRead(file)) using (var str = File.OpenRead(file))
using (var reader = new StreamReader(str)) using (var reader = new StreamReader(str))
{ {

View file

@ -141,12 +141,12 @@ namespace Emby.Server.Implementations.MediaEncoder
var inputPath = MediaEncoderHelpers.GetInputArgument(_fileSystem, video.Path, protocol, null, Array.Empty<string>()); var inputPath = MediaEncoderHelpers.GetInputArgument(_fileSystem, video.Path, protocol, null, Array.Empty<string>());
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path)); Directory.CreateDirectory(Path.GetDirectoryName(path));
var container = video.Container; var container = video.Container;
var tempFile = await _encoder.ExtractVideoImage(inputPath, container, protocol, video.GetDefaultVideoStream(), video.Video3DFormat, time, cancellationToken).ConfigureAwait(false); var tempFile = await _encoder.ExtractVideoImage(inputPath, container, protocol, video.GetDefaultVideoStream(), video.Video3DFormat, time, cancellationToken).ConfigureAwait(false);
_fileSystem.CopyFile(tempFile, path, true); File.Copy(tempFile, path, true);
try try
{ {

View file

@ -119,7 +119,7 @@ namespace Emby.Server.Implementations.Playlists
try try
{ {
_fileSystem.CreateDirectory(path); Directory.CreateDirectory(path);
var playlist = new Playlist var playlist = new Playlist
{ {
@ -164,7 +164,7 @@ namespace Emby.Server.Implementations.Playlists
private string GetTargetPath(string path) private string GetTargetPath(string path)
{ {
while (_fileSystem.DirectoryExists(path)) while (Directory.Exists(path))
{ {
path += "1"; path += "1";
} }
@ -340,7 +340,8 @@ namespace Emby.Server.Implementations.Playlists
playlist.PlaylistEntries.Add(entry); playlist.PlaylistEntries.Add(entry);
} }
_fileSystem.WriteAllText(playlistPath, new WplContent().ToText(playlist)); string text = new WplContent().ToText(playlist);
File.WriteAllText(playlistPath, text);
} }
if (string.Equals(".zpl", extension, StringComparison.OrdinalIgnoreCase)) if (string.Equals(".zpl", extension, StringComparison.OrdinalIgnoreCase))
{ {
@ -373,7 +374,8 @@ namespace Emby.Server.Implementations.Playlists
playlist.PlaylistEntries.Add(entry); playlist.PlaylistEntries.Add(entry);
} }
_fileSystem.WriteAllText(playlistPath, new ZplContent().ToText(playlist)); string text = new ZplContent().ToText(playlist);
File.WriteAllText(playlistPath, text);
} }
if (string.Equals(".m3u", extension, StringComparison.OrdinalIgnoreCase)) if (string.Equals(".m3u", extension, StringComparison.OrdinalIgnoreCase))
{ {
@ -401,7 +403,8 @@ namespace Emby.Server.Implementations.Playlists
playlist.PlaylistEntries.Add(entry); playlist.PlaylistEntries.Add(entry);
} }
_fileSystem.WriteAllText(playlistPath, new M3uContent().ToText(playlist)); string text = new M3uContent().ToText(playlist);
File.WriteAllText(playlistPath, text);
} }
if (string.Equals(".m3u8", extension, StringComparison.OrdinalIgnoreCase)) if (string.Equals(".m3u8", extension, StringComparison.OrdinalIgnoreCase))
{ {
@ -429,7 +432,8 @@ namespace Emby.Server.Implementations.Playlists
playlist.PlaylistEntries.Add(entry); playlist.PlaylistEntries.Add(entry);
} }
_fileSystem.WriteAllText(playlistPath, new M3u8Content().ToText(playlist)); string text = new M3u8Content().ToText(playlist);
File.WriteAllText(playlistPath, text);
} }
if (string.Equals(".pls", extension, StringComparison.OrdinalIgnoreCase)) if (string.Equals(".pls", extension, StringComparison.OrdinalIgnoreCase))
{ {
@ -449,13 +453,14 @@ namespace Emby.Server.Implementations.Playlists
playlist.PlaylistEntries.Add(entry); playlist.PlaylistEntries.Add(entry);
} }
_fileSystem.WriteAllText(playlistPath, new PlsContent().ToText(playlist)); string text = new PlsContent().ToText(playlist);
File.WriteAllText(playlistPath, text);
} }
} }
private string NormalizeItemPath(string playlistPath, string itemPath) private string NormalizeItemPath(string playlistPath, string itemPath)
{ {
return MakeRelativePath(_fileSystem.GetDirectoryName(playlistPath), itemPath); return MakeRelativePath(Path.GetDirectoryName(playlistPath), itemPath);
} }
private static string MakeRelativePath(string folderPath, string fileAbsolutePath) private static string MakeRelativePath(string folderPath, string fileAbsolutePath)

View file

@ -37,16 +37,16 @@ namespace Emby.Server.Implementations
public string ReadAllText(string basePath, string virtualPath) public string ReadAllText(string basePath, string virtualPath)
{ {
return _fileSystem.ReadAllText(GetResourcePath(basePath, virtualPath)); return File.ReadAllText(GetResourcePath(basePath, virtualPath));
} }
private string GetResourcePath(string basePath, string virtualPath) private string GetResourcePath(string basePath, string virtualPath)
{ {
var fullPath = Path.Combine(basePath, virtualPath.Replace('/', _fileSystem.DirectorySeparatorChar)); var fullPath = Path.Combine(basePath, virtualPath.Replace('/', Path.DirectorySeparatorChar));
try try
{ {
fullPath = _fileSystem.GetFullPath(fullPath); fullPath = Path.GetFullPath(fullPath);
} }
catch (Exception ex) catch (Exception ex)
{ {

View file

@ -101,17 +101,20 @@ namespace Emby.Server.Implementations.ScheduledTasks
List<string> previouslyFailedImages; List<string> previouslyFailedImages;
try if (File.Exists(failHistoryPath))
{ {
previouslyFailedImages = _fileSystem.ReadAllText(failHistoryPath) try
.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries) {
.ToList(); previouslyFailedImages = File.ReadAllText(failHistoryPath)
.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)
.ToList();
}
catch (IOException)
{
previouslyFailedImages = new List<string>();
}
} }
catch (FileNotFoundException) else
{
previouslyFailedImages = new List<string>();
}
catch (IOException)
{ {
previouslyFailedImages = new List<string>(); previouslyFailedImages = new List<string>();
} }
@ -136,11 +139,12 @@ namespace Emby.Server.Implementations.ScheduledTasks
{ {
previouslyFailedImages.Add(key); previouslyFailedImages.Add(key);
var parentPath = _fileSystem.GetDirectoryName(failHistoryPath); var parentPath = Path.GetDirectoryName(failHistoryPath);
_fileSystem.CreateDirectory(parentPath); Directory.CreateDirectory(parentPath);
_fileSystem.WriteAllText(failHistoryPath, string.Join("|", previouslyFailedImages.ToArray())); string text = string.Join("|", previouslyFailedImages);
File.WriteAllText(failHistoryPath, text);
} }
numComplete++; numComplete++;

View file

@ -129,21 +129,16 @@ namespace Emby.Server.Implementations.ScheduledTasks
{ {
if (_lastExecutionResult == null && !_readFromFile) if (_lastExecutionResult == null && !_readFromFile)
{ {
try if (File.Exists(path))
{ {
_lastExecutionResult = JsonSerializer.DeserializeFromFile<TaskResult>(path); try
} {
catch (DirectoryNotFoundException) _lastExecutionResult = JsonSerializer.DeserializeFromFile<TaskResult>(path);
{ }
// File doesn't exist. No biggie catch (Exception ex)
} {
catch (FileNotFoundException) Logger.LogError(ex, "Error deserializing {File}", path);
{ }
// File doesn't exist. No biggie
}
catch (Exception ex)
{
Logger.LogError(ex, "Error deserializing {path}", path);
} }
_readFromFile = true; _readFromFile = true;
} }
@ -156,7 +151,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
_lastExecutionResult = value; _lastExecutionResult = value;
var path = GetHistoryFilePath(); var path = GetHistoryFilePath();
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path)); Directory.CreateDirectory(Path.GetDirectoryName(path));
lock (_lastExecutionResultSyncLock) lock (_lastExecutionResultSyncLock)
{ {
@ -532,28 +527,15 @@ namespace Emby.Server.Implementations.ScheduledTasks
private TaskTriggerInfo[] LoadTriggerSettings() private TaskTriggerInfo[] LoadTriggerSettings()
{ {
try string path = GetConfigurationFilePath();
TaskTriggerInfo[] list = null;
if (File.Exists(path))
{ {
var list = JsonSerializer.DeserializeFromFile<IEnumerable<TaskTriggerInfo>>(GetConfigurationFilePath()); list = JsonSerializer.DeserializeFromFile<TaskTriggerInfo[]>(path);
}
if (list != null) // Return defaults if file doesn't exist.
{ return list ?? GetDefaultTriggers();
return list.ToArray();
}
}
catch (FileNotFoundException)
{
// File doesn't exist. No biggie. Return defaults.
}
catch (DirectoryNotFoundException)
{
// File doesn't exist. No biggie. Return defaults.
}
catch
{
}
return GetDefaultTriggers();
} }
private TaskTriggerInfo[] GetDefaultTriggers() private TaskTriggerInfo[] GetDefaultTriggers()
@ -583,7 +565,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
{ {
var path = GetConfigurationFilePath(); var path = GetConfigurationFilePath();
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path)); Directory.CreateDirectory(Path.GetDirectoryName(path));
JsonSerializer.SerializeToFile(triggers, path); JsonSerializer.SerializeToFile(triggers, path);
} }

View file

@ -86,7 +86,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
try try
{ {
lines = _fileSystem.ReadAllLines(path).Where(i => !string.IsNullOrWhiteSpace(i)).Distinct(StringComparer.OrdinalIgnoreCase).ToList(); lines = File.ReadAllLines(path).Where(i => !string.IsNullOrWhiteSpace(i)).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
foreach (var key in lines) foreach (var key in lines)
{ {

View file

@ -128,7 +128,7 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks
{ {
try try
{ {
_fileSystem.DeleteDirectory(directory, false); Directory.Delete(directory, false);
} }
catch (UnauthorizedAccessException ex) catch (UnauthorizedAccessException ex)
{ {

View file

@ -107,7 +107,7 @@ namespace Emby.Server.Implementations.Serialization
public object DeserializeFromFile(Type type, string file) public object DeserializeFromFile(Type type, string file)
{ {
_logger.LogDebug("Deserializing file {0}", file); _logger.LogDebug("Deserializing file {0}", file);
using (var stream = _fileSystem.OpenRead(file)) using (var stream = File.OpenRead(file))
{ {
return DeserializeFromStream(type, stream); return DeserializeFromStream(type, stream);
} }

View file

@ -555,7 +555,7 @@ namespace Emby.Server.Implementations.Updates
var packageChecksum = string.IsNullOrWhiteSpace(package.checksum) ? Guid.Empty : new Guid(package.checksum); var packageChecksum = string.IsNullOrWhiteSpace(package.checksum) ? Guid.Empty : new Guid(package.checksum);
if (!packageChecksum.Equals(Guid.Empty)) // support for legacy uploads for now if (!packageChecksum.Equals(Guid.Empty)) // support for legacy uploads for now
{ {
using (var stream = _fileSystem.OpenRead(tempFile)) using (var stream = File.OpenRead(tempFile))
{ {
var check = Guid.Parse(BitConverter.ToString(_cryptographyProvider.ComputeMD5(stream)).Replace("-", string.Empty)); var check = Guid.Parse(BitConverter.ToString(_cryptographyProvider.ComputeMD5(stream)).Replace("-", string.Empty));
if (check != packageChecksum) if (check != packageChecksum)
@ -570,12 +570,12 @@ namespace Emby.Server.Implementations.Updates
// Success - move it to the real target // Success - move it to the real target
try try
{ {
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(target)); Directory.CreateDirectory(Path.GetDirectoryName(target));
_fileSystem.CopyFile(tempFile, target, true); File.Copy(tempFile, target, true);
//If it is an archive - write out a version file so we know what it is //If it is an archive - write out a version file so we know what it is
if (isArchive) if (isArchive)
{ {
_fileSystem.WriteAllText(target + ".ver", package.versionStr); File.WriteAllText(target + ".ver", package.versionStr);
} }
} }
catch (IOException ex) catch (IOException ex)
@ -611,7 +611,7 @@ namespace Emby.Server.Implementations.Updates
_logger.LogInformation("Deleting plugin file {0}", path); _logger.LogInformation("Deleting plugin file {0}", path);
// Make this case-insensitive to account for possible incorrect assembly naming // Make this case-insensitive to account for possible incorrect assembly naming
var file = _fileSystem.GetFilePaths(_fileSystem.GetDirectoryName(path)) var file = _fileSystem.GetFilePaths(Path.GetDirectoryName(path))
.FirstOrDefault(i => string.Equals(i, path, StringComparison.OrdinalIgnoreCase)); .FirstOrDefault(i => string.Equals(i, path, StringComparison.OrdinalIgnoreCase));
if (!string.IsNullOrWhiteSpace(file)) if (!string.IsNullOrWhiteSpace(file))

View file

@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\SharedVersion.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="SkiaSharp" Version="1.68.0" />
<PackageReference Include="SkiaSharp.NativeAssets.Linux" Version="1.68.0" />
<PackageReference Include="Jellyfin.SkiaSharp.NativeAssets.LinuxArm" Version="1.68.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj" />
<ProjectReference Include="..\MediaBrowser.Controller\MediaBrowser.Controller.csproj" />
<ProjectReference Include="..\MediaBrowser.Common\MediaBrowser.Common.csproj" />
</ItemGroup>
</Project>

View file

@ -2,7 +2,7 @@ using System;
using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Drawing;
using SkiaSharp; using SkiaSharp;
namespace Emby.Drawing namespace Jellyfin.Drawing.Skia
{ {
public static class PercentPlayedDrawer public static class PercentPlayedDrawer
{ {

View file

@ -1,7 +1,7 @@
using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Drawing;
using SkiaSharp; using SkiaSharp;
namespace Emby.Drawing namespace Jellyfin.Drawing.Skia
{ {
public static class PlayedIndicatorDrawer public static class PlayedIndicatorDrawer
{ {

View file

@ -0,0 +1,21 @@
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Jellyfin.Drawing.Skia")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jellyfin Project")]
[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

View file

@ -12,7 +12,7 @@ using MediaBrowser.Model.IO;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using SkiaSharp; using SkiaSharp;
namespace Emby.Drawing namespace Jellyfin.Drawing.Skia
{ {
public class SkiaEncoder : IImageEncoder public class SkiaEncoder : IImageEncoder
{ {
@ -72,16 +72,11 @@ namespace Emby.Drawing
_logger.LogInformation("SkiaSharp version: " + GetVersion()); _logger.LogInformation("SkiaSharp version: " + GetVersion());
} }
public static string GetVersion() public static Version GetVersion()
{ => typeof(SKBitmap).GetTypeInfo().Assembly.GetName().Version;
return typeof(SKBitmap).GetTypeInfo().Assembly.GetName().Version.ToString();
}
private static bool IsTransparent(SKColor color) private static bool IsTransparent(SKColor color)
{ => (color.Red == 255 && color.Green == 255 && color.Blue == 255) || color.Alpha == 0;
return (color.Red == 255 && color.Green == 255 && color.Blue == 255) || color.Alpha == 0;
}
public static SKEncodedImageFormat GetImageFormat(ImageFormat selectedFormat) public static SKEncodedImageFormat GetImageFormat(ImageFormat selectedFormat)
{ {
@ -130,33 +125,51 @@ namespace Emby.Drawing
for (int row = 0; row < bitmap.Height; ++row) for (int row = 0; row < bitmap.Height; ++row)
{ {
if (IsTransparentRow(bitmap, row)) if (IsTransparentRow(bitmap, row))
{
topmost = row + 1; topmost = row + 1;
else break; }
else
{
break;
}
} }
int bottommost = bitmap.Height; int bottommost = bitmap.Height;
for (int row = bitmap.Height - 1; row >= 0; --row) for (int row = bitmap.Height - 1; row >= 0; --row)
{ {
if (IsTransparentRow(bitmap, row)) if (IsTransparentRow(bitmap, row))
{
bottommost = row; bottommost = row;
else break; }
else
{
break;
}
} }
int leftmost = 0, rightmost = bitmap.Width; int leftmost = 0, rightmost = bitmap.Width;
for (int col = 0; col < bitmap.Width; ++col) for (int col = 0; col < bitmap.Width; ++col)
{ {
if (IsTransparentColumn(bitmap, col)) if (IsTransparentColumn(bitmap, col))
{
leftmost = col + 1; leftmost = col + 1;
}
else else
{
break; break;
}
} }
for (int col = bitmap.Width - 1; col >= 0; --col) for (int col = bitmap.Width - 1; col >= 0; --col)
{ {
if (IsTransparentColumn(bitmap, col)) if (IsTransparentColumn(bitmap, col))
{
rightmost = col; rightmost = col;
}
else else
{
break; break;
}
} }
var newRect = SKRectI.Create(leftmost, topmost, rightmost - leftmost, bottommost - topmost); var newRect = SKRectI.Create(leftmost, topmost, rightmost - leftmost, bottommost - topmost);
@ -180,9 +193,7 @@ namespace Emby.Drawing
} }
private static bool HasDiacritics(string text) private static bool HasDiacritics(string text)
{ => !string.Equals(text, text.RemoveDiacritics(), StringComparison.Ordinal);
return !string.Equals(text, text.RemoveDiacritics(), StringComparison.Ordinal);
}
private static bool RequiresSpecialCharacterHack(string path) private static bool RequiresSpecialCharacterHack(string path)
{ {
@ -208,8 +219,8 @@ namespace Emby.Drawing
var tempPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + Path.GetExtension(path) ?? string.Empty); var tempPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + Path.GetExtension(path) ?? string.Empty);
fileSystem.CreateDirectory(fileSystem.GetDirectoryName(tempPath)); Directory.CreateDirectory(Path.GetDirectoryName(tempPath));
fileSystem.CopyFile(path, tempPath, true); File.Copy(path, tempPath, true);
return tempPath; return tempPath;
} }
@ -243,9 +254,10 @@ namespace Emby.Drawing
} }
private static string[] TransparentImageTypes = new string[] { ".png", ".gif", ".webp" }; private static string[] TransparentImageTypes = new string[] { ".png", ".gif", ".webp" };
internal static SKBitmap Decode(string path, bool forceCleanBitmap, IFileSystem fileSystem, ImageOrientation? orientation, out SKEncodedOrigin origin) internal static SKBitmap Decode(string path, bool forceCleanBitmap, IFileSystem fileSystem, ImageOrientation? orientation, out SKEncodedOrigin origin)
{ {
if (!fileSystem.FileExists(path)) if (!File.Exists(path))
{ {
throw new FileNotFoundException("File not found", path); throw new FileNotFoundException("File not found", path);
} }
@ -267,7 +279,7 @@ namespace Emby.Drawing
var bitmap = new SKBitmap(codec.Info.Width, codec.Info.Height, !requiresTransparencyHack); var bitmap = new SKBitmap(codec.Info.Width, codec.Info.Height, !requiresTransparencyHack);
// decode // decode
codec.GetPixels(bitmap.Info, bitmap.GetPixels()); var _ = codec.GetPixels(bitmap.Info, bitmap.GetPixels());
origin = codec.EncodedOrigin; origin = codec.EncodedOrigin;
@ -316,14 +328,11 @@ namespace Emby.Drawing
{ {
var bitmap = GetBitmap(path, cropWhitespace, true, orientation, out origin); var bitmap = GetBitmap(path, cropWhitespace, true, orientation, out origin);
if (bitmap != null) if (bitmap != null && origin != SKEncodedOrigin.TopLeft)
{ {
if (origin != SKEncodedOrigin.TopLeft) using (bitmap)
{ {
using (bitmap) return OrientImage(bitmap, origin);
{
return OrientImage(bitmap, origin);
}
} }
} }
@ -347,7 +356,6 @@ namespace Emby.Drawing
switch (origin) switch (origin)
{ {
case SKEncodedOrigin.TopRight: case SKEncodedOrigin.TopRight:
{ {
var rotated = new SKBitmap(bitmap.Width, bitmap.Height); var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
@ -366,11 +374,8 @@ namespace Emby.Drawing
var rotated = new SKBitmap(bitmap.Width, bitmap.Height); var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
using (var surface = new SKCanvas(rotated)) using (var surface = new SKCanvas(rotated))
{ {
float px = bitmap.Width; float px = (float)bitmap.Width / 2;
px /= 2; float py = (float)bitmap.Height / 2;
float py = bitmap.Height;
py /= 2;
surface.RotateDegrees(180, px, py); surface.RotateDegrees(180, px, py);
surface.DrawBitmap(bitmap, 0, 0); surface.DrawBitmap(bitmap, 0, 0);
@ -384,11 +389,9 @@ namespace Emby.Drawing
var rotated = new SKBitmap(bitmap.Width, bitmap.Height); var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
using (var surface = new SKCanvas(rotated)) using (var surface = new SKCanvas(rotated))
{ {
float px = bitmap.Width; float px = (float)bitmap.Width / 2;
px /= 2;
float py = bitmap.Height; float py = (float)bitmap.Height / 2;
py /= 2;
surface.Translate(rotated.Width, 0); surface.Translate(rotated.Width, 0);
surface.Scale(-1, 1); surface.Scale(-1, 1);
@ -412,7 +415,6 @@ namespace Emby.Drawing
surface.RotateDegrees(90); surface.RotateDegrees(90);
surface.DrawBitmap(bitmap, 0, 0); surface.DrawBitmap(bitmap, 0, 0);
} }
var flippedBitmap = new SKBitmap(rotated.Width, rotated.Height); var flippedBitmap = new SKBitmap(rotated.Width, rotated.Height);
@ -477,8 +479,7 @@ namespace Emby.Drawing
return rotated; return rotated;
} }
default: default: return bitmap;
return bitmap;
} }
} }
@ -488,6 +489,7 @@ namespace Emby.Drawing
{ {
throw new ArgumentNullException(nameof(inputPath)); throw new ArgumentNullException(nameof(inputPath));
} }
if (string.IsNullOrWhiteSpace(inputPath)) if (string.IsNullOrWhiteSpace(inputPath))
{ {
throw new ArgumentNullException(nameof(outputPath)); throw new ArgumentNullException(nameof(outputPath));
@ -507,11 +509,11 @@ namespace Emby.Drawing
throw new ArgumentOutOfRangeException(string.Format("Skia unable to read image {0}", inputPath)); throw new ArgumentOutOfRangeException(string.Format("Skia unable to read image {0}", inputPath));
} }
//_logger.LogInformation("Color type {0}", bitmap.Info.ColorType);
var originalImageSize = new ImageDimensions(bitmap.Width, bitmap.Height); var originalImageSize = new ImageDimensions(bitmap.Width, bitmap.Height);
if (!options.CropWhiteSpace && options.HasDefaultOptions(inputPath, originalImageSize) && !autoOrient) if (!options.CropWhiteSpace
&& options.HasDefaultOptions(inputPath, originalImageSize)
&& !autoOrient)
{ {
// Just spit out the original file if all the options are default // Just spit out the original file if all the options are default
return inputPath; return inputPath;
@ -522,7 +524,7 @@ namespace Emby.Drawing
var width = newImageSize.Width; var width = newImageSize.Width;
var height = newImageSize.Height; var height = newImageSize.Height;
using (var resizedBitmap = new SKBitmap(width, height))//, bitmap.ColorType, bitmap.AlphaType)) using (var resizedBitmap = new SKBitmap(width, height, bitmap.ColorType, bitmap.AlphaType))
{ {
// scale image // scale image
bitmap.ScalePixels(resizedBitmap, SKFilterQuality.High); bitmap.ScalePixels(resizedBitmap, SKFilterQuality.High);
@ -530,14 +532,12 @@ namespace Emby.Drawing
// If all we're doing is resizing then we can stop now // If all we're doing is resizing then we can stop now
if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator) if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
{ {
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath)); Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
using (var outputStream = new SKFileWStream(outputPath)) using (var outputStream = new SKFileWStream(outputPath))
using (var pixmap = new SKPixmap(new SKImageInfo(width, height), resizedBitmap.GetPixels()))
{ {
using (var pixmap = new SKPixmap(new SKImageInfo(width, height), resizedBitmap.GetPixels())) pixmap.Encode(outputStream, skiaOutputFormat, quality);
{ return outputPath;
pixmap.Encode(outputStream, skiaOutputFormat, quality);
return outputPath;
}
} }
} }
@ -584,7 +584,7 @@ namespace Emby.Drawing
DrawIndicator(canvas, width, height, options); DrawIndicator(canvas, width, height, options);
} }
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath)); Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
using (var outputStream = new SKFileWStream(outputPath)) using (var outputStream = new SKFileWStream(outputPath))
{ {
using (var pixmap = new SKPixmap(new SKImageInfo(width, height), saveBitmap.GetPixels())) using (var pixmap = new SKPixmap(new SKImageInfo(width, height), saveBitmap.GetPixels()))
@ -600,8 +600,7 @@ namespace Emby.Drawing
public void CreateImageCollage(ImageCollageOptions options) public void CreateImageCollage(ImageCollageOptions options)
{ {
double ratio = options.Width; double ratio = (double)options.Width / options.Height;
ratio /= options.Height;
if (ratio >= 1.4) if (ratio >= 1.4)
{ {
@ -613,7 +612,7 @@ namespace Emby.Drawing
} }
else else
{ {
// @todo create Poster collage capability // TODO: Create Poster collage capability
new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height); new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
} }
} }

View file

@ -5,7 +5,7 @@ using MediaBrowser.Common.Configuration;
using MediaBrowser.Model.IO; using MediaBrowser.Model.IO;
using SkiaSharp; using SkiaSharp;
namespace Emby.Drawing namespace Jellyfin.Drawing.Skia
{ {
public class StripCollageBuilder public class StripCollageBuilder
{ {
@ -43,21 +43,14 @@ namespace Emby.Drawing
return SKEncodedImageFormat.Png; return SKEncodedImageFormat.Png;
} }
public void BuildPosterCollage(string[] paths, string outputPath, int width, int height)
{
// @todo
}
public void BuildSquareCollage(string[] paths, string outputPath, int width, int height) public void BuildSquareCollage(string[] paths, string outputPath, int width, int height)
{ {
using (var bitmap = BuildSquareCollageBitmap(paths, width, height)) using (var bitmap = BuildSquareCollageBitmap(paths, width, height))
using (var outputStream = new SKFileWStream(outputPath))
{ {
using (var outputStream = new SKFileWStream(outputPath)) using (var pixmap = new SKPixmap(new SKImageInfo(width, height), bitmap.GetPixels()))
{ {
using (var pixmap = new SKPixmap(new SKImageInfo(width, height), bitmap.GetPixels())) pixmap.Encode(outputStream, GetEncodedFormat(outputPath), 90);
{
pixmap.Encode(outputStream, GetEncodedFormat(outputPath), 90);
}
} }
} }
} }

View file

@ -2,7 +2,7 @@ using System.Globalization;
using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Drawing;
using SkiaSharp; using SkiaSharp;
namespace Emby.Drawing namespace Jellyfin.Drawing.Skia
{ {
public static class UnplayedCountIndicator public static class UnplayedCountIndicator
{ {

View file

@ -49,6 +49,7 @@
<ProjectReference Include="..\Emby.Drawing\Emby.Drawing.csproj" /> <ProjectReference Include="..\Emby.Drawing\Emby.Drawing.csproj" />
<ProjectReference Include="..\Emby.IsoMounting\IsoMounter\IsoMounter.csproj" /> <ProjectReference Include="..\Emby.IsoMounting\IsoMounter\IsoMounter.csproj" />
<ProjectReference Include="..\Emby.Server.Implementations\Emby.Server.Implementations.csproj" /> <ProjectReference Include="..\Emby.Server.Implementations\Emby.Server.Implementations.csproj" />
<ProjectReference Include="..\Jellyfin.Drawing.Skia\Jellyfin.Drawing.Skia.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View file

@ -13,6 +13,7 @@ using Emby.Server.Implementations;
using Emby.Server.Implementations.EnvironmentInfo; using Emby.Server.Implementations.EnvironmentInfo;
using Emby.Server.Implementations.IO; using Emby.Server.Implementations.IO;
using Emby.Server.Implementations.Networking; using Emby.Server.Implementations.Networking;
using Jellyfin.Drawing.Skia;
using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Drawing;
using MediaBrowser.Model.Globalization; using MediaBrowser.Model.Globalization;

View file

@ -646,7 +646,7 @@ namespace MediaBrowser.Api
/// <param name="outputFilePath">The output file path.</param> /// <param name="outputFilePath">The output file path.</param>
private void DeleteHlsPartialStreamFiles(string outputFilePath) private void DeleteHlsPartialStreamFiles(string outputFilePath)
{ {
var directory = _fileSystem.GetDirectoryName(outputFilePath); var directory = Path.GetDirectoryName(outputFilePath);
var name = Path.GetFileNameWithoutExtension(outputFilePath); var name = Path.GetFileNameWithoutExtension(outputFilePath);
var filesToDelete = _fileSystem.GetFilePaths(directory) var filesToDelete = _fileSystem.GetFilePaths(directory)

View file

@ -137,14 +137,14 @@ namespace MediaBrowser.Api
{ {
if (request.IsFile.Value) if (request.IsFile.Value)
{ {
if (!_fileSystem.FileExists(request.Path)) if (!File.Exists(request.Path))
{ {
throw new FileNotFoundException("File not found", request.Path); throw new FileNotFoundException("File not found", request.Path);
} }
} }
else else
{ {
if (!_fileSystem.DirectoryExists(request.Path)) if (!Directory.Exists(request.Path))
{ {
throw new FileNotFoundException("File not found", request.Path); throw new FileNotFoundException("File not found", request.Path);
} }
@ -153,7 +153,7 @@ namespace MediaBrowser.Api
else else
{ {
if (!_fileSystem.FileExists(request.Path) && !_fileSystem.DirectoryExists(request.Path)) if (!File.Exists(request.Path) && !Directory.Exists(request.Path))
{ {
throw new FileNotFoundException("Path not found", request.Path); throw new FileNotFoundException("Path not found", request.Path);
} }
@ -169,7 +169,7 @@ namespace MediaBrowser.Api
{ {
var file = Path.Combine(path, Guid.NewGuid().ToString()); var file = Path.Combine(path, Guid.NewGuid().ToString());
_fileSystem.WriteAllText(file, string.Empty); File.WriteAllText(file, string.Empty);
_fileSystem.DeleteFile(file); _fileSystem.DeleteFile(file);
} }
@ -303,7 +303,7 @@ namespace MediaBrowser.Api
public object Get(GetParentPath request) public object Get(GetParentPath request)
{ {
var parent = _fileSystem.GetDirectoryName(request.Path); var parent = Path.GetDirectoryName(request.Path);
if (string.IsNullOrEmpty(parent)) if (string.IsNullOrEmpty(parent))
{ {

View file

@ -158,7 +158,7 @@ namespace MediaBrowser.Api.Images
private string GetThemeName(string path, string rootImagePath) private string GetThemeName(string path, string rootImagePath)
{ {
var parentName = _fileSystem.GetDirectoryName(path); var parentName = Path.GetDirectoryName(path);
if (string.Equals(parentName, rootImagePath, StringComparison.OrdinalIgnoreCase)) if (string.Equals(parentName, rootImagePath, StringComparison.OrdinalIgnoreCase))
{ {
@ -185,7 +185,7 @@ namespace MediaBrowser.Api.Images
var paths = BaseItem.SupportedImageExtensions.Select(i => Path.Combine(_appPaths.GeneralPath, request.Name, filename + i)).ToList(); var paths = BaseItem.SupportedImageExtensions.Select(i => Path.Combine(_appPaths.GeneralPath, request.Name, filename + i)).ToList();
var path = paths.FirstOrDefault(_fileSystem.FileExists) ?? paths.FirstOrDefault(); var path = paths.FirstOrDefault(File.Exists) ?? paths.FirstOrDefault();
return _resultFactory.GetStaticFileResult(Request, path); return _resultFactory.GetStaticFileResult(Request, path);
} }
@ -199,11 +199,11 @@ namespace MediaBrowser.Api.Images
{ {
var themeFolder = Path.Combine(_appPaths.RatingsPath, request.Theme); var themeFolder = Path.Combine(_appPaths.RatingsPath, request.Theme);
if (_fileSystem.DirectoryExists(themeFolder)) if (Directory.Exists(themeFolder))
{ {
var path = BaseItem.SupportedImageExtensions var path = BaseItem.SupportedImageExtensions
.Select(i => Path.Combine(themeFolder, request.Name + i)) .Select(i => Path.Combine(themeFolder, request.Name + i))
.FirstOrDefault(_fileSystem.FileExists); .FirstOrDefault(File.Exists);
if (!string.IsNullOrEmpty(path)) if (!string.IsNullOrEmpty(path))
{ {
@ -213,14 +213,14 @@ namespace MediaBrowser.Api.Images
var allFolder = Path.Combine(_appPaths.RatingsPath, "all"); var allFolder = Path.Combine(_appPaths.RatingsPath, "all");
if (_fileSystem.DirectoryExists(allFolder)) if (Directory.Exists(allFolder))
{ {
// Avoid implicitly captured closure // Avoid implicitly captured closure
var currentRequest = request; var currentRequest = request;
var path = BaseItem.SupportedImageExtensions var path = BaseItem.SupportedImageExtensions
.Select(i => Path.Combine(allFolder, currentRequest.Name + i)) .Select(i => Path.Combine(allFolder, currentRequest.Name + i))
.FirstOrDefault(_fileSystem.FileExists); .FirstOrDefault(File.Exists);
if (!string.IsNullOrEmpty(path)) if (!string.IsNullOrEmpty(path))
{ {
@ -240,10 +240,10 @@ namespace MediaBrowser.Api.Images
{ {
var themeFolder = Path.Combine(_appPaths.MediaInfoImagesPath, request.Theme); var themeFolder = Path.Combine(_appPaths.MediaInfoImagesPath, request.Theme);
if (_fileSystem.DirectoryExists(themeFolder)) if (Directory.Exists(themeFolder))
{ {
var path = BaseItem.SupportedImageExtensions.Select(i => Path.Combine(themeFolder, request.Name + i)) var path = BaseItem.SupportedImageExtensions.Select(i => Path.Combine(themeFolder, request.Name + i))
.FirstOrDefault(_fileSystem.FileExists); .FirstOrDefault(File.Exists);
if (!string.IsNullOrEmpty(path)) if (!string.IsNullOrEmpty(path))
{ {
@ -253,13 +253,13 @@ namespace MediaBrowser.Api.Images
var allFolder = Path.Combine(_appPaths.MediaInfoImagesPath, "all"); var allFolder = Path.Combine(_appPaths.MediaInfoImagesPath, "all");
if (_fileSystem.DirectoryExists(allFolder)) if (Directory.Exists(allFolder))
{ {
// Avoid implicitly captured closure // Avoid implicitly captured closure
var currentRequest = request; var currentRequest = request;
var path = BaseItem.SupportedImageExtensions.Select(i => Path.Combine(allFolder, currentRequest.Name + i)) var path = BaseItem.SupportedImageExtensions.Select(i => Path.Combine(allFolder, currentRequest.Name + i))
.FirstOrDefault(_fileSystem.FileExists); .FirstOrDefault(File.Exists);
if (!string.IsNullOrEmpty(path)) if (!string.IsNullOrEmpty(path))
{ {

View file

@ -220,9 +220,9 @@ namespace MediaBrowser.Api.Images
try try
{ {
contentPath = _fileSystem.ReadAllText(pointerCachePath); contentPath = File.ReadAllText(pointerCachePath);
if (_fileSystem.FileExists(contentPath)) if (File.Exists(contentPath))
{ {
return await ResultFactory.GetStaticFileResult(Request, contentPath).ConfigureAwait(false); return await ResultFactory.GetStaticFileResult(Request, contentPath).ConfigureAwait(false);
} }
@ -239,7 +239,7 @@ namespace MediaBrowser.Api.Images
await DownloadImage(request.ImageUrl, urlHash, pointerCachePath).ConfigureAwait(false); await DownloadImage(request.ImageUrl, urlHash, pointerCachePath).ConfigureAwait(false);
// Read the pointer file again // Read the pointer file again
contentPath = _fileSystem.ReadAllText(pointerCachePath); contentPath = File.ReadAllText(pointerCachePath);
return await ResultFactory.GetStaticFileResult(Request, contentPath).ConfigureAwait(false); return await ResultFactory.GetStaticFileResult(Request, contentPath).ConfigureAwait(false);
} }
@ -264,7 +264,7 @@ namespace MediaBrowser.Api.Images
var fullCachePath = GetFullCachePath(urlHash + "." + ext); var fullCachePath = GetFullCachePath(urlHash + "." + ext);
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(fullCachePath)); Directory.CreateDirectory(Path.GetDirectoryName(fullCachePath));
using (var stream = result.Content) using (var stream = result.Content)
{ {
using (var filestream = _fileSystem.GetFileStream(fullCachePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) using (var filestream = _fileSystem.GetFileStream(fullCachePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
@ -273,8 +273,8 @@ namespace MediaBrowser.Api.Images
} }
} }
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(pointerCachePath)); Directory.CreateDirectory(Path.GetDirectoryName(pointerCachePath));
_fileSystem.WriteAllText(pointerCachePath, fullCachePath); File.WriteAllText(pointerCachePath, fullCachePath);
} }
} }

View file

@ -265,9 +265,9 @@ namespace MediaBrowser.Api
try try
{ {
contentPath = _fileSystem.ReadAllText(pointerCachePath); contentPath = File.ReadAllText(pointerCachePath);
if (_fileSystem.FileExists(contentPath)) if (File.Exists(contentPath))
{ {
return await ResultFactory.GetStaticFileResult(Request, contentPath).ConfigureAwait(false); return await ResultFactory.GetStaticFileResult(Request, contentPath).ConfigureAwait(false);
} }
@ -284,7 +284,7 @@ namespace MediaBrowser.Api
await DownloadImage(request.ProviderName, request.ImageUrl, urlHash, pointerCachePath).ConfigureAwait(false); await DownloadImage(request.ProviderName, request.ImageUrl, urlHash, pointerCachePath).ConfigureAwait(false);
// Read the pointer file again // Read the pointer file again
contentPath = _fileSystem.ReadAllText(pointerCachePath); contentPath = File.ReadAllText(pointerCachePath);
return await ResultFactory.GetStaticFileResult(Request, contentPath).ConfigureAwait(false); return await ResultFactory.GetStaticFileResult(Request, contentPath).ConfigureAwait(false);
} }
@ -305,7 +305,7 @@ namespace MediaBrowser.Api
var fullCachePath = GetFullCachePath(urlHash + "." + ext); var fullCachePath = GetFullCachePath(urlHash + "." + ext);
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(fullCachePath)); Directory.CreateDirectory(Path.GetDirectoryName(fullCachePath));
using (var stream = result.Content) using (var stream = result.Content)
{ {
using (var filestream = _fileSystem.GetFileStream(fullCachePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) using (var filestream = _fileSystem.GetFileStream(fullCachePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
@ -314,8 +314,8 @@ namespace MediaBrowser.Api
} }
} }
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(pointerCachePath)); Directory.CreateDirectory(Path.GetDirectoryName(pointerCachePath));
_fileSystem.WriteAllText(pointerCachePath, fullCachePath); File.WriteAllText(pointerCachePath, fullCachePath);
} }
/// <summary> /// <summary>

View file

@ -255,12 +255,12 @@ namespace MediaBrowser.Api.Library
var currentPath = Path.Combine(rootFolderPath, request.Name); var currentPath = Path.Combine(rootFolderPath, request.Name);
var newPath = Path.Combine(rootFolderPath, request.NewName); var newPath = Path.Combine(rootFolderPath, request.NewName);
if (!_fileSystem.DirectoryExists(currentPath)) if (!Directory.Exists(currentPath))
{ {
throw new FileNotFoundException("The media collection does not exist"); throw new FileNotFoundException("The media collection does not exist");
} }
if (!string.Equals(currentPath, newPath, StringComparison.OrdinalIgnoreCase) && _fileSystem.DirectoryExists(newPath)) if (!string.Equals(currentPath, newPath, StringComparison.OrdinalIgnoreCase) && Directory.Exists(newPath))
{ {
throw new ArgumentException("Media library already exists at " + newPath + "."); throw new ArgumentException("Media library already exists at " + newPath + ".");
} }
@ -273,11 +273,11 @@ namespace MediaBrowser.Api.Library
if (string.Equals(currentPath, newPath, StringComparison.OrdinalIgnoreCase)) if (string.Equals(currentPath, newPath, StringComparison.OrdinalIgnoreCase))
{ {
var tempPath = Path.Combine(rootFolderPath, Guid.NewGuid().ToString("N")); var tempPath = Path.Combine(rootFolderPath, Guid.NewGuid().ToString("N"));
_fileSystem.MoveDirectory(currentPath, tempPath); Directory.Move(currentPath, tempPath);
currentPath = tempPath; currentPath = tempPath;
} }
_fileSystem.MoveDirectory(currentPath, newPath); Directory.Move(currentPath, newPath);
} }
finally finally
{ {

View file

@ -192,7 +192,7 @@ namespace MediaBrowser.Api.Playback
CancellationTokenSource cancellationTokenSource, CancellationTokenSource cancellationTokenSource,
string workingDirectory = null) string workingDirectory = null)
{ {
FileSystem.CreateDirectory(FileSystem.GetDirectoryName(outputPath)); Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
await AcquireResources(state, cancellationTokenSource).ConfigureAwait(false); await AcquireResources(state, cancellationTokenSource).ConfigureAwait(false);
@ -258,7 +258,7 @@ namespace MediaBrowser.Api.Playback
} }
var logFilePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, logFilePrefix + "-" + Guid.NewGuid() + ".txt"); var logFilePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, logFilePrefix + "-" + Guid.NewGuid() + ".txt");
FileSystem.CreateDirectory(FileSystem.GetDirectoryName(logFilePath)); Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
// FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
state.LogFileStream = FileSystem.GetFileStream(logFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true); state.LogFileStream = FileSystem.GetFileStream(logFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true);
@ -290,7 +290,7 @@ namespace MediaBrowser.Api.Playback
new JobLogger(Logger).StartStreamingLog(state, process.StandardError.BaseStream, state.LogFileStream); new JobLogger(Logger).StartStreamingLog(state, process.StandardError.BaseStream, state.LogFileStream);
// Wait for the file to exist before proceeeding // Wait for the file to exist before proceeeding
while (!FileSystem.FileExists(state.WaitForPath ?? outputPath) && !transcodingJob.HasExited) while (!File.Exists(state.WaitForPath ?? outputPath) && !transcodingJob.HasExited)
{ {
await Task.Delay(100, cancellationTokenSource.Token).ConfigureAwait(false); await Task.Delay(100, cancellationTokenSource.Token).ConfigureAwait(false);
} }

View file

@ -83,13 +83,13 @@ namespace MediaBrowser.Api.Playback.Hls
TranscodingJob job = null; TranscodingJob job = null;
var playlist = state.OutputFilePath; var playlist = state.OutputFilePath;
if (!FileSystem.FileExists(playlist)) if (!File.Exists(playlist))
{ {
var transcodingLock = ApiEntryPoint.Instance.GetTranscodingLock(playlist); var transcodingLock = ApiEntryPoint.Instance.GetTranscodingLock(playlist);
await transcodingLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false); await transcodingLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
try try
{ {
if (!FileSystem.FileExists(playlist)) if (!File.Exists(playlist))
{ {
// If the playlist doesn't already exist, startup ffmpeg // If the playlist doesn't already exist, startup ffmpeg
try try
@ -264,7 +264,7 @@ namespace MediaBrowser.Api.Playback.Hls
var useGenericSegmenter = true; var useGenericSegmenter = true;
if (useGenericSegmenter) if (useGenericSegmenter)
{ {
var outputTsArg = Path.Combine(FileSystem.GetDirectoryName(outputPath), Path.GetFileNameWithoutExtension(outputPath)) + "%d" + GetSegmentFileExtension(state.Request); var outputTsArg = Path.Combine(Path.GetDirectoryName(outputPath), Path.GetFileNameWithoutExtension(outputPath)) + "%d" + GetSegmentFileExtension(state.Request);
var timeDeltaParam = string.Empty; var timeDeltaParam = string.Empty;

View file

@ -164,7 +164,7 @@ namespace MediaBrowser.Api.Playback.Hls
TranscodingJob job = null; TranscodingJob job = null;
if (FileSystem.FileExists(segmentPath)) if (File.Exists(segmentPath))
{ {
job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType); job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, requestedIndex, job, cancellationToken).ConfigureAwait(false); return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, requestedIndex, job, cancellationToken).ConfigureAwait(false);
@ -177,7 +177,7 @@ namespace MediaBrowser.Api.Playback.Hls
try try
{ {
if (FileSystem.FileExists(segmentPath)) if (File.Exists(segmentPath))
{ {
job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType); job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
transcodingLock.Release(); transcodingLock.Release();
@ -381,7 +381,7 @@ namespace MediaBrowser.Api.Playback.Hls
private static FileSystemMetadata GetLastTranscodingFile(string playlist, string segmentExtension, IFileSystem fileSystem) private static FileSystemMetadata GetLastTranscodingFile(string playlist, string segmentExtension, IFileSystem fileSystem)
{ {
var folder = fileSystem.GetDirectoryName(playlist); var folder = Path.GetDirectoryName(playlist);
var filePrefix = Path.GetFileNameWithoutExtension(playlist) ?? string.Empty; var filePrefix = Path.GetFileNameWithoutExtension(playlist) ?? string.Empty;
@ -418,7 +418,7 @@ namespace MediaBrowser.Api.Playback.Hls
private string GetSegmentPath(StreamState state, string playlist, int index) private string GetSegmentPath(StreamState state, string playlist, int index)
{ {
var folder = FileSystem.GetDirectoryName(playlist); var folder = Path.GetDirectoryName(playlist);
var filename = Path.GetFileNameWithoutExtension(playlist); var filename = Path.GetFileNameWithoutExtension(playlist);
@ -433,7 +433,7 @@ namespace MediaBrowser.Api.Playback.Hls
TranscodingJob transcodingJob, TranscodingJob transcodingJob,
CancellationToken cancellationToken) CancellationToken cancellationToken)
{ {
var segmentFileExists = FileSystem.FileExists(segmentPath); var segmentFileExists = File.Exists(segmentPath);
// If all transcoding has completed, just return immediately // If all transcoding has completed, just return immediately
if (transcodingJob != null && transcodingJob.HasExited && segmentFileExists) if (transcodingJob != null && transcodingJob.HasExited && segmentFileExists)
@ -458,14 +458,14 @@ namespace MediaBrowser.Api.Playback.Hls
{ {
try try
{ {
var text = FileSystem.ReadAllText(playlistPath, Encoding.UTF8); var text = File.ReadAllText(playlistPath, Encoding.UTF8);
// If it appears in the playlist, it's done // If it appears in the playlist, it's done
if (text.IndexOf(segmentFilename, StringComparison.OrdinalIgnoreCase) != -1) if (text.IndexOf(segmentFilename, StringComparison.OrdinalIgnoreCase) != -1)
{ {
if (!segmentFileExists) if (!segmentFileExists)
{ {
segmentFileExists = FileSystem.FileExists(segmentPath); segmentFileExists = File.Exists(segmentPath);
} }
if (segmentFileExists) if (segmentFileExists)
{ {
@ -932,7 +932,7 @@ namespace MediaBrowser.Api.Playback.Hls
var mapArgs = state.IsOutputVideo ? EncodingHelper.GetMapArgs(state) : string.Empty; var mapArgs = state.IsOutputVideo ? EncodingHelper.GetMapArgs(state) : string.Empty;
var outputTsArg = Path.Combine(FileSystem.GetDirectoryName(outputPath), Path.GetFileNameWithoutExtension(outputPath)) + "%d" + GetSegmentFileExtension(state.Request); var outputTsArg = Path.Combine(Path.GetDirectoryName(outputPath), Path.GetFileNameWithoutExtension(outputPath)) + "%d" + GetSegmentFileExtension(state.Request);
var timeDeltaParam = string.Empty; var timeDeltaParam = string.Empty;

View file

@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.IO;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using MediaBrowser.Common.Net; using MediaBrowser.Common.Net;
@ -153,7 +154,7 @@ namespace MediaBrowser.Api.Playback.Progressive
} }
var outputPath = state.OutputFilePath; var outputPath = state.OutputFilePath;
var outputPathExists = FileSystem.FileExists(outputPath); var outputPathExists = File.Exists(outputPath);
var transcodingJob = ApiEntryPoint.Instance.GetTranscodingJob(outputPath, TranscodingJobType.Progressive); var transcodingJob = ApiEntryPoint.Instance.GetTranscodingJob(outputPath, TranscodingJobType.Progressive);
var isTranscodeCached = outputPathExists && transcodingJob != null; var isTranscodeCached = outputPathExists && transcodingJob != null;
@ -377,7 +378,7 @@ namespace MediaBrowser.Api.Playback.Progressive
{ {
TranscodingJob job; TranscodingJob job;
if (!FileSystem.FileExists(outputPath)) if (!File.Exists(outputPath))
{ {
job = await StartFfMpeg(state, outputPath, cancellationTokenSource).ConfigureAwait(false); job = await StartFfMpeg(state, outputPath, cancellationTokenSource).ConfigureAwait(false);
} }

View file

@ -153,7 +153,11 @@ namespace MediaBrowser.Api
private readonly INetworkManager _network; private readonly INetworkManager _network;
private readonly IDeviceManager _deviceManager; private readonly IDeviceManager _deviceManager;
public PluginService(IJsonSerializer jsonSerializer, IApplicationHost appHost, IInstallationManager installationManager, INetworkManager network, IDeviceManager deviceManager) public PluginService(IJsonSerializer jsonSerializer,
IApplicationHost appHost,
IInstallationManager installationManager,
INetworkManager network,
IDeviceManager deviceManager)
: base() : base()
{ {
if (jsonSerializer == null) if (jsonSerializer == null)
@ -173,7 +177,7 @@ namespace MediaBrowser.Api
/// </summary> /// </summary>
/// <param name="request">The request.</param> /// <param name="request">The request.</param>
/// <returns>System.Object.</returns> /// <returns>System.Object.</returns>
public async Task<object> Get(GetRegistrationStatus request) public object Get(GetRegistrationStatus request)
{ {
var record = new MBRegistrationRecord var record = new MBRegistrationRecord
{ {
@ -187,26 +191,12 @@ namespace MediaBrowser.Api
return ToOptimizedResult(record); return ToOptimizedResult(record);
} }
//TODO this function is only kept for compatibility and should be removed once paid plugins break
public async Task<object> Get(GetRegistration request)
{
var info = new RegistrationInfo
{
ExpirationDate = DateTime.Now.AddYears(100),
IsRegistered = true,
IsTrial = false,
Name = request.Name
};
return ToOptimizedResult(info);
}
/// <summary> /// <summary>
/// Gets the specified request. /// Gets the specified request.
/// </summary> /// </summary>
/// <param name="request">The request.</param> /// <param name="request">The request.</param>
/// <returns>System.Object.</returns> /// <returns>System.Object.</returns>
public async Task<object> Get(GetPlugins request) public object Get(GetPlugins request)
{ {
var result = _appHost.Plugins.OrderBy(p => p.Name).Select(p => p.GetPluginInfo()).ToArray(); var result = _appHost.Plugins.OrderBy(p => p.Name).Select(p => p.GetPluginInfo()).ToArray();
return ToOptimizedResult(result); return ToOptimizedResult(result);
@ -230,7 +220,7 @@ namespace MediaBrowser.Api
/// </summary> /// </summary>
/// <param name="request">The request.</param> /// <param name="request">The request.</param>
/// <returns>System.Object.</returns> /// <returns>System.Object.</returns>
public async Task<object> Get(GetPluginSecurityInfo request) public object Get(GetPluginSecurityInfo request)
{ {
var result = new PluginSecurityInfo var result = new PluginSecurityInfo
{ {

View file

@ -102,7 +102,8 @@ namespace MediaBrowser.Api
return new StartupUser return new StartupUser
{ {
Name = user.Name, Name = user.Name,
ConnectUserName = user.ConnectUserName ConnectUserName = user.ConnectUserName,
Password = user.Password
}; };
} }
@ -111,8 +112,13 @@ namespace MediaBrowser.Api
var user = _userManager.Users.First(); var user = _userManager.Users.First();
user.Name = request.Name; user.Name = request.Name;
_userManager.UpdateUser(user); _userManager.UpdateUser(user);
if (!string.IsNullOrEmpty(request.Password)) {
await _userManager.ChangePassword(user, request.Password).ConfigureAwait(false);
}
var result = new UpdateStartupUserResult(); var result = new UpdateStartupUserResult();
return result; return result;
@ -130,6 +136,7 @@ namespace MediaBrowser.Api
{ {
public string Name { get; set; } public string Name { get; set; }
public string ConnectUserName { get; set; } public string ConnectUserName { get; set; }
public string Password { get; set; }
} }
public class UpdateStartupUserResult public class UpdateStartupUserResult

View file

@ -267,13 +267,13 @@ namespace MediaBrowser.Api.UserLibrary
var session = GetSession(_sessionContext); var session = GetSession(_sessionContext);
var dto = await UpdatePlayedStatus(user, request.Id, true, datePlayed).ConfigureAwait(false); var dto = UpdatePlayedStatus(user, request.Id, true, datePlayed);
foreach (var additionalUserInfo in session.AdditionalUsers) foreach (var additionalUserInfo in session.AdditionalUsers)
{ {
var additionalUser = _userManager.GetUserById(additionalUserInfo.UserId); var additionalUser = _userManager.GetUserById(additionalUserInfo.UserId);
await UpdatePlayedStatus(additionalUser, request.Id, true, datePlayed).ConfigureAwait(false); UpdatePlayedStatus(additionalUser, request.Id, true, datePlayed);
} }
return dto; return dto;
@ -412,13 +412,13 @@ namespace MediaBrowser.Api.UserLibrary
var session = GetSession(_sessionContext); var session = GetSession(_sessionContext);
var dto = await UpdatePlayedStatus(user, request.Id, false, null).ConfigureAwait(false); var dto = UpdatePlayedStatus(user, request.Id, false, null);
foreach (var additionalUserInfo in session.AdditionalUsers) foreach (var additionalUserInfo in session.AdditionalUsers)
{ {
var additionalUser = _userManager.GetUserById(additionalUserInfo.UserId); var additionalUser = _userManager.GetUserById(additionalUserInfo.UserId);
await UpdatePlayedStatus(additionalUser, request.Id, false, null).ConfigureAwait(false); UpdatePlayedStatus(additionalUser, request.Id, false, null);
} }
return dto; return dto;
@ -432,7 +432,7 @@ namespace MediaBrowser.Api.UserLibrary
/// <param name="wasPlayed">if set to <c>true</c> [was played].</param> /// <param name="wasPlayed">if set to <c>true</c> [was played].</param>
/// <param name="datePlayed">The date played.</param> /// <param name="datePlayed">The date played.</param>
/// <returns>Task.</returns> /// <returns>Task.</returns>
private async Task<UserItemDataDto> UpdatePlayedStatus(User user, string itemId, bool wasPlayed, DateTime? datePlayed) private UserItemDataDto UpdatePlayedStatus(User user, string itemId, bool wasPlayed, DateTime? datePlayed)
{ {
var item = _libraryManager.GetItemById(itemId); var item = _libraryManager.GetItemById(itemId);

View file

@ -63,7 +63,8 @@ namespace MediaBrowser.Controller.Drawing
case ImageType.Logo: case ImageType.Logo:
return 2.58; return 2.58;
case ImageType.Primary: case ImageType.Primary:
return item.GetDefaultPrimaryImageAspectRatio(); double defaultPrimaryImageAspectRatio = item.GetDefaultPrimaryImageAspectRatio();
return defaultPrimaryImageAspectRatio > 0 ? defaultPrimaryImageAspectRatio : 2.0 / 3;
default: default:
return 1; return 1;
} }

View file

@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.IO;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
@ -228,7 +229,7 @@ namespace MediaBrowser.Controller.Entities
return Path; return Path;
} }
return FileSystem.GetDirectoryName(Path); return System.IO.Path.GetDirectoryName(Path);
} }
} }
@ -2208,7 +2209,7 @@ namespace MediaBrowser.Controller.Entities
{ {
var allFiles = ImageInfos var allFiles = ImageInfos
.Where(i => i.IsLocalFile) .Where(i => i.IsLocalFile)
.Select(i => FileSystem.GetDirectoryName(i.Path)) .Select(i => System.IO.Path.GetDirectoryName(i.Path))
.Distinct(StringComparer.OrdinalIgnoreCase) .Distinct(StringComparer.OrdinalIgnoreCase)
.SelectMany(i => directoryService.GetFilePaths(i)) .SelectMany(i => directoryService.GetFilePaths(i))
.ToList(); .ToList();
@ -2343,7 +2344,7 @@ namespace MediaBrowser.Controller.Entities
var newImagePaths = images.Select(i => i.FullName).ToList(); var newImagePaths = images.Select(i => i.FullName).ToList();
var deleted = existingImages var deleted = existingImages
.Where(i => i.IsLocalFile && !newImagePaths.Contains(i.Path, StringComparer.OrdinalIgnoreCase) && !FileSystem.FileExists(i.Path)) .Where(i => i.IsLocalFile && !newImagePaths.Contains(i.Path, StringComparer.OrdinalIgnoreCase) && !File.Exists(i.Path))
.ToList(); .ToList();
if (deleted.Count > 0) if (deleted.Count > 0)
@ -2396,7 +2397,7 @@ namespace MediaBrowser.Controller.Entities
var extensions = new List<string> { ".nfo", ".xml", ".srt", ".vtt", ".sub", ".idx", ".txt", ".edl", ".bif", ".smi", ".ttml" }; var extensions = new List<string> { ".nfo", ".xml", ".srt", ".vtt", ".sub", ".idx", ".txt", ".edl", ".bif", ".smi", ".ttml" };
extensions.AddRange(SupportedImageExtensions); extensions.AddRange(SupportedImageExtensions);
return FileSystem.GetFiles(FileSystem.GetDirectoryName(Path), extensions.ToArray(), false, false) return FileSystem.GetFiles(System.IO.Path.GetDirectoryName(Path), extensions.ToArray(), false, false)
.Where(i => System.IO.Path.GetFileNameWithoutExtension(i.FullName).StartsWith(filename, StringComparison.OrdinalIgnoreCase)) .Where(i => System.IO.Path.GetFileNameWithoutExtension(i.FullName).StartsWith(filename, StringComparison.OrdinalIgnoreCase))
.ToList(); .ToList();
} }
@ -2508,7 +2509,7 @@ namespace MediaBrowser.Controller.Entities
if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Path)) if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Path))
{ {
Name = FileSystem.GetFileNameWithoutExtension(Path); Name = System.IO.Path.GetFileNameWithoutExtension(Path);
hasChanges = true; hasChanges = true;
} }

View file

@ -87,7 +87,7 @@ namespace MediaBrowser.Controller.Entities
return new[] { return new[] {
new FileSystemMetadata new FileSystemMetadata
{ {
FullName = FileSystem.GetDirectoryName(Path), FullName = System.IO.Path.GetDirectoryName(Path),
IsDirectory = true IsDirectory = true
} }
}; };

View file

@ -97,7 +97,7 @@ namespace MediaBrowser.Controller.Entities.TV
return series.Path; return series.Path;
} }
return FileSystem.GetDirectoryName(Path); return System.IO.Path.GetDirectoryName(Path);
} }
} }

View file

@ -1,4 +1,5 @@
using System; using System;
using System.IO;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Library;
@ -167,18 +168,18 @@ namespace MediaBrowser.Controller.Entities
var oldConfigurationDirectory = ConfigurationDirectoryPath; var oldConfigurationDirectory = ConfigurationDirectoryPath;
// Exceptions will be thrown if these paths already exist // Exceptions will be thrown if these paths already exist
if (FileSystem.DirectoryExists(newConfigDirectory)) if (Directory.Exists(newConfigDirectory))
{ {
FileSystem.DeleteDirectory(newConfigDirectory, true); Directory.Delete(newConfigDirectory, true);
} }
if (FileSystem.DirectoryExists(oldConfigurationDirectory)) if (Directory.Exists(oldConfigurationDirectory))
{ {
FileSystem.MoveDirectory(oldConfigurationDirectory, newConfigDirectory); Directory.Move(oldConfigurationDirectory, newConfigDirectory);
} }
else else
{ {
FileSystem.CreateDirectory(newConfigDirectory); Directory.CreateDirectory(newConfigDirectory);
} }
} }

View file

@ -345,7 +345,7 @@ namespace MediaBrowser.Controller.Entities
{ {
if (IsStacked) if (IsStacked)
{ {
return FileSystem.GetDirectoryName(Path); return System.IO.Path.GetDirectoryName(Path);
} }
if (!IsPlaceHolder) if (!IsPlaceHolder)

View file

@ -85,7 +85,7 @@ namespace MediaBrowser.Controller.Library
return false; return false;
} }
var parentDir = BaseItem.FileSystem.GetDirectoryName(Path) ?? string.Empty; var parentDir = System.IO.Path.GetDirectoryName(Path) ?? string.Empty;
return parentDir.Length > _appPaths.RootFolderPath.Length return parentDir.Length > _appPaths.RootFolderPath.Length
&& parentDir.StartsWith(_appPaths.RootFolderPath, StringComparison.OrdinalIgnoreCase); && parentDir.StartsWith(_appPaths.RootFolderPath, StringComparison.OrdinalIgnoreCase);

View file

@ -434,7 +434,7 @@ namespace MediaBrowser.Controller.MediaEncoding
if (string.Equals(Path.GetExtension(subtitlePath), ".sub", StringComparison.OrdinalIgnoreCase)) if (string.Equals(Path.GetExtension(subtitlePath), ".sub", StringComparison.OrdinalIgnoreCase))
{ {
var idxFile = Path.ChangeExtension(subtitlePath, ".idx"); var idxFile = Path.ChangeExtension(subtitlePath, ".idx");
if (_fileSystem.FileExists(idxFile)) if (File.Exists(idxFile))
{ {
subtitlePath = idxFile; subtitlePath = idxFile;
} }
@ -542,7 +542,7 @@ namespace MediaBrowser.Controller.MediaEncoding
// var fallbackFontPath = Path.Combine(_appPaths.ProgramDataPath, "fonts", "DroidSansFallback.ttf"); // var fallbackFontPath = Path.Combine(_appPaths.ProgramDataPath, "fonts", "DroidSansFallback.ttf");
// string fallbackFontParam = string.Empty; // string fallbackFontParam = string.Empty;
// if (!_fileSystem.FileExists(fallbackFontPath)) // if (!File.Exists(fallbackFontPath))
// { // {
// _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(fallbackFontPath)); // _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(fallbackFontPath));
// using (var stream = _assemblyInfo.GetManifestResourceStream(GetType(), GetType().Namespace + ".DroidSansFallback.ttf")) // using (var stream = _assemblyInfo.GetManifestResourceStream(GetType(), GetType().Namespace + ".DroidSansFallback.ttf"))
@ -1438,6 +1438,11 @@ namespace MediaBrowser.Controller.MediaEncoding
if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase) && outputSizeParam.Length == 0) if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase) && outputSizeParam.Length == 0)
{ {
outputSizeParam = ",format=nv12|vaapi,hwupload"; outputSizeParam = ",format=nv12|vaapi,hwupload";
// Add parameters to use VAAPI with burn-in subttiles (GH issue #642)
if (state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode) {
outputSizeParam += ",hwmap=mode=read+write+direct";
}
} }
var videoSizeParam = string.Empty; var videoSizeParam = string.Empty;
@ -1741,6 +1746,12 @@ namespace MediaBrowser.Controller.MediaEncoding
filters.Add(subParam); filters.Add(subParam);
// Ensure proper filters are passed to ffmpeg in case of hardware acceleration via VA-API
// Reference: https://trac.ffmpeg.org/wiki/Hardware/VAAPI
if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
{
filters.Add("hwmap");
}
if (allowTimeStampCopy) if (allowTimeStampCopy)
{ {
output += " -copyts"; output += " -copyts";

View file

@ -50,7 +50,7 @@ namespace MediaBrowser.Controller.Playlists
if (IsPlaylistFile(path)) if (IsPlaylistFile(path))
{ {
return FileSystem.GetDirectoryName(path); return System.IO.Path.GetDirectoryName(path);
} }
return path; return path;

View file

@ -15,11 +15,6 @@ namespace MediaBrowser.Controller.Subtitles
/// </summary> /// </summary>
event EventHandler<SubtitleDownloadFailureEventArgs> SubtitleDownloadFailure; event EventHandler<SubtitleDownloadFailureEventArgs> SubtitleDownloadFailure;
/// <summary>
/// Occurs when [subtitles downloaded].
/// </summary>
event EventHandler<SubtitleDownloadEventArgs> SubtitlesDownloaded;
/// <summary> /// <summary>
/// Adds the parts. /// Adds the parts.
/// </summary> /// </summary>

View file

@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Linq; using System.Linq;
using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Entities.TV;
@ -29,11 +30,11 @@ namespace MediaBrowser.LocalMetadata.Images
public List<LocalImageInfo> GetImages(BaseItem item, IDirectoryService directoryService) public List<LocalImageInfo> GetImages(BaseItem item, IDirectoryService directoryService)
{ {
var parentPath = _fileSystem.GetDirectoryName(item.Path); var parentPath = Path.GetDirectoryName(item.Path);
var parentPathFiles = directoryService.GetFiles(parentPath); var parentPathFiles = directoryService.GetFiles(parentPath);
var nameWithoutExtension = _fileSystem.GetFileNameWithoutExtension(item.Path); var nameWithoutExtension = Path.GetFileNameWithoutExtension(item.Path);
return GetFilesFromParentFolder(nameWithoutExtension, parentPathFiles); return GetFilesFromParentFolder(nameWithoutExtension, parentPathFiles);
} }

View file

@ -102,7 +102,7 @@ namespace MediaBrowser.LocalMetadata.Parsers
{ {
item.ResetPeople(); item.ResetPeople();
using (var fileStream = FileSystem.OpenRead(metadataFile)) using (var fileStream = File.OpenRead(metadataFile))
{ {
using (var streamReader = new StreamReader(fileStream, encoding)) using (var streamReader = new StreamReader(fileStream, encoding))
{ {

View file

@ -33,7 +33,7 @@ namespace MediaBrowser.LocalMetadata.Providers
var specificFile = Path.ChangeExtension(info.Path, ".xml"); var specificFile = Path.ChangeExtension(info.Path, ".xml");
var file = FileSystem.GetFileInfo(specificFile); var file = FileSystem.GetFileInfo(specificFile);
return info.IsInMixedFolder || file.Exists ? file : FileSystem.GetFileInfo(Path.Combine(FileSystem.GetDirectoryName(info.Path), "game.xml")); return info.IsInMixedFolder || file.Exists ? file : FileSystem.GetFileInfo(Path.Combine(Path.GetDirectoryName(info.Path), "game.xml"));
} }
} }
} }

View file

@ -94,7 +94,7 @@ namespace MediaBrowser.LocalMetadata.Savers
private void SaveToFile(Stream stream, string path) private void SaveToFile(Stream stream, string path)
{ {
FileSystem.CreateDirectory(FileSystem.GetDirectoryName(path)); Directory.CreateDirectory(Path.GetDirectoryName(path));
// On Windows, savint the file will fail if the file is hidden or readonly // On Windows, savint the file will fail if the file is hidden or readonly
FileSystem.SetAttributes(path, false, false); FileSystem.SetAttributes(path, false, false);

View file

@ -46,7 +46,7 @@ namespace MediaBrowser.MediaEncoding.Configuration
&& !string.Equals(oldEncodingConfig.TranscodingTempPath ?? string.Empty, newPath)) && !string.Equals(oldEncodingConfig.TranscodingTempPath ?? string.Empty, newPath))
{ {
// Validate // Validate
if (!_fileSystem.DirectoryExists(newPath)) if (!Directory.Exists(newPath))
{ {
throw new FileNotFoundException(string.Format("{0} does not exist.", newPath)); throw new FileNotFoundException(string.Format("{0} does not exist.", newPath));
} }

View file

@ -67,7 +67,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
.CreateJob(options, EncodingHelper, IsVideoEncoder, progress, cancellationToken).ConfigureAwait(false); .CreateJob(options, EncodingHelper, IsVideoEncoder, progress, cancellationToken).ConfigureAwait(false);
encodingJob.OutputFilePath = GetOutputFilePath(encodingJob); encodingJob.OutputFilePath = GetOutputFilePath(encodingJob);
FileSystem.CreateDirectory(FileSystem.GetDirectoryName(encodingJob.OutputFilePath)); Directory.CreateDirectory(Path.GetDirectoryName(encodingJob.OutputFilePath));
encodingJob.ReadInputAtNativeFramerate = options.ReadInputAtNativeFramerate; encodingJob.ReadInputAtNativeFramerate = options.ReadInputAtNativeFramerate;
@ -105,7 +105,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
Logger.LogInformation(commandLineLogMessage); Logger.LogInformation(commandLineLogMessage);
var logFilePath = Path.Combine(ConfigurationManager.CommonApplicationPaths.LogDirectoryPath, "transcode-" + Guid.NewGuid() + ".txt"); var logFilePath = Path.Combine(ConfigurationManager.CommonApplicationPaths.LogDirectoryPath, "transcode-" + Guid.NewGuid() + ".txt");
FileSystem.CreateDirectory(FileSystem.GetDirectoryName(logFilePath)); Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
// FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
encodingJob.LogFileStream = FileSystem.GetFileStream(logFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true); encodingJob.LogFileStream = FileSystem.GetFileStream(logFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true);
@ -137,7 +137,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
new JobLogger(Logger).StartStreamingLog(encodingJob, process.StandardError.BaseStream, encodingJob.LogFileStream); new JobLogger(Logger).StartStreamingLog(encodingJob, process.StandardError.BaseStream, encodingJob.LogFileStream);
// Wait for the file to exist before proceeeding // Wait for the file to exist before proceeeding
while (!FileSystem.FileExists(encodingJob.OutputFilePath) && !encodingJob.HasExited) while (!File.Exists(encodingJob.OutputFilePath) && !encodingJob.HasExited)
{ {
await Task.Delay(100, cancellationToken).ConfigureAwait(false); await Task.Delay(100, cancellationToken).ConfigureAwait(false);
} }

View file

@ -214,7 +214,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
throw new ArgumentNullException(nameof(path)); throw new ArgumentNullException(nameof(path));
} }
if (!FileSystem.FileExists(path) && !FileSystem.DirectoryExists(path)) if (!File.Exists(path) && !Directory.Exists(path))
{ {
throw new ResourceNotFoundException(); throw new ResourceNotFoundException();
} }
@ -288,12 +288,12 @@ namespace MediaBrowser.MediaEncoding.Encoder
if (!string.IsNullOrWhiteSpace(appPath)) if (!string.IsNullOrWhiteSpace(appPath))
{ {
if (FileSystem.DirectoryExists(appPath)) if (Directory.Exists(appPath))
{ {
return GetPathsFromDirectory(appPath); return GetPathsFromDirectory(appPath);
} }
if (FileSystem.FileExists(appPath)) if (File.Exists(appPath))
{ {
return new Tuple<string, string>(appPath, GetProbePathFromEncoderPath(appPath)); return new Tuple<string, string>(appPath, GetProbePathFromEncoderPath(appPath));
} }
@ -336,7 +336,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
var ffmpegPath = files.FirstOrDefault(i => string.Equals(Path.GetFileNameWithoutExtension(i), "ffmpeg", StringComparison.OrdinalIgnoreCase) && !excludeExtensions.Contains(Path.GetExtension(i) ?? string.Empty)); var ffmpegPath = files.FirstOrDefault(i => string.Equals(Path.GetFileNameWithoutExtension(i), "ffmpeg", StringComparison.OrdinalIgnoreCase) && !excludeExtensions.Contains(Path.GetExtension(i) ?? string.Empty));
var ffprobePath = files.FirstOrDefault(i => string.Equals(Path.GetFileNameWithoutExtension(i), "ffprobe", StringComparison.OrdinalIgnoreCase) && !excludeExtensions.Contains(Path.GetExtension(i) ?? string.Empty)); var ffprobePath = files.FirstOrDefault(i => string.Equals(Path.GetFileNameWithoutExtension(i), "ffprobe", StringComparison.OrdinalIgnoreCase) && !excludeExtensions.Contains(Path.GetExtension(i) ?? string.Empty));
if (string.IsNullOrWhiteSpace(ffmpegPath) || !FileSystem.FileExists(ffmpegPath)) if (string.IsNullOrWhiteSpace(ffmpegPath) || !File.Exists(ffmpegPath))
{ {
files = FileSystem.GetFilePaths(path, true); files = FileSystem.GetFilePaths(path, true);
@ -353,7 +353,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
private string GetProbePathFromEncoderPath(string appPath) private string GetProbePathFromEncoderPath(string appPath)
{ {
return FileSystem.GetFilePaths(FileSystem.GetDirectoryName(appPath)) return FileSystem.GetFilePaths(Path.GetDirectoryName(appPath))
.FirstOrDefault(i => string.Equals(Path.GetFileNameWithoutExtension(i), "ffprobe", StringComparison.OrdinalIgnoreCase)); .FirstOrDefault(i => string.Equals(Path.GetFileNameWithoutExtension(i), "ffprobe", StringComparison.OrdinalIgnoreCase));
} }
@ -608,7 +608,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
} }
var tempExtractPath = Path.Combine(ConfigurationManager.ApplicationPaths.TempDirectory, Guid.NewGuid() + ".jpg"); var tempExtractPath = Path.Combine(ConfigurationManager.ApplicationPaths.TempDirectory, Guid.NewGuid() + ".jpg");
FileSystem.CreateDirectory(FileSystem.GetDirectoryName(tempExtractPath)); Directory.CreateDirectory(Path.GetDirectoryName(tempExtractPath));
// apply some filters to thumbnail extracted below (below) crop any black lines that we made and get the correct ar then scale to width 600. // apply some filters to thumbnail extracted below (below) crop any black lines that we made and get the correct ar then scale to width 600.
// This filter chain may have adverse effects on recorded tv thumbnails if ar changes during presentation ex. commercials @ diff ar // This filter chain may have adverse effects on recorded tv thumbnails if ar changes during presentation ex. commercials @ diff ar
@ -770,7 +770,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
vf += string.Format(",scale=min(iw\\,{0}):trunc(ow/dar/2)*2", maxWidthParam); vf += string.Format(",scale=min(iw\\,{0}):trunc(ow/dar/2)*2", maxWidthParam);
} }
FileSystem.CreateDirectory(targetDirectory); Directory.CreateDirectory(targetDirectory);
var outputPath = Path.Combine(targetDirectory, filenamePrefix + "%05d.jpg"); var outputPath = Path.Combine(targetDirectory, filenamePrefix + "%05d.jpg");
var args = string.Format("-i {0} -threads 0 -v quiet -vf \"{2}\" -f image2 \"{1}\"", inputArgument, outputPath, vf); var args = string.Format("-i {0} -threads 0 -v quiet -vf \"{2}\" -f image2 \"{1}\"", inputArgument, outputPath, vf);

View file

@ -269,7 +269,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
var subLanguageId = NormalizeLanguage(request.Language); var subLanguageId = NormalizeLanguage(request.Language);
string hash; string hash;
using (var fileStream = _fileSystem.OpenRead(request.MediaPath)) using (var fileStream = File.OpenRead(request.MediaPath))
{ {
hash = Utilities.ComputeHash(fileStream); hash = Utilities.ComputeHash(fileStream);
} }

View file

@ -210,7 +210,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
} }
} }
return _fileSystem.OpenRead(path); return File.OpenRead(path);
} }
private async Task<SubtitleInfo> GetReadableFile( private async Task<SubtitleInfo> GetReadableFile(
@ -386,7 +386,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
try try
{ {
if (!_fileSystem.FileExists(outputPath)) if (!File.Exists(outputPath))
{ {
await ConvertTextSubtitleToSrtInternal(inputPath, language, inputProtocol, outputPath, cancellationToken).ConfigureAwait(false); await ConvertTextSubtitleToSrtInternal(inputPath, language, inputProtocol, outputPath, cancellationToken).ConfigureAwait(false);
} }
@ -422,7 +422,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
throw new ArgumentNullException(nameof(outputPath)); throw new ArgumentNullException(nameof(outputPath));
} }
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath)); Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
var encodingParam = await GetSubtitleFileCharacterSet(inputPath, language, inputProtocol, cancellationToken).ConfigureAwait(false); var encodingParam = await GetSubtitleFileCharacterSet(inputPath, language, inputProtocol, cancellationToken).ConfigureAwait(false);
@ -481,7 +481,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
{ {
failed = true; failed = true;
if (_fileSystem.FileExists(outputPath)) if (File.Exists(outputPath))
{ {
try try
{ {
@ -494,7 +494,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
} }
} }
} }
else if (!_fileSystem.FileExists(outputPath)) else if (!File.Exists(outputPath))
{ {
failed = true; failed = true;
} }
@ -537,7 +537,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
try try
{ {
if (!_fileSystem.FileExists(outputPath)) if (!File.Exists(outputPath))
{ {
await ExtractTextSubtitleInternal(_mediaEncoder.GetInputArgument(inputFiles, protocol), subtitleStreamIndex, outputCodec, outputPath, cancellationToken).ConfigureAwait(false); await ExtractTextSubtitleInternal(_mediaEncoder.GetInputArgument(inputFiles, protocol), subtitleStreamIndex, outputCodec, outputPath, cancellationToken).ConfigureAwait(false);
} }
@ -565,7 +565,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
throw new ArgumentNullException(nameof(outputPath)); throw new ArgumentNullException(nameof(outputPath));
} }
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath)); Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
var processArgs = string.Format("-i {0} -map 0:{1} -an -vn -c:s {2} \"{3}\"", inputPath, var processArgs = string.Format("-i {0} -map 0:{1} -an -vn -c:s {2} \"{3}\"", inputPath,
subtitleStreamIndex, outputCodec, outputPath); subtitleStreamIndex, outputCodec, outputPath);
@ -634,7 +634,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
_logger.LogError(ex, "Error deleting extracted subtitle {Path}", outputPath); _logger.LogError(ex, "Error deleting extracted subtitle {Path}", outputPath);
} }
} }
else if (!_fileSystem.FileExists(outputPath)) else if (!File.Exists(outputPath))
{ {
failed = true; failed = true;
} }
@ -672,7 +672,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
string text; string text;
Encoding encoding; Encoding encoding;
using (var fileStream = _fileSystem.OpenRead(file)) using (var fileStream = File.OpenRead(file))
using (var reader = new StreamReader(fileStream, true)) using (var reader = new StreamReader(fileStream, true))
{ {
encoding = reader.CurrentEncoding; encoding = reader.CurrentEncoding;
@ -747,7 +747,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
} }
if (protocol == MediaProtocol.File) if (protocol == MediaProtocol.File)
{ {
return _fileSystem.ReadAllBytes(path); return File.ReadAllBytes(path);
} }
throw new ArgumentOutOfRangeException(nameof(protocol)); throw new ArgumentOutOfRangeException(nameof(protocol));

View file

@ -36,32 +36,32 @@ namespace MediaBrowser.Model.IO
string MakeAbsolutePath(string folderPath, string filePath); string MakeAbsolutePath(string folderPath, string filePath);
/// <summary> /// <summary>
/// Returns a <see cref="FileSystemMetadata"/> object for the specified file or directory path. /// Returns a <see cref="FileSystemMetadata" /> object for the specified file or directory path.
/// </summary> /// </summary>
/// <param name="path">A path to a file or directory.</param> /// <param name="path">A path to a file or directory.</param>
/// <returns>A <see cref="FileSystemMetadata"/> object.</returns> /// <returns>A <see cref="FileSystemMetadata" /> object.</returns>
/// <remarks>If the specified path points to a directory, the returned <see cref="FileSystemMetadata"/> object's /// <remarks>If the specified path points to a directory, the returned <see cref="FileSystemMetadata" /> object's
/// <see cref="FileSystemMetadata.IsDirectory"/> property will be set to true and all other properties will reflect the properties of the directory.</remarks> /// <see cref="FileSystemMetadata.IsDirectory" /> property will be set to true and all other properties will reflect the properties of the directory.</remarks>
FileSystemMetadata GetFileSystemInfo(string path); FileSystemMetadata GetFileSystemInfo(string path);
/// <summary> /// <summary>
/// Returns a <see cref="FileSystemMetadata"/> object for the specified file path. /// Returns a <see cref="FileSystemMetadata" /> object for the specified file path.
/// </summary> /// </summary>
/// <param name="path">A path to a file.</param> /// <param name="path">A path to a file.</param>
/// <returns>A <see cref="FileSystemMetadata"/> object.</returns> /// <returns>A <see cref="FileSystemMetadata" /> object.</returns>
/// <remarks><para>If the specified path points to a directory, the returned <see cref="FileSystemMetadata"/> object's /// <remarks><para>If the specified path points to a directory, the returned <see cref="FileSystemMetadata" /> object's
/// <see cref="FileSystemMetadata.IsDirectory"/> property and the <see cref="FileSystemMetadata.Exists"/> property will both be set to false.</para> /// <see cref="FileSystemMetadata.IsDirectory" /> property and the <see cref="FileSystemMetadata.Exists" /> property will both be set to false.</para>
/// <para>For automatic handling of files <b>and</b> directories, use <see cref="GetFileSystemInfo"/>.</para></remarks> /// <para>For automatic handling of files <b>and</b> directories, use <see cref="M:IFileSystem.GetFileSystemInfo(System.String)" />.</para></remarks>
FileSystemMetadata GetFileInfo(string path); FileSystemMetadata GetFileInfo(string path);
/// <summary> /// <summary>
/// Returns a <see cref="FileSystemMetadata"/> object for the specified directory path. /// Returns a <see cref="FileSystemMetadata" /> object for the specified directory path.
/// </summary> /// </summary>
/// <param name="path">A path to a directory.</param> /// <param name="path">A path to a directory.</param>
/// <returns>A <see cref="FileSystemMetadata"/> object.</returns> /// <returns>A <see cref="FileSystemMetadata" /> object.</returns>
/// <remarks><para>If the specified path points to a file, the returned <see cref="FileSystemMetadata"/> object's /// <remarks><para>If the specified path points to a file, the returned <see cref="FileSystemMetadata" /> object's
/// <see cref="FileSystemMetadata.IsDirectory"/> property will be set to true and the <see cref="FileSystemMetadata.Exists"/> property will be set to false.</para> /// <see cref="FileSystemMetadata.IsDirectory" /> property will be set to true and the <see cref="FileSystemMetadata.Exists" /> property will be set to false.</para>
/// <para>For automatic handling of files <b>and</b> directories, use <see cref="GetFileSystemInfo"/>.</para></remarks> /// <para>For automatic handling of files <b>and</b> directories, use <see cref="M:IFileSystem.GetFileSystemInfo(System.String)" />.</para></remarks>
FileSystemMetadata GetDirectoryInfo(string path); FileSystemMetadata GetDirectoryInfo(string path);
/// <summary> /// <summary>
@ -110,14 +110,8 @@ namespace MediaBrowser.Model.IO
/// <returns>FileStream.</returns> /// <returns>FileStream.</returns>
Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, bool isAsync = false); Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, bool isAsync = false);
Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, FileOpenOptions fileOpenOptions); Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share,
FileOpenOptions fileOpenOptions);
/// <summary>
/// Opens the read.
/// </summary>
/// <param name="path">The path.</param>
/// <returns>Stream.</returns>
Stream OpenRead(string path);
string DefaultDirectory { get; } string DefaultDirectory { get; }
@ -152,8 +146,6 @@ namespace MediaBrowser.Model.IO
/// <returns>System.String.</returns> /// <returns>System.String.</returns>
string NormalizePath(string path); string NormalizePath(string path);
string GetDirectoryName(string path);
/// <summary> /// <summary>
/// Gets the file name without extension. /// Gets the file name without extension.
/// </summary> /// </summary>
@ -161,13 +153,6 @@ namespace MediaBrowser.Model.IO
/// <returns>System.String.</returns> /// <returns>System.String.</returns>
string GetFileNameWithoutExtension(FileSystemMetadata info); string GetFileNameWithoutExtension(FileSystemMetadata info);
/// <summary>
/// Gets the file name without extension.
/// </summary>
/// <param name="path">The path.</param>
/// <returns>System.String.</returns>
string GetFileNameWithoutExtension(string path);
/// <summary> /// <summary>
/// Determines whether [is path file] [the specified path]. /// Determines whether [is path file] [the specified path].
/// </summary> /// </summary>
@ -181,13 +166,6 @@ namespace MediaBrowser.Model.IO
/// <param name="path">The path.</param> /// <param name="path">The path.</param>
void DeleteFile(string path); void DeleteFile(string path);
/// <summary>
/// Deletes the directory.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="recursive">if set to <c>true</c> [recursive].</param>
void DeleteDirectory(string path, bool recursive);
/// <summary> /// <summary>
/// Gets the directories. /// Gets the directories.
/// </summary> /// </summary>
@ -211,86 +189,6 @@ namespace MediaBrowser.Model.IO
/// <returns>IEnumerable&lt;FileSystemMetadata&gt;.</returns> /// <returns>IEnumerable&lt;FileSystemMetadata&gt;.</returns>
IEnumerable<FileSystemMetadata> GetFileSystemEntries(string path, bool recursive = false); IEnumerable<FileSystemMetadata> GetFileSystemEntries(string path, bool recursive = false);
/// <summary>
/// Creates the directory.
/// </summary>
/// <param name="path">The path.</param>
void CreateDirectory(string path);
/// <summary>
/// Copies the file.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="target">The target.</param>
/// <param name="overwrite">if set to <c>true</c> [overwrite].</param>
void CopyFile(string source, string target, bool overwrite);
/// <summary>
/// Moves the file.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="target">The target.</param>
void MoveFile(string source, string target);
/// <summary>
/// Moves the directory.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="target">The target.</param>
void MoveDirectory(string source, string target);
/// <summary>
/// Directories the exists.
/// </summary>
/// <param name="path">The path.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
bool DirectoryExists(string path);
/// <summary>
/// Files the exists.
/// </summary>
/// <param name="path">The path.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
bool FileExists(string path);
/// <summary>
/// Reads all text.
/// </summary>
/// <param name="path">The path.</param>
/// <returns>System.String.</returns>
string ReadAllText(string path);
byte[] ReadAllBytes(string path);
void WriteAllBytes(string path, byte[] bytes);
/// <summary>
/// Writes all text.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="text">The text.</param>
void WriteAllText(string path, string text);
/// <summary>
/// Writes all text.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="text">The text.</param>
/// <param name="encoding">The encoding.</param>
void WriteAllText(string path, string text, Encoding encoding);
/// <summary>
/// Reads all text.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="encoding">The encoding.</param>
/// <returns>System.String.</returns>
string ReadAllText(string path, Encoding encoding);
string[] ReadAllLines(string path);
void WriteAllLines(string path, IEnumerable<string> lines);
/// <summary> /// <summary>
/// Gets the directory paths. /// Gets the directory paths.
/// </summary> /// </summary>
@ -306,6 +204,7 @@ namespace MediaBrowser.Model.IO
/// <param name="recursive">if set to <c>true</c> [recursive].</param> /// <param name="recursive">if set to <c>true</c> [recursive].</param>
/// <returns>IEnumerable&lt;System.String&gt;.</returns> /// <returns>IEnumerable&lt;System.String&gt;.</returns>
IEnumerable<string> GetFilePaths(string path, bool recursive = false); IEnumerable<string> GetFilePaths(string path, bool recursive = false);
IEnumerable<string> GetFilePaths(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive); IEnumerable<string> GetFilePaths(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive);
/// <summary> /// <summary>
@ -319,15 +218,10 @@ namespace MediaBrowser.Model.IO
void SetHidden(string path, bool isHidden); void SetHidden(string path, bool isHidden);
void SetReadOnly(string path, bool readOnly); void SetReadOnly(string path, bool readOnly);
void SetAttributes(string path, bool isHidden, bool readOnly); void SetAttributes(string path, bool isHidden, bool readOnly);
char DirectorySeparatorChar { get; }
string GetFullPath(string path);
List<FileSystemMetadata> GetDrives(); List<FileSystemMetadata> GetDrives();
void SetExecutable(string path); void SetExecutable(string path);
} }
//TODO Investigate if can be replaced by the one from System.IO ? //TODO Investigate if can be replaced by the one from System.IO ?
public enum FileOpenMode public enum FileOpenMode
{ {

View file

@ -156,7 +156,7 @@ namespace MediaBrowser.Providers.BoxSets
var dataFilePath = GetDataFilePath(_config.ApplicationPaths, tmdbId, preferredMetadataLanguage); var dataFilePath = GetDataFilePath(_config.ApplicationPaths, tmdbId, preferredMetadataLanguage);
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(dataFilePath)); Directory.CreateDirectory(Path.GetDirectoryName(dataFilePath));
_json.SerializeToFile(mainResult, dataFilePath); _json.SerializeToFile(mainResult, dataFilePath);
} }

Some files were not shown because too many files have changed in this diff Show more