add db startup error handling

This commit is contained in:
Luke Pulverenti 2017-02-17 16:11:13 -05:00
parent b51f00feb6
commit 36f8eb1149
16 changed files with 307 additions and 61 deletions

View File

@ -863,7 +863,7 @@ namespace Emby.Server.Core
/// </summary>
private void ConfigureNotificationsRepository()
{
var repo = new SqliteNotificationsRepository(LogManager.GetLogger("SqliteNotificationsRepository"), ServerConfigurationManager.ApplicationPaths);
var repo = new SqliteNotificationsRepository(LogManager.GetLogger("SqliteNotificationsRepository"), ServerConfigurationManager.ApplicationPaths, FileSystemManager);
repo.Initialize();

View File

@ -818,30 +818,6 @@ namespace Emby.Server.Implementations.Library
return _userRootFolder;
}
public Guid? FindIdByPath(string path, bool? isFolder)
{
// If this returns multiple items it could be tricky figuring out which one is correct.
// In most cases, the newest one will be and the others obsolete but not yet cleaned up
var query = new InternalItemsQuery
{
Path = path,
IsFolder = isFolder,
SortBy = new[] { ItemSortBy.DateCreated },
SortOrder = SortOrder.Descending,
Limit = 1
};
var id = GetItemIds(query);
if (id.Count == 0)
{
return null;
}
return id[0];
}
public BaseItem FindByPath(string path, bool? isFolder)
{
// If this returns multiple items it could be tricky figuring out which one is correct.

View File

@ -248,6 +248,13 @@ namespace Emby.Server.Implementations.Library
}
}
var isPlayed = request.IsPlayed;
if (parents.OfType<ICollectionFolder>().Any(i => string.Equals(i.CollectionType, CollectionType.Music, StringComparison.OrdinalIgnoreCase)))
{
isPlayed = null;
}
if (parents.Count == 0)
{
parents = user.RootFolder.GetChildren(user, true)
@ -282,7 +289,7 @@ namespace Emby.Server.Implementations.Library
IsVirtualItem = false,
Limit = limit * 5,
SourceTypes = parents.Count == 0 ? new[] { SourceType.Library } : new SourceType[] { },
IsPlayed = request.IsPlayed
IsPlayed = isPlayed
}, parents);
}

View File

@ -1172,7 +1172,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
};
var isAudio = false;
await new LiveStreamHelper(_mediaEncoder, _logger).AddMediaInfoWithProbe(stream, isAudio, false, cancellationToken).ConfigureAwait(false);
await new LiveStreamHelper(_mediaEncoder, _logger).AddMediaInfoWithProbe(stream, isAudio, cancellationToken).ConfigureAwait(false);
return new List<MediaSourceInfo>
{

View File

@ -260,7 +260,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
_logger.Info("Calling recording process.WaitForExit for {0}", _targetPath);
if (_process.WaitForExit(5000))
if (_process.WaitForExit(10000))
{
return;
}

View File

@ -22,7 +22,7 @@ namespace Emby.Server.Implementations.LiveTv
_logger = logger;
}
public async Task AddMediaInfoWithProbe(MediaSourceInfo mediaSource, bool isAudio, bool assumeInterlaced, CancellationToken cancellationToken)
public async Task AddMediaInfoWithProbe(MediaSourceInfo mediaSource, bool isAudio, CancellationToken cancellationToken)
{
var originalRuntime = mediaSource.RunTimeTicks;
@ -96,17 +96,6 @@ namespace Emby.Server.Implementations.LiveTv
videoStream.IsAVC = null;
}
if (assumeInterlaced)
{
foreach (var mediaStream in mediaSource.MediaStreams)
{
if (mediaStream.Type == MediaStreamType.Video)
{
mediaStream.IsInterlaced = true;
}
}
}
// Try to estimate this
mediaSource.InferTotalBitrate(true);
}

View File

