public async Task <EmbySettings> SignIn([FromBody] EmbySettings request) { // Check if settings exist since we allow anon... var settings = await EmbySettings.GetSettingsAsync(); if (settings?.Servers?.Any() ?? false) { return(null); } var client = await EmbyApi.CreateClient(); request.Enable = true; var firstServer = request.Servers.FirstOrDefault(); // Test that we can connect var result = await client.GetUsers(firstServer.FullUri, firstServer.ApiKey); if (result != null && result.Any()) { firstServer.AdministratorId = result.FirstOrDefault(x => x.Policy.IsAdministrator)?.Id ?? string.Empty; await EmbySettings.SaveSettingsAsync(request); return(request); } return(null); }
public void Start() { JobRecord.SetRunning(true, JobNames.EmbyUserChecker); try { var settings = EmbySettings.GetSettings(); if (string.IsNullOrEmpty(settings.ApiKey) || !settings.Enable) { return; } var embyUsers = EmbyApi.GetUsers(settings.FullUri, settings.ApiKey); var userManagementSettings = UserManagementSettings.GetSettings(); var dbUsers = Repo.GetAll().ToList(); // Regular users foreach (var user in embyUsers) { var dbUser = dbUsers.FirstOrDefault(x => x.EmbyUserId == user.Id); if (dbUser != null) { // we already have a user continue; } // Looks like it's a new user! var m = new EmbyUsers { EmbyUserId = user.Id, Permissions = UserManagementHelper.GetPermissions(userManagementSettings), Features = UserManagementHelper.GetFeatures(userManagementSettings), UserAlias = string.Empty, Username = user.Name, LoginId = Guid.NewGuid().ToString() }; // If it's the admin, give them the admin permission if (user.Policy.IsAdministrator) { if (!((Permissions)m.Permissions).HasFlag(Permissions.Administrator)) { m.Permissions += (int)Permissions.Administrator; } } Repo.Insert(m); } } catch (Exception e) { Log.Error(e); } finally { JobRecord.SetRunning(false, JobNames.EmbyUserChecker); JobRecord.Record(JobNames.EmbyUserChecker); } }
public async Task <PublicInfo> GetServerInfo([FromBody] EmbyServers server) { var client = await EmbyApi.CreateClient(); var result = await client.GetPublicInformation(server.FullUri); return(result); }
private async Task StartEmbyMovies(EmbySettings settings) { var allMovies = await _embyRepo.GetAll().Where(x => x.Type == EmbyMediaType.Movie && (x.TheMovieDbId == null || x.ImdbId == null)).ToListAsync(); foreach (var movie in allMovies) { movie.ImdbId.HasValue(); movie.TheMovieDbId.HasValue(); // Movies don't really use TheTvDb // Check if it even has 1 ID if (!movie.HasImdb && !movie.HasTheMovieDb) { // Ok this sucks, // The only think I can think that has happened is that we scanned Emby before Emby has got the metadata // So let's recheck emby to see if they have got the metadata now // // Yeah your right that does suck - Future Jamie _log.LogInformation($"Movie {movie.Title} does not have a ImdbId or TheMovieDbId, so rechecking emby"); foreach (var server in settings.Servers) { _log.LogInformation($"Checking server {server.Name} for upto date metadata"); var movieInfo = await EmbyApi.GetMovieInformation(movie.EmbyId, server.ApiKey, server.AdministratorId, server.FullUri); if (movieInfo.ProviderIds?.Imdb.HasValue() ?? false) { movie.ImdbId = movieInfo.ProviderIds.Imdb; } if (movieInfo.ProviderIds?.Tmdb.HasValue() ?? false) { movie.TheMovieDbId = movieInfo.ProviderIds.Tmdb; } } } if (!movie.HasImdb) { var imdbId = await GetImdbId(movie.HasTheMovieDb, false, movie.Title, movie.TheMovieDbId, string.Empty, RequestType.Movie); movie.ImdbId = imdbId; _embyRepo.UpdateWithoutSave(movie); } if (!movie.HasTheMovieDb) { var id = await GetTheMovieDbId(false, movie.HasImdb, string.Empty, movie.ImdbId, movie.Title, true); movie.TheMovieDbId = id; _embyRepo.UpdateWithoutSave(movie); } await _embyRepo.SaveChangesAsync(); } }
public async Task <bool> Emby([FromBody] EmbyServers settings) { try { var result = await EmbyApi.GetUsers(settings.FullUri, settings.ApiKey); return(result.Any()); } catch (Exception e) { Log.LogError(LoggingEvents.Api, e, "Could not test Emby"); return(false); } }
private EmbyUser GetEmbyUser(string username, EmbySettings s) { try { var users = EmbyApi.GetUsers(s.FullUri, s.ApiKey); var allUsers = users?.Where(x => !string.IsNullOrEmpty(x.Name)); return(allUsers?.FirstOrDefault(x => x.Name.Equals(username, StringComparison.CurrentCultureIgnoreCase))); } catch (Exception e) { Log.Error(e); return(null); } }
private async Task <Response> EmbyAuth() { var ip = (string)Request.Form.Ip; var port = (int)Request.Form.Port; var apiKey = (string)Request.Form.ApiKey; var ssl = (bool)Request.Form.Ssl; var settings = new EmbySettings { ApiKey = apiKey, Enable = true, Ip = ip, Port = port, Ssl = ssl, }; try { // Test that we can connect var result = EmbyApi.GetUsers(settings.FullUri, apiKey); if (result != null && result.Any()) { settings.AdministratorId = result.FirstOrDefault(x => x.Policy.IsAdministrator)?.Id ?? string.Empty; await EmbySettings.SaveSettingsAsync(settings); return(Response.AsJson(new JsonResponseModel { Result = true })); } } catch (Exception e) { return(Response.AsJson(new JsonResponseModel { Result = false, Message = $"Could not connect to Emby, please check your settings. Error: {e.Message}" })); } return(Response.AsJson(new JsonResponseModel { Result = false, Message = "Could not connect to Emby, please check your settings." })); }
public async Task <EmbyItemContainer <MediaFolders> > GetLibaries([FromBody] EmbyServers server) { var client = await EmbyApi.CreateClient(); var result = await client.GetLibraries(server.ApiKey, server.FullUri); var mediaFolders = new EmbyItemContainer <MediaFolders> { TotalRecordCount = result.Count, Items = new List <MediaFolders>() }; foreach (var folder in result) { var toAdd = new MediaFolders { Name = folder.Name, Id = folder.ItemId, ServerId = server.ServerId }; var types = folder?.LibraryOptions?.TypeOptions?.Select(x => x.Type); if (!types.Any()) { continue; } if (types.Where(x => x.Equals("Movie", System.StringComparison.InvariantCultureIgnoreCase) || x.Equals("Episode", System.StringComparison.InvariantCultureIgnoreCase)).Count() >= 2) { toAdd.CollectionType = "mixed"; } else if (types.Where(x => x.Equals("Movie", System.StringComparison.InvariantCultureIgnoreCase)).Any()) { toAdd.CollectionType = "movies"; } else if (types.Where(x => x.Equals("Episode", System.StringComparison.InvariantCultureIgnoreCase)).Any()) { toAdd.CollectionType = "tvshows"; } mediaFolders.Items.Add(toAdd); } return(mediaFolders); }
private async Task <Response> CheckStatus() { var plexSettings = await PlexSettings.GetSettingsAsync(); if (plexSettings.Enable) { if (string.IsNullOrEmpty(plexSettings.PlexAuthToken) || string.IsNullOrEmpty(plexSettings.Ip)) { return(Response.AsJson(false)); } try { var status = PlexApi.GetStatus(plexSettings.PlexAuthToken, plexSettings.FullUri); return(Response.AsJson(status != null)); } catch (Exception) { return(Response.AsJson(false)); } } var emby = await EmbySettings.GetSettingsAsync(); if (emby.Enable) { if (string.IsNullOrEmpty(emby.AdministratorId) || string.IsNullOrEmpty(emby.Ip)) { return(Response.AsJson(false)); } try { var status = EmbyApi.GetSystemInformation(emby.ApiKey, emby.FullUri); return(Response.AsJson(status?.Version != null)); } catch (Exception) { return(Response.AsJson(false)); } } return(Response.AsJson(false)); }
public async Task <IEnumerable <UsersViewModel> > EmbyUsers() { var vm = new List <UsersViewModel>(); var s = await EmbySettings.GetSettingsAsync(); foreach (var server in s?.Servers ?? new List <EmbyServers>()) { var users = await EmbyApi.GetUsers(server.FullUri, server.ApiKey); if (users != null && users.Any()) { vm.AddRange(users.Select(u => new UsersViewModel { Username = u.Name, Id = u.Id })); } } // Filter out any dupes return(vm.DistinctBy(x => x.Id)); }
public List <EmbyMovieItem> GetMovies() { var settings = Emby.GetSettings(); return(EmbyApi.GetAllMovies(settings.ApiKey, settings.AdministratorId, settings.FullUri).Items); }
private async Task <Response> PasswordLogin() { var password = Request.Form.password.Value; if (string.IsNullOrEmpty(password)) { return(Response.AsJson(new { result = false, message = Resources.UI.UserLogin_IncorrectUserPass })); } var dateTimeOffset = Request.Form.DateTimeOffset; var loginGuid = Guid.Empty; var settings = await AuthService.GetSettingsAsync(); var username = Session[SessionKeys.UserLoginName].ToString(); var authenticated = false; var isOwner = false; var userId = string.Empty; var plexSettings = await PlexSettings.GetSettingsAsync(); var embySettings = await EmbySettings.GetSettingsAsync(); // attempt local login first as it has the least amount of overhead userId = CustomUserMapper.ValidateUser(username, password)?.ToString(); if (userId != null) { authenticated = true; } else if (userId == null && plexSettings.Enable) { if (settings.UserAuthentication) // Authenticate with Plex { Log.Debug("Need to auth and also provide pass"); var signedIn = (PlexAuthentication)PlexApi.SignIn(username, password); if (signedIn.user?.authentication_token != null) { Log.Debug("Correct credentials, checking if the user is account owner or in the friends list"); if (CheckIfUserIsOwner(plexSettings.PlexAuthToken, signedIn.user?.username)) { Log.Debug("User is the account owner"); authenticated = true; isOwner = true; } else { authenticated = CheckIfUserIsInPlexFriends(username, plexSettings.PlexAuthToken); Log.Debug("Friends list result = {0}", authenticated); } userId = signedIn.user.uuid; } } } else if (userId == null && embySettings.Enable) { if (settings.UserAuthentication) // Authenticate with Emby { Log.Debug("Need to auth and also provide pass"); EmbyUser signedIn = null; try { signedIn = (EmbyUser)EmbyApi.LogIn(username, password, embySettings.ApiKey, embySettings.FullUri); } catch (Exception e) { Log.Error(e); } if (signedIn != null) { Log.Debug("Correct credentials, checking if the user is account owner or in the friends list"); if (signedIn?.Policy?.IsAdministrator ?? false) { Log.Debug("User is the account owner"); authenticated = true; isOwner = true; } else { authenticated = CheckIfEmbyUser(username, embySettings); Log.Debug("Friends list result = {0}", authenticated); } userId = signedIn?.Id; } } } if (!authenticated) { return(Response.AsJson(new { result = false, message = Resources.UI.UserLogin_IncorrectUserPass })); } var m = await AuthenticationSetup(userId, username, dateTimeOffset, loginGuid, isOwner, plexSettings.Enable, embySettings.Enable); var landingSettings = await LandingPageSettings.GetSettingsAsync(); if (landingSettings.Enabled) { if (!landingSettings.BeforeLogin) // After Login { var uri = Linker.BuildRelativeUri(Context, "LandingPageIndex"); if (m.LoginGuid != Guid.Empty) { return(CustomModuleExtensions.LoginAndRedirect(this, m.LoginGuid, null, uri.ToString())); } return(Response.AsRedirect(uri.ToString())); } } var retVal = Linker.BuildRelativeUri(Context, "SearchIndex"); if (m.LoginGuid != Guid.Empty) { return(CustomModuleExtensions.LoginAndRedirect(this, m.LoginGuid, null, retVal.ToString())); } return(Response.AsJson(new { result = true, url = retVal.ToString() })); }
private void CachedLibraries(EmbySettings embySettings) { if (!ValidateSettings(embySettings)) { Log.Warn("The settings are not configured"); } try { var movies = GetMovies(); // Delete everything EmbyContent.Custom(connection => { connection.Open(); connection.Query("delete from EmbyContent where type = @type", new { type = 0 }); return(new List <EmbyContent>()); }); foreach (var m in movies) { if (m.Type.Equals("boxset", StringComparison.CurrentCultureIgnoreCase)) { var info = EmbyApi.GetCollection(m.Id, embySettings.ApiKey, embySettings.AdministratorId, embySettings.FullUri); foreach (var item in info.Items) { var movieInfo = EmbyApi.GetInformation(item.Id, EmbyMediaType.Movie, embySettings.ApiKey, embySettings.AdministratorId, embySettings.FullUri).MovieInformation; ProcessMovies(movieInfo); } } else { var movieInfo = EmbyApi.GetInformation(m.Id, EmbyMediaType.Movie, embySettings.ApiKey, embySettings.AdministratorId, embySettings.FullUri).MovieInformation; ProcessMovies(movieInfo); } } var tv = GetTvShows(); // Delete everything EmbyContent.Custom(connection => { connection.Open(); connection.Query("delete from EmbyContent where type = @type", new { type = 1 }); return(new List <EmbyContent>()); }); foreach (var t in tv) { var tvInfo = EmbyApi.GetInformation(t.Id, EmbyMediaType.Series, embySettings.ApiKey, embySettings.AdministratorId, embySettings.FullUri).SeriesInformation; if (string.IsNullOrEmpty(tvInfo.ProviderIds?.Tvdb)) { Log.Error("Provider Id on tv {0} is null", t.Name); continue; } // Check if it exists var item = EmbyContent.Custom(connection => { connection.Open(); var media = connection.QueryFirstOrDefault <EmbyContent>("select * from EmbyContent where ProviderId = @ProviderId and type = @type", new { ProviderId = tvInfo.ProviderIds.Tvdb, type = 1 }); connection.Dispose(); return(media); }); if (item != null && item.EmbyId != t.Id) { // delete this item since the Id has changed EmbyContent.Delete(item); item = null; } if (item == null) { EmbyContent.Insert(new EmbyContent { ProviderId = tvInfo.ProviderIds.Tvdb, PremierDate = tvInfo.PremiereDate, Title = tvInfo.Name, Type = Store.Models.Plex.EmbyMediaType.Series, EmbyId = t.Id, AddedAt = DateTime.UtcNow }); } } //TODO Emby //var albums = GetPlexAlbums(results); //foreach (var a in albums) //{ // if (string.IsNullOrEmpty(a.ProviderId)) // { // Log.Error("Provider Id on album {0} is null", a.Title); // continue; // } // // Check if it exists // var item = EmbyContent.Custom(connection => // { // connection.Open(); // var media = connection.QueryFirstOrDefault<PlexContent>("select * from EmbyContent where ProviderId = @ProviderId and type = @type", new { a.ProviderId, type = 2 }); // connection.Dispose(); // return media; // }); // if (item == null) // { // EmbyContent.Insert(new PlexContent // { // ProviderId = a.ProviderId, // ReleaseYear = a.ReleaseYear ?? string.Empty, // Title = a.Title, // Type = Store.Models.Plex.PlexMediaType.Artist, // Url = a.Url // }); // } //} } catch (Exception ex) { Log.Error(ex, "Failed to obtain Emby libraries"); } }
public List <EmbySeriesItem> GetTvShows() { var settings = Emby.GetSettings(); return(EmbyApi.GetAllShows(settings.ApiKey, settings.AdministratorId, settings.FullUri).Items); }
public async Task NotifyUsers(RequestedModel model, NotificationType type) { try { var embySettings = await EmbySettings.GetSettingsAsync(); var embyUsers = EmbyApi.GetUsers(embySettings.FullUri, embySettings.ApiKey); var userAccount = embyUsers.FirstOrDefault(x => x.Policy.IsAdministrator); var localUsers = UserHelper.GetUsers().ToList(); var adminUsername = userAccount.Name ?? string.Empty; var users = UserHelper.GetUsersWithFeature(Features.RequestAddedNotification).ToList(); Log.Debug("Notifying Users Count {0}", users.Count); // Get the usernames or alias depending if they have an alias var userNamesWithFeature = users.Select(x => x.UsernameOrAlias).ToList(); Log.Debug("Users with the feature count {0}", userNamesWithFeature.Count); Log.Debug("Usernames: "); foreach (var u in userNamesWithFeature) { Log.Debug(u); } Log.Debug("Users in the requested model count: {0}", model.AllUsers.Count); Log.Debug("usernames from model: "); foreach (var modelAllUser in model.AllUsers) { Log.Debug(modelAllUser); } if (model.AllUsers == null || !model.AllUsers.Any()) { Log.Debug("There are no users in the model.AllUsers, no users to notify"); return; } var usersToNotify = userNamesWithFeature.Intersect(model.AllUsers, StringComparer.CurrentCultureIgnoreCase).ToList(); if (!usersToNotify.Any()) { Log.Debug("Could not find any users after the .Intersect()"); } Log.Debug("Users being notified for this request count {0}", users.Count); foreach (var user in usersToNotify) { var embyUser = EmbyUserRepo.GetUserByUsername(user); Log.Info("Notifying user {0}", user); if (user.Equals(adminUsername, StringComparison.CurrentCultureIgnoreCase)) { Log.Info("This user is the Emby server owner"); await PublishUserNotification(userAccount.Name, embyUser.EmailAddress, model.Title, model.PosterPath, type, model.Type); return; } var email = embyUsers.FirstOrDefault(x => x.Name.Equals(user, StringComparison.CurrentCultureIgnoreCase)); if (email == null) { // Local User? var local = localUsers.FirstOrDefault(x => x.UsernameOrAlias.Equals(user)); if (local != null) { Log.Info("Sending notification to: {0} at: {1}, for title: {2}", local.UsernameOrAlias, local.EmailAddress, model.Title); await PublishUserNotification(local.UsernameOrAlias, local.EmailAddress, model.Title, model.PosterPath, type, model.Type); continue; } } Log.Info("Sending notification to: {0} at: {1}, for title: {2}", email.Name, embyUser.EmailAddress, model.Title); await PublishUserNotification(email.Name, embyUser.EmailAddress, model.Title, model.PosterPath, type, model.Type); } } catch (Exception e) { Log.Error(e); } }
public async Task NotifyUsers(IEnumerable <RequestedModel> modelChanged, NotificationType type) { try { var embySettings = await EmbySettings.GetSettingsAsync(); var embyUsers = EmbyApi.GetUsers(embySettings.FullUri, embySettings.ApiKey); var userAccount = embyUsers.FirstOrDefault(x => x.Policy.IsAdministrator); var adminUsername = userAccount?.Name ?? string.Empty; var users = UserHelper.GetUsersWithFeature(Features.RequestAddedNotification).ToList(); Log.Debug("Notifying Users Count {0}", users.Count); foreach (var model in modelChanged) { var selectedUsers = new List <string>(); foreach (var u in users) { var requestUser = model.RequestedUsers.FirstOrDefault( x => x.Equals(u.Username, StringComparison.CurrentCultureIgnoreCase) || x.Equals(u.UserAlias, StringComparison.CurrentCultureIgnoreCase)); if (string.IsNullOrEmpty(requestUser)) { continue; } // Make sure we do not already have the user if (!selectedUsers.Contains(requestUser)) { selectedUsers.Add(requestUser); } } foreach (var user in selectedUsers) { var localUser = users.FirstOrDefault(x => x.Username.Equals(user, StringComparison.CurrentCultureIgnoreCase) || x.UserAlias.Equals(user, StringComparison.CurrentCultureIgnoreCase)); Log.Info("Notifying user {0}", user); if (user.Equals(adminUsername, StringComparison.CurrentCultureIgnoreCase)) { Log.Info("This user is the Plex server owner"); await PublishUserNotification(userAccount?.Name, localUser?.EmailAddress, model.Title, model.PosterPath, type, model.Type); return; } // So if the request was from an alias, then we need to use the local user (since that contains the alias). // If we do not have a local user, then we should be using the Emby user if that user exists. // This will execute most of the time since Emby and Local users will most always be in the database. if (localUser != null) { if (string.IsNullOrEmpty(localUser?.EmailAddress)) { Log.Info("There is no email address for this Local user ({0}), cannot send notification", localUser.Username); continue; } Log.Info("Sending notification to: {0} at: {1}, for : {2}", localUser, localUser.EmailAddress, model.Title); await PublishUserNotification(localUser.Username, localUser.EmailAddress, model.Title, model.PosterPath, type, model.Type); } else { var embyUser = EmbyUserRepo.GetUserByUsername(user); var email = embyUsers.FirstOrDefault(x => x.Name.Equals(user, StringComparison.CurrentCultureIgnoreCase)); if (string.IsNullOrEmpty(embyUser?.EmailAddress)) // TODO this needs to be the email { Log.Info("There is no email address for this Emby user ({0}), cannot send notification", email?.Name); // We do not have a plex user that requested this! continue; } Log.Info("Sending notification to: {0} at: {1}, for : {2}", embyUser?.Username, embyUser?.EmailAddress, model.Title); await PublishUserNotification(email?.Name, embyUser?.EmailAddress, model.Title, model.PosterPath, type, model.Type); } } } } catch (Exception e) { Log.Error(e); } }
// Note, once an episode exists, we store it and it always exists. // We might want to look at checking if something has been removed from the server in the future. public void CacheEpisodes(EmbySettings settings) { var allEpisodes = EmbyApi.GetAllEpisodes(settings.ApiKey, settings.AdministratorId, settings.FullUri); var model = new List <EmbyEpisodes>(); foreach (var ep in allEpisodes.Items) { var epInfo = EmbyApi.GetInformation(ep.Id, EmbyMediaType.Episode, settings.ApiKey, settings.AdministratorId, settings.FullUri); if (epInfo.EpisodeInformation?.ProviderIds?.Tvdb == null) { continue; } // Check it this episode exists var item = Repo.Custom(connection => { connection.Open(); var media = connection.QueryFirstOrDefault <EmbyEpisodes>( "select * from EmbyEpisodes where ProviderId = @ProviderId", new { ProviderId = epInfo.EpisodeInformation?.ProviderIds?.Tvdb }); connection.Dispose(); return(media); }); if (item != null) { if (item.EmbyId != ep.Id) // The id's dont match, delete it { Repo.Delete(item); item = null; } } if (item == null) { // add it model.Add(new EmbyEpisodes { EmbyId = ep.Id, EpisodeNumber = ep.IndexNumber, SeasonNumber = ep.ParentIndexNumber, EpisodeTitle = ep.Name, ParentId = ep.SeriesId, ShowTitle = ep.SeriesName, ProviderId = epInfo.EpisodeInformation.ProviderIds.Tvdb, AddedAt = DateTime.UtcNow }); } } // Insert the new items var result = Repo.BatchInsert(model, TableName); if (!result) { Log.Error("Saving the emby episodes to the DB Failed"); } }