@ -126,14 +126,12 @@ namespace Emby.Server.Implementations.LiveTv
var keys = openToken.Split(new[] { StreamIdDelimeter }, 3);
var mediaSourceId = keys.Length >= 3 ? keys[2] : null;
IDirectStreamProvider directStreamProvider = null;
var assumeInterlaced = false;
if (string.Equals(keys[0], typeof(LiveTvChannel).Name, StringComparison.OrdinalIgnoreCase))
{
var info = await _liveTvManager.GetChannelStream(keys[1], mediaSourceId, cancellationToken).ConfigureAwait(false);
stream = info.Item1;
directStreamProvider = info.Item2;
assumeInterlaced = info.Item3;
}
else
{
@ -148,7 +146,7 @@ namespace Emby.Server.Implementations.LiveTv
}
else
{
await new LiveStreamHelper(_mediaEncoder, _logger).AddMediaInfoWithProbe(stream, isAudio, assumeInterlaced, cancellationToken).ConfigureAwait(false);
await new LiveStreamHelper(_mediaEncoder, _logger).AddMediaInfoWithProbe(stream, isAudio, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception ex)

View File

@ -8,6 +8,7 @@ using System.Threading.Tasks;
using Emby.Server.Implementations.Data;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Notifications;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Notifications;
using SQLitePCL.pretty;
@ -16,8 +17,11 @@ namespace Emby.Server.Implementations.Notifications
{
public class SqliteNotificationsRepository : BaseSqliteRepository, INotificationsRepository
{
public SqliteNotificationsRepository(ILogger logger, IServerApplicationPaths appPaths) : base(logger)
protected IFileSystem FileSystem { get; private set; }
public SqliteNotificationsRepository(ILogger logger, IServerApplicationPaths appPaths, IFileSystem fileSystem) : base(logger)
{
FileSystem = fileSystem;
DbFilePath = Path.Combine(appPaths.DataPath, "notifications.db");
}
@ -26,6 +30,22 @@ namespace Emby.Server.Implementations.Notifications
////public event EventHandler<NotificationUpdateEventArgs> NotificationUpdated;
public void Initialize()
{
try
{
InitializeInternal();
}
catch (Exception ex)
{
Logger.ErrorException("Error loading notifications database file. Will reset and retry.", ex);
FileSystem.DeleteFile(DbFilePath);
InitializeInternal();
}
}
private void InitializeInternal()
{
using (var connection = CreateConnection())
{

View File

@ -59,6 +59,7 @@
<Compile Include="IHasDtoOptions.cs" />
<Compile Include="Playback\MediaInfoService.cs" />
<Compile Include="Playback\TranscodingThrottler.cs" />
<Compile Include="Playback\UniversalAudioService.cs" />
<Compile Include="PlaylistService.cs" />
<Compile Include="Reports\Activities\ReportActivitiesBuilder.cs" />
<Compile Include="Reports\Common\HeaderActivitiesMetadata.cs" />

View File

@ -126,14 +126,10 @@ namespace MediaBrowser.Api.Playback
/// <summary>
/// Gets the output file path.
/// </summary>
/// <param name="state">The state.</param>
/// <returns>System.String.</returns>
private string GetOutputFilePath(StreamState state)
private string GetOutputFilePath(StreamState state, string outputFileExtension)
{
var folder = ServerConfigurationManager.ApplicationPaths.TranscodingTempPath;
var outputFileExtension = GetOutputFileExtension(state);
var data = GetCommandLineArguments("dummy\\dummy", state, false);
data += "-" + (state.Request.DeviceId ?? string.Empty);
@ -802,7 +798,7 @@ namespace MediaBrowser.Api.Playback
{
state.User = UserManager.GetUserById(auth.UserId);
}
//if ((Request.UserAgent ?? string.Empty).IndexOf("iphone", StringComparison.OrdinalIgnoreCase) != -1 ||
// (Request.UserAgent ?? string.Empty).IndexOf("ipad", StringComparison.OrdinalIgnoreCase) != -1 ||
// (Request.UserAgent ?? string.Empty).IndexOf("ipod", StringComparison.OrdinalIgnoreCase) != -1)
@ -876,11 +872,16 @@ namespace MediaBrowser.Api.Playback
var container = Path.GetExtension(state.RequestedUrl);
if (string.IsNullOrEmpty(container))
{
container = request.Container;
}
if (string.IsNullOrEmpty(container))
{
container = request.Static ?
state.InputContainer :
(Path.GetExtension(GetOutputFilePath(state)) ?? string.Empty).TrimStart('.');
GetOutputFileExtension(state);
}
state.OutputContainer = (container ?? string.Empty).TrimStart('.');
@ -923,7 +924,10 @@ namespace MediaBrowser.Api.Playback
ApplyDeviceProfileSettings(state);
}
state.OutputFilePath = GetOutputFilePath(state);
var ext = string.IsNullOrWhiteSpace(state.OutputContainer)
? GetOutputFileExtension(state)
: ("." + state.OutputContainer);
state.OutputFilePath = GetOutputFilePath(state, ext);
return state;
}

View File

@ -18,9 +18,6 @@ using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.IO;
using MediaBrowser.Controller.IO;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Services;
using MimeTypes = MediaBrowser.Model.Net.MimeTypes;

View File

@ -146,7 +146,7 @@ namespace MediaBrowser.Api.Playback
Task.WaitAll(task);
}
public async Task<object> Post(GetPostedPlaybackInfo request)
public async Task<PlaybackInfoResponse> GetPlaybackInfo(GetPostedPlaybackInfo request)
{
var authInfo = _authContext.GetAuthorizationInfo(Request);
@ -172,7 +172,14 @@ namespace MediaBrowser.Api.Playback
SetDeviceSpecificData(request.Id, info, profile, authInfo, request.MaxStreamingBitrate ?? profile.MaxStreamingBitrate, request.StartTimeTicks ?? 0, mediaSourceId, request.AudioStreamIndex, request.SubtitleStreamIndex, request.MaxAudioChannels, request.UserId);
}
return ToOptimizedResult(info);
return info;
}
public async Task<object> Post(GetPostedPlaybackInfo request)
{
var result = await GetPlaybackInfo(request).ConfigureAwait(false);
return ToOptimizedResult(result);
}
private T Clone<T>(T obj)

View File

@ -26,8 +26,6 @@ namespace MediaBrowser.Api.Playback.Progressive
[Route("/Audio/{Id}/stream", "HEAD", Summary = "Gets an audio stream")]
public class GetAudioStream : StreamRequest
{
[ApiMember(Name = "Container", Description = "Container", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
public string Container { get; set; }
}
/// <summary>

View File

@ -22,6 +22,9 @@ namespace MediaBrowser.Api.Playback
[ApiMember(Name = "DeviceId", Description = "The device id of the client requesting. Used to stop encoding processes when needed.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
public string DeviceId { get; set; }
[ApiMember(Name = "Container", Description = "Container", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
public string Container { get; set; }
/// <summary>
/// Gets or sets the audio codec.
/// </summary>

View File

@ -0,0 +1,248 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using MediaBrowser.Api.Playback.Hls;
using MediaBrowser.Api.Playback.Progressive;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Devices;
using MediaBrowser.Controller.Dlna;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Net;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Services;
namespace MediaBrowser.Api.Playback
{
public class BaseUniversalRequest
{
/// <summary>
/// Gets or sets the id.
/// </summary>
/// <value>The id.</value>
[ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
public string Id { get; set; }
[ApiMember(Name = "MediaSourceId", Description = "The media version id, if playing an alternate version", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
public string MediaSourceId { get; set; }
[ApiMember(Name = "DeviceId", Description = "The device id of the client requesting. Used to stop encoding processes when needed.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
public string DeviceId { get; set; }
public string Token { get; set; }
public string UserId { get; set; }
public string AudioCodec { get; set; }
public string Container { get; set; }
public int? MaxAudioChannels { get; set; }
public long? MaxStreamingBitrate { get; set; }
[ApiMember(Name = "StartTimeTicks", Description = "Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
public long? StartTimeTicks { get; set; }
}
[Route("/Audio/{Id}/universal.{Container}", "GET", Summary = "Gets an audio stream")]
[Route("/Audio/{Id}/universal", "GET", Summary = "Gets an audio stream")]
[Route("/Audio/{Id}/universal.{Container}", "HEAD", Summary = "Gets an audio stream")]
[Route("/Audio/{Id}/universal", "HEAD", Summary = "Gets an audio stream")]
public class GetUniversalAudioStream : BaseUniversalRequest
{
}
//[Authenticated]
public class UniversalAudioService : BaseApiService
{
public UniversalAudioService(IServerConfigurationManager serverConfigurationManager, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, IDeviceManager deviceManager, ISubtitleEncoder subtitleEncoder, IMediaSourceManager mediaSourceManager, IZipClient zipClient, IJsonSerializer jsonSerializer, IAuthorizationContext authorizationContext, IImageProcessor imageProcessor, INetworkManager networkManager)
{
ServerConfigurationManager = serverConfigurationManager;
UserManager = userManager;
LibraryManager = libraryManager;
IsoManager = isoManager;
MediaEncoder = mediaEncoder;
FileSystem = fileSystem;
DlnaManager = dlnaManager;
DeviceManager = deviceManager;
SubtitleEncoder = subtitleEncoder;
MediaSourceManager = mediaSourceManager;
ZipClient = zipClient;
JsonSerializer = jsonSerializer;
AuthorizationContext = authorizationContext;
ImageProcessor = imageProcessor;
NetworkManager = networkManager;
}
protected IServerConfigurationManager ServerConfigurationManager { get; private set; }
protected IUserManager UserManager { get; private set; }
protected ILibraryManager LibraryManager { get; private set; }
protected IIsoManager IsoManager { get; private set; }
protected IMediaEncoder MediaEncoder { get; private set; }
protected IFileSystem FileSystem { get; private set; }
protected IDlnaManager DlnaManager { get; private set; }
protected IDeviceManager DeviceManager { get; private set; }
protected ISubtitleEncoder SubtitleEncoder { get; private set; }
protected IMediaSourceManager MediaSourceManager { get; private set; }
protected IZipClient ZipClient { get; private set; }
protected IJsonSerializer JsonSerializer { get; private set; }
protected IAuthorizationContext AuthorizationContext { get; private set; }
protected IImageProcessor ImageProcessor { get; private set; }
protected INetworkManager NetworkManager { get; private set; }
public Task<object> Get(GetUniversalAudioStream request)
{
return GetUniversalStream(request, false);
}
public Task<object> Head(GetUniversalAudioStream request)
{
return GetUniversalStream(request, true);
}
private DeviceProfile GetDeviceProfile(GetUniversalAudioStream request)
{
var deviceProfile = new DeviceProfile();
var directPlayProfiles = new List<DirectPlayProfile>();
directPlayProfiles.Add(new DirectPlayProfile
{
Type = DlnaProfileType.Audio,
Container = request.Container
});
deviceProfile.DirectPlayProfiles = directPlayProfiles.ToArray();
deviceProfile.TranscodingProfiles = new[]
{
new TranscodingProfile
{
Type = DlnaProfileType.Audio,
Context = EncodingContext.Streaming,
Container = "ts",
AudioCodec = "aac",
Protocol = "hls"
}
};
return deviceProfile;
}
private async Task<object> GetUniversalStream(GetUniversalAudioStream request, bool isHeadRequest)
{
var deviceProfile = GetDeviceProfile(request);
AuthorizationContext.GetAuthorizationInfo(Request).DeviceId = request.DeviceId;
var mediaInfoService = new MediaInfoService(MediaSourceManager, DeviceManager, LibraryManager, ServerConfigurationManager, NetworkManager, MediaEncoder, UserManager, JsonSerializer, AuthorizationContext)
{
Request = Request
};
var playbackInfoResult = await mediaInfoService.GetPlaybackInfo(new GetPostedPlaybackInfo
{
Id = request.Id,
MaxAudioChannels = request.MaxAudioChannels,
MaxStreamingBitrate = request.MaxStreamingBitrate,
StartTimeTicks = request.StartTimeTicks,
UserId = request.UserId,
DeviceProfile = deviceProfile,
MediaSourceId = request.MediaSourceId
}).ConfigureAwait(false);
var mediaSource = playbackInfoResult.MediaSources[0];
var isStatic = mediaSource.SupportsDirectStream;
if (!isStatic && string.Equals(mediaSource.TranscodingSubProtocol, "hls", StringComparison.OrdinalIgnoreCase))
{
var service = new DynamicHlsService(ServerConfigurationManager,
UserManager,
LibraryManager,
IsoManager,
MediaEncoder,
FileSystem,
DlnaManager,
SubtitleEncoder,
DeviceManager,
MediaSourceManager,
ZipClient,
JsonSerializer,
AuthorizationContext,
NetworkManager)
{
Request = Request
};
var transcodingProfile = deviceProfile.TranscodingProfiles[0];
var newRequest = new GetMasterHlsAudioPlaylist
{
AudioBitRate = isStatic ? (int?)null : Convert.ToInt32(Math.Min(request.MaxStreamingBitrate ?? 192000, int.MaxValue)),
AudioCodec = transcodingProfile.AudioCodec,
Container = ".m3u8",
DeviceId = request.DeviceId,
Id = request.Id,
MaxAudioChannels = request.MaxAudioChannels,
MediaSourceId = mediaSource.Id,
PlaySessionId = playbackInfoResult.PlaySessionId,
StartTimeTicks = request.StartTimeTicks,
Static = isStatic
};
if (isHeadRequest)
{
return service.Head(newRequest);
}
return service.Get(newRequest);
}
else
{
var service = new AudioService(ServerConfigurationManager,
UserManager,
LibraryManager,
IsoManager,
MediaEncoder,
FileSystem,
DlnaManager,
SubtitleEncoder,
DeviceManager,
MediaSourceManager,
ZipClient,
JsonSerializer,
AuthorizationContext,
ImageProcessor)
{
Request = Request
};
var newRequest = new GetAudioStream
{
AudioBitRate = isStatic ? (int?)null : Convert.ToInt32(Math.Min(request.MaxStreamingBitrate ?? 192000, int.MaxValue)),
//AudioCodec = request.AudioCodec,
Container = isStatic ? null : ("." + mediaSource.TranscodingContainer),
DeviceId = request.DeviceId,
Id = request.Id,
MaxAudioChannels = request.MaxAudioChannels,
MediaSourceId = mediaSource.Id,
PlaySessionId = playbackInfoResult.PlaySessionId,
StartTimeTicks = request.StartTimeTicks,
Static = isStatic
};
if (isHeadRequest)
{
return service.Head(newRequest);
}
return service.Get(newRequest);
}
}
}
}

View File

@ -62,8 +62,6 @@ namespace MediaBrowser.Controller.Library
/// <returns>BaseItem.</returns>
BaseItem FindByPath(string path, bool? isFolder);
Guid? FindIdByPath(string path, bool? isFolder);
/// <summary>
/// Gets the artist.
/// </summary>