예제 #1
0
        private void StartNewsLetter(NewletterSettings newletterSettings, bool testEmail = false)
        {
            var embySettings = EmbySettings.GetSettings();

            if (embySettings.Enable)
            {
                var html = EmbyNewsletter.GetNewsletterHtml(testEmail);

                var escapedHtml = new string(html.Where(c => !char.IsControl(c)).ToArray());
                Log.Debug(escapedHtml);
                SendNewsletter(newletterSettings, escapedHtml, testEmail, "New Content On Emby!");
            }
            else
            {
                var plexSettings = PlexSettings.GetSettings();
                if (plexSettings.Enable)
                {
                    var html = PlexNewsletter.GetNewsletterHtml(testEmail);

                    var escapedHtml = new string(html.Where(c => !char.IsControl(c)).ToArray());
                    Log.Debug(escapedHtml);
                    SendNewsletter(newletterSettings, html, testEmail);
                }
            }
        }
예제 #2
0
        private async Task <IEnumerable <UserManagementUsersViewModel> > LoadEmbyUsers()
        {
            var embyDbUsers = await EmbyRepository.GetAllAsync();

            var model = new List <UserManagementUsersViewModel>();

            var userLogins = UserLoginsRepo.GetAll().ToList();

            var embySettings = await EmbySettings.GetSettingsAsync();

            if (!string.IsNullOrEmpty(embySettings.ApiKey))
            {
                //Get Plex Users
                var embyUsers = EmbyApi.GetUsers(embySettings.FullUri, embySettings.ApiKey);
                if (embyUsers != null)
                {
                    foreach (var u in embyUsers)
                    {
                        var dbUser = embyDbUsers.FirstOrDefault(x => x.EmbyUserId == u.Id);
                        var userDb = userLogins.FirstOrDefault(x => x.UserId == u.Id);

                        // We don't have the user in the database yet
                        model.Add(dbUser == null
                            ? MapEmbyUser(u, null, userDb?.LastLoggedIn ?? DateTime.MinValue)
                            : MapEmbyUser(u, dbUser, userDb?.LastLoggedIn ?? DateTime.MinValue));
                    }
                }
            }
            return(model);
        }
예제 #3
0
        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);
        }
예제 #4
0
        private void StartNewsLetter(NewletterSettings newletterSettings, bool testEmail = false)
        {
            var embySettings = EmbySettings.GetSettings();

            if (embySettings.Enable)
            {
                var letter = EmbyNewsletter.GetNewsletter(testEmail) ?? new Newsletter();
                if (letter.Send || testEmail)
                {
                    SendNewsletter(newletterSettings, letter.Html, testEmail, "New Content On Emby!");
                }
                else
                {
                    Log.Warn("There is no new content to send the newsletter");
                }
            }
            else
            {
                var plexSettings = PlexSettings.GetSettings();
                if (plexSettings.Enable)
                {
                    var letter = PlexNewsletter.GetNewsletter(testEmail) ?? new Newsletter();
                    if (letter.Send || testEmail)
                    {
                        SendNewsletter(newletterSettings, letter.Html, testEmail);
                    }
                }
            }
        }
예제 #5
0
        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);
            }
        }
예제 #6
0
        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();
            }
        }
예제 #7
0
 private bool ValidateSettings(EmbySettings emby)
 {
     if (emby.Enable)
     {
         if (emby?.Ip == null || string.IsNullOrEmpty(emby?.ApiKey))
         {
             Log.Warn("A setting is null, Ensure Emby is configured correctly, and we have a Emby Auth token.");
             return(false);
         }
     }
     return(emby.Enable);
 }
예제 #8
0
 private bool ValidateSettings(EmbySettings emby)
 {
     if (emby.Enable)
     {
         if (string.IsNullOrEmpty(emby?.Ip) || string.IsNullOrEmpty(emby?.ApiKey) || string.IsNullOrEmpty(emby?.AdministratorId))
         {
             Log.Warn("A setting is null, Ensure Emby is configured correctly");
             return(false);
         }
     }
     return(emby.Enable);
 }
예제 #9
0
 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);
     }
 }
예제 #10
0
        public async Task <bool> EmbySettings([FromBody] EmbySettings emby)
        {
            if (emby.Enable)
            {
                foreach (var server in emby.Servers)
                {
                    var users = await _embyApi.GetUsers(server.FullUri, server.ApiKey);

                    var admin = users.FirstOrDefault(x => x.Policy.IsAdministrator);
                    server.AdministratorId = admin?.Id;
                }
            }
            var result = await Save(emby);

            return(result);
        }
예제 #11
0
        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."
            }));
        }
예제 #12
0
        private async Task <Response> LoadUsers()
        {
            var plexSettings = await PlexSettings.GetSettingsAsync();

            var embySettings = await EmbySettings.GetSettingsAsync();

            if (plexSettings.Enable)
            {
                return(await LoadPlexUsers());
            }
            if (embySettings.Enable)
            {
                return(await LoadEmbyUsers());
            }

            return(null);
        }
예제 #13
0
        private async Task <Response> ChangeRequestAvailability(int requestId, bool available)
        {
            if (!Security.HasAnyPermissions(User, Permissions.Administrator, Permissions.ManageRequests))
            {
                return(Response.AsJson(new JsonResponseModel {
                    Result = false, Message = "Sorry, you do not have the correct permissions to change a request."
                }));
            }

            Analytics.TrackEventAsync(Category.Requests, Action.Update, available ? "Make request available" : "Make request unavailable", Username, CookieHelper.GetAnalyticClientId(Cookies));
            var originalRequest = await Service.GetAsync(requestId);

            if (originalRequest == null)
            {
                return(Response.AsJson(new JsonResponseModel {
                    Result = false, Message = "Request does not exist to change the availability!"
                }));
            }

            originalRequest.Available = available;

            var result = await Service.UpdateRequestAsync(originalRequest);

            var plexSettings = await PlexSettings.GetSettingsAsync();

            if (plexSettings.Enable)
            {
                await
                PlexNotificationEngine.NotifyUsers(originalRequest,
                                                   available?NotificationType.RequestAvailable : NotificationType.RequestDeclined);
            }

            var embySettings = await EmbySettings.GetSettingsAsync();

            if (embySettings.Enable)
            {
                await EmbyNotificationEngine.NotifyUsers(originalRequest,
                                                         available?NotificationType.RequestAvailable : NotificationType.RequestDeclined);
            }
            return(Response.AsJson(result
                                       ? new { Result = true, Available = available, Message = string.Empty }
                                       : new { Result = false, Available = false, Message = "Could not update the availability, please try again or check the logs" }));
        }
예제 #14
0
        private async Task StartServerCache(EmbyServers server, EmbySettings settings)
        {
            if (!ValidateSettings(server))
            {
                return;
            }

            //await _repo.ExecuteSql("DELETE FROM EmbyEpisode");
            //await _repo.ExecuteSql("DELETE FROM EmbyContent");

            if (server.EmbySelectedLibraries.Any() && server.EmbySelectedLibraries.Any(x => x.Enabled))
            {
                var movieLibsToFilter = server.EmbySelectedLibraries.Where(x => x.Enabled && x.CollectionType == "movies");

                foreach (var movieParentIdFilder in movieLibsToFilter)
                {
                    _logger.LogInformation($"Scanning Lib '{movieParentIdFilder.Title}'");
                    await ProcessMovies(server, movieParentIdFilder.Key);
                }

                var tvLibsToFilter = server.EmbySelectedLibraries.Where(x => x.Enabled && x.CollectionType == "tvshows");
                foreach (var tvParentIdFilter in tvLibsToFilter)
                {
                    _logger.LogInformation($"Scanning Lib '{tvParentIdFilter.Title}'");
                    await ProcessTv(server, tvParentIdFilter.Key);
                }


                var mixedLibs = server.EmbySelectedLibraries.Where(x => x.Enabled && x.CollectionType == "mixed");
                foreach (var m in mixedLibs)
                {
                    _logger.LogInformation($"Scanning Lib '{m.Title}'");
                    await ProcessTv(server, m.Key);
                    await ProcessMovies(server, m.Key);
                }
            }
            else
            {
                await ProcessMovies(server);
                await ProcessTv(server);
            }
        }
예제 #15
0
        private async Task <Response> LoadUsers()
        {
            var model        = new List <UserManagementUsersViewModel>();
            var plexSettings = await PlexSettings.GetSettingsAsync();

            var embySettings = await EmbySettings.GetSettingsAsync();

            if (plexSettings.Enable)
            {
                model.AddRange(await LoadPlexUsers());
            }
            if (embySettings.Enable)
            {
                model.AddRange(await LoadEmbyUsers());
            }

            model.AddRange(await LoadLocalUsers());

            return(Response.AsJson(model));
        }
예제 #16
0
        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));
        }
예제 #17
0
        public async Task <bool> EmbySettings([FromBody] EmbySettings emby)
        {
            if (emby.Enable)
            {
                var client = await _embyApi.CreateClient();

                foreach (var server in emby.Servers)
                {
                    var users = await client.GetUsers(server.FullUri, server.ApiKey);

                    var admin = users.FirstOrDefault(x => x.Policy.IsAdministrator);
                    server.AdministratorId = admin?.Id;
                }
            }
            var result = await Save(emby);

            if (result)
            {
                await OmbiQuartz.TriggerJob(nameof(IEmbyContentSync), "Emby");
            }
            return(result);
        }
예제 #18
0
        private string GetHtml(bool test)
        {
            var sb           = new StringBuilder();
            var embySettings = EmbySettings.GetSettings();

            var embyContent = Content.GetAll().ToList();

            var series   = embyContent.Where(x => x.Type == EmbyMediaType.Series).ToList();
            var episodes = Episodes.GetAll().ToList();
            var movie    = embyContent.Where(x => x.Type == EmbyMediaType.Movie).ToList();

            var recentlyAdded = RecentlyAddedLog.GetAll().ToList();

            var firstRun = !recentlyAdded.Any();

            var filteredMovies = movie.Where(m => recentlyAdded.All(x => x.ProviderId != m.ProviderId)).ToList();
            var filteredEp     = episodes.Where(m => recentlyAdded.All(x => x.ProviderId != m.ProviderId)).ToList();


            var info = new List <EmbyRecentlyAddedModel>();

            foreach (var m in filteredMovies)
            {
                var i = Api.GetInformation(m.EmbyId, Ombi.Api.Models.Emby.EmbyMediaType.Movie,
                                           embySettings.ApiKey, embySettings.AdministratorId, embySettings.FullUri);
                info.Add(new EmbyRecentlyAddedModel
                {
                    EmbyInformation = i,
                    EmbyContent     = m
                });
            }
            GenerateMovieHtml(info, sb);

            info.Clear();
            foreach (var t in series)
            {
                var i = Api.GetInformation(t.EmbyId, Ombi.Api.Models.Emby.EmbyMediaType.Series,
                                           embySettings.ApiKey, embySettings.AdministratorId, embySettings.FullUri);
                var ep = filteredEp.Where(x => x.ParentId == t.EmbyId);

                if (ep.Any())
                {
                    var episodeList = new List <EmbyEpisodeInformation>();
                    foreach (var embyEpisodese in ep)
                    {
                        var epInfo = Api.GetInformation(embyEpisodese.EmbyId, Ombi.Api.Models.Emby.EmbyMediaType.Episode,
                                                        embySettings.ApiKey, embySettings.AdministratorId, embySettings.FullUri);
                        episodeList.Add(epInfo.EpisodeInformation);
                    }
                    info.Add(new EmbyRecentlyAddedModel
                    {
                        EmbyContent        = t,
                        EmbyInformation    = i,
                        EpisodeInformation = episodeList
                    });
                }
            }
            GenerateTvHtml(info, sb);

            var template = new RecentlyAddedTemplate();
            var html     = template.LoadTemplate(sb.ToString());

            Log.Debug("Loaded the template");

            if (!test || firstRun)
            {
                foreach (var a in filteredMovies)
                {
                    RecentlyAddedLog.Insert(new RecentlyAddedLog
                    {
                        ProviderId = a.ProviderId,
                        AddedAt    = DateTime.UtcNow
                    });
                }
                foreach (var a in filteredEp)
                {
                    RecentlyAddedLog.Insert(new RecentlyAddedLog
                    {
                        ProviderId = a.ProviderId,
                        AddedAt    = DateTime.UtcNow
                    });
                }
            }

            var escapedHtml = new string(html.Where(c => !char.IsControl(c)).ToArray());

            Log.Debug(escapedHtml);
            return(escapedHtml);
        }
예제 #19
0
        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);
            }
        }
예제 #20
0
        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");
            }
        }
예제 #21
0
        private Newsletter GetHtml(bool test)
        {
            var sb         = new StringBuilder();
            var newsletter = new Newsletter();

            var embySettings = EmbySettings.GetSettings();
            var embyContent  = Content.GetAll().ToList();

            var series   = embyContent.Where(x => x.Type == EmbyMediaType.Series).ToList();
            var episodes = Episodes.GetAll().ToList();
            var movie    = embyContent.Where(x => x.Type == EmbyMediaType.Movie).ToList();

            var recentlyAdded = RecentlyAddedLog.GetAll().ToList();

            var firstRun = !recentlyAdded.Any();

            var filteredMovies = movie.Where(m => recentlyAdded.All(x => x.ProviderId != m.EmbyId)).ToList();
            var filteredEp     = episodes.Where(m => recentlyAdded.All(x => x.ProviderId != m.EmbyId)).ToList();
            var filteredSeries = series.Where(m => recentlyAdded.All(x => x.ProviderId != m.EmbyId)).ToList();

            var info = new List <EmbyRecentlyAddedModel>();

            foreach (var m in filteredMovies.OrderByDescending(x => x.AddedAt))
            {
                var policy = RetryHandler.RetryAndWaitPolicy((exception, timespan) =>
                                                             Log.Error(exception, "Exception thrown when processing an emby movie for the newsletter, Retrying {0}", timespan));
                var result = policy.Execute(() =>
                {
                    var i = Api.GetInformation(m.EmbyId, Ombi.Api.Models.Emby.EmbyMediaType.Movie,
                                               embySettings.ApiKey, embySettings.AdministratorId, embySettings.FullUri);

                    return(new EmbyRecentlyAddedModel
                    {
                        EmbyInformation = i,
                        EmbyContent = m
                    });
                });
                info.Add(result);
            }
            GenerateMovieHtml(info, sb);
            newsletter.MovieCount = info.Count;

            info.Clear();

            // Check if there are any epiosdes, then get the series info.
            // Otherwise then just add the series to the newsletter
            if (test && !filteredEp.Any() && episodes.Any())
            {
                // if this is a test make sure we show something
                filteredEp = episodes.Take(5).ToList();
            }
            if (filteredEp.Any())
            {
                var recentlyAddedModel = new List <EmbyRecentlyAddedModel>();
                foreach (var embyEpisodes in filteredEp)
                {
                    try
                    {
                        var policy = RetryHandler.RetryAndWaitPolicy((exception, timespan) =>
                                                                     Log.Error(exception, "Exception thrown when processing an emby episode for the newsletter, Retrying {0}", timespan));

                        policy.Execute(() =>
                        {
                            // Find related series item
                            var relatedSeries = series.FirstOrDefault(x => x.EmbyId == embyEpisodes.ParentId);

                            if (relatedSeries == null)
                            {
                                return;
                            }

                            // Get series information
                            var i = Api.GetInformation(relatedSeries.EmbyId, Ombi.Api.Models.Emby.EmbyMediaType.Series,
                                                       embySettings.ApiKey, embySettings.AdministratorId, embySettings.FullUri);

                            Thread.Sleep(200);
                            var episodeInfo = Api.GetInformation(embyEpisodes.EmbyId,
                                                                 Ombi.Api.Models.Emby.EmbyMediaType.Episode,
                                                                 embySettings.ApiKey, embySettings.AdministratorId, embySettings.FullUri);

                            // Check if we already have this series
                            var existingSeries = recentlyAddedModel.FirstOrDefault(x =>
                                                                                   x.EmbyInformation.SeriesInformation.Id.Equals(i.SeriesInformation.Id,
                                                                                                                                 StringComparison.CurrentCultureIgnoreCase));

                            if (existingSeries != null)
                            {
                                existingSeries.EpisodeInformation.Add(episodeInfo.EpisodeInformation);
                            }
                            else
                            {
                                recentlyAddedModel.Add(new EmbyRecentlyAddedModel
                                {
                                    EmbyInformation    = i,
                                    EpisodeInformation = new List <EmbyEpisodeInformation>()
                                    {
                                        episodeInfo.EpisodeInformation
                                    },
                                    EmbyContent = relatedSeries
                                });
                            }
                        });
                    }
                    catch (JsonReaderException)
                    {
                        Log.Error("Failed getting information from Emby, we may have overloaded Emby's api... Waiting and we will skip this one and go to the next");
                        Thread.Sleep(1000);
                    }
                }

                info.AddRange(recentlyAddedModel);
            }
            else
            {
                foreach (var t in filteredSeries.OrderByDescending(x => x.AddedAt))
                {
                    var policy = RetryHandler.RetryAndWaitPolicy((exception, timespan) =>
                                                                 Log.Error(exception, "Exception thrown when processing an emby series for the newsletter, Retrying {0}", timespan));
                    var item = policy.Execute(() =>
                    {
                        var i = Api.GetInformation(t.EmbyId, Ombi.Api.Models.Emby.EmbyMediaType.Series,
                                                   embySettings.ApiKey, embySettings.AdministratorId, embySettings.FullUri);
                        var model = new EmbyRecentlyAddedModel
                        {
                            EmbyContent     = t,
                            EmbyInformation = i,
                        };
                        return(model);
                    });
                    info.Add(item);
                }
            }
            GenerateTvHtml(info, sb);
            newsletter.TvCount = info.Count;


            var template = new RecentlyAddedTemplate();
            var html     = template.LoadTemplate(sb.ToString());

            Log.Debug("Loaded the template");

            if (!test || firstRun)
            {
                foreach (var a in filteredMovies)
                {
                    RecentlyAddedLog.Insert(new RecentlyAddedLog
                    {
                        ProviderId = a.EmbyId,
                        AddedAt    = DateTime.UtcNow
                    });
                }
                foreach (var a in filteredEp)
                {
                    RecentlyAddedLog.Insert(new RecentlyAddedLog
                    {
                        ProviderId = a.EmbyId,
                        AddedAt    = DateTime.UtcNow
                    });
                }
                foreach (var s in filteredSeries)
                {
                    RecentlyAddedLog.Insert(new RecentlyAddedLog
                    {
                        ProviderId = s.EmbyId,
                        AddedAt    = DateTime.UtcNow
                    });
                }
            }


            var escapedHtml = new string(html.Where(c => !char.IsControl(c)).ToArray());

            Log.Debug(escapedHtml);
            newsletter.Html = escapedHtml;
            return(newsletter);
        }
예제 #22
0
 public IEmbyApi CreateClient(EmbySettings settings)
 {
     return(new EmbyApi(_api));
 }
예제 #23
0
        private async Task <string> BuildHtml(IQueryable <PlexServerContent> plexContentToSend, IQueryable <EmbyContent> embyContentToSend,
                                              HashSet <PlexEpisode> plexEpisodes, HashSet <EmbyEpisode> embyEp, HashSet <LidarrAlbumCache> albums, NewsletterSettings settings, EmbySettings embySettings,
                                              PlexSettings plexSettings)
        {
            var ombiSettings = await _ombiSettings.GetSettingsAsync();

            var sb = new StringBuilder();

            var plexMovies = plexContentToSend.Where(x => x.Type == PlexMediaTypeEntity.Movie);
            var embyMovies = embyContentToSend.Where(x => x.Type == EmbyMediaType.Movie);

            if ((plexMovies.Any() || embyMovies.Any()) && !settings.DisableMovies)
            {
                sb.Append("<h1 style=\"text-align: center; max-width: 1042px;\">New Movies</h1><br /><br />");
                sb.Append(
                    "<table class=\"movies-table\" style=\"border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%; \">");
                sb.Append("<tr>");
                sb.Append("<td style=\"font-family: 'Open Sans', Helvetica, Arial, sans-serif; font-size: 14px; vertical-align: top; \">");
                sb.Append("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%; \">");
                sb.Append("<tr>");
                if (plexSettings.Enable)
                {
                    await ProcessPlexMovies(plexMovies, sb, ombiSettings.DefaultLanguageCode);
                }

                if (embySettings.Enable)
                {
                    await ProcessEmbyMovies(embyMovies, sb, ombiSettings.DefaultLanguageCode);
                }

                sb.Append("</tr>");
                sb.Append("</table>");
                sb.Append("</td>");
                sb.Append("</tr>");
                sb.Append("</table>");
            }

            if ((plexEpisodes.Any() || embyEp.Any()) && !settings.DisableTv)
            {
                sb.Append("<br /><br /><h1 style=\"text-align: center; max-width: 1042px;\">New TV</h1><br /><br />");
                sb.Append(
                    "<table class=\"tv-table\" style=\"border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%; \">");
                sb.Append("<tr>");
                sb.Append("<td style=\"font-family: 'Open Sans', Helvetica, Arial, sans-serif; font-size: 14px; vertical-align: top; \">");
                sb.Append("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%; \">");
                sb.Append("<tr>");
                if (plexSettings.Enable)
                {
                    await ProcessPlexTv(plexEpisodes, sb);
                }

                if (embySettings.Enable)
                {
                    await ProcessEmbyTv(embyEp, sb);
                }

                sb.Append("</tr>");
                sb.Append("</table>");
                sb.Append("</td>");
                sb.Append("</tr>");
                sb.Append("</table>");
            }


            if (albums.Any() && !settings.DisableMusic)
            {
                sb.Append("<h1 style=\"text-align: center; max-width: 1042px;\">New Albums</h1><br /><br />");
                sb.Append(
                    "<table class=\"movies-table\" style=\"border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%; \">");
                sb.Append("<tr>");
                sb.Append("<td style=\"font-family: 'Open Sans', Helvetica, Arial, sans-serif; font-size: 14px; vertical-align: top; \">");
                sb.Append("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%; \">");
                sb.Append("<tr>");
                await ProcessAlbums(albums, sb);

                sb.Append("</tr>");
                sb.Append("</table>");
                sb.Append("</td>");
                sb.Append("</tr>");
                sb.Append("</table>");
            }

            return(sb.ToString());
        }
예제 #24
0
        private async Task StartServerCache(EmbyServers server, EmbySettings settings)
        {
            if (!ValidateSettings(server))
            {
                return;
            }

            //await _repo.ExecuteSql("DELETE FROM EmbyEpisode");
            //await _repo.ExecuteSql("DELETE FROM EmbyContent");

            var movies = await _api.GetAllMovies(server.ApiKey, 0, 200, server.AdministratorId, server.FullUri);

            var totalCount = movies.TotalRecordCount;
            var processed  = 1;

            var mediaToAdd = new HashSet <EmbyContent>();

            while (processed < totalCount)
            {
                foreach (var movie in movies.Items)
                {
                    if (movie.Type.Equals("boxset", StringComparison.InvariantCultureIgnoreCase))
                    {
                        var movieInfo =
                            await _api.GetCollection(movie.Id, server.ApiKey, server.AdministratorId, server.FullUri);

                        foreach (var item in movieInfo.Items)
                        {
                            await ProcessMovies(item, mediaToAdd, server);
                        }

                        processed++;
                    }
                    else
                    {
                        processed++;
                        // Regular movie
                        await ProcessMovies(movie, mediaToAdd, server);
                    }
                }

                // Get the next batch
                movies = await _api.GetAllMovies(server.ApiKey, processed, 200, server.AdministratorId, server.FullUri);

                await _repo.AddRange(mediaToAdd);

                mediaToAdd.Clear();
            }


            // TV Time
            var tv = await _api.GetAllShows(server.ApiKey, 0, 200, server.AdministratorId, server.FullUri);

            var totalTv = tv.TotalRecordCount;

            processed = 1;
            while (processed < totalTv)
            {
                foreach (var tvShow in tv.Items)
                {
                    try
                    {
                        processed++;
                        if (string.IsNullOrEmpty(tvShow.ProviderIds?.Tvdb))
                        {
                            _logger.LogInformation("Provider Id on tv {0} is null", tvShow.Name);
                            continue;
                        }

                        var existingTv = await _repo.GetByEmbyId(tvShow.Id);

                        if (existingTv == null)
                        {
                            _logger.LogDebug("Adding new TV Show {0}", tvShow.Name);
                            mediaToAdd.Add(new EmbyContent
                            {
                                TvDbId       = tvShow.ProviderIds?.Tvdb,
                                ImdbId       = tvShow.ProviderIds?.Imdb,
                                TheMovieDbId = tvShow.ProviderIds?.Tmdb,
                                Title        = tvShow.Name,
                                Type         = EmbyMediaType.Series,
                                EmbyId       = tvShow.Id,
                                Url          = EmbyHelper.GetEmbyMediaUrl(tvShow.Id, server.ServerHostname, settings.IsJellyfin),
                                AddedAt      = DateTime.UtcNow
                            });
                        }
                        else
                        {
                            _logger.LogDebug("We already have TV Show {0}", tvShow.Name);
                        }
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
                // Get the next batch
                tv = await _api.GetAllShows(server.ApiKey, processed, 200, server.AdministratorId, server.FullUri);

                await _repo.AddRange(mediaToAdd);

                mediaToAdd.Clear();
            }

            if (mediaToAdd.Any())
            {
                await _repo.AddRange(mediaToAdd);
            }
        }
예제 #25
0
        // 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");
            }
        }
예제 #26
0
 private async Task StartEmby(EmbySettings s)
 {
     await StartEmbyMovies(s);
     await StartEmbyTv();
 }
예제 #27
0
 private async Task StartEmby(EmbySettings s)
 {
     EmbyApi = _embyApiFactory.CreateClient(s);
     await StartEmbyMovies(s);
     await StartEmbyTv();
 }
예제 #28
0
        private async Task <Response> UsernameLogin()
        {
            var username       = Request.Form.username.Value;
            var dateTimeOffset = Request.Form.DateTimeOffset;
            var loginGuid      = Guid.Empty;
            var settings       = await AuthService.GetSettingsAsync();

            if (string.IsNullOrWhiteSpace(username) || IsUserInDeniedList(username, settings))
            {
                return(Response.AsJson(new { result = false, message = Resources.UI.UserLogin_IncorrectUserPass }));
            }

            var plexSettings = await PlexSettings.GetSettingsAsync();

            var embySettings = await EmbySettings.GetSettingsAsync();

            var      authenticated = false;
            var      isOwner       = false;
            var      userId        = string.Empty;
            EmbyUser embyUser      = null;

            if (plexSettings.Enable)
            {
                if (settings.UserAuthentication) // Check against the users in Plex
                {
                    try
                    {
                        Log.Debug("Need to auth");
                        authenticated = CheckIfUserIsInPlexFriends(username, plexSettings.PlexAuthToken);
                        if (authenticated)
                        {
                            userId = GetUserIdIsInPlexFriends(username, plexSettings.PlexAuthToken);
                        }
                        if (CheckIfUserIsOwner(plexSettings.PlexAuthToken, username))
                        {
                            Log.Debug("User is the account owner");
                            authenticated = true;
                            isOwner       = true;
                            userId        = GetOwnerId(plexSettings.PlexAuthToken, username);
                        }
                        Log.Debug("Friends list result = {0}", authenticated);
                    }
                    catch (Exception)
                    {
                        return(Response.AsJson(new { result = false, message = Resources.UI.UserLogin_IncorrectUserPass }));
                    }
                }
                else if (!settings.UserAuthentication) // No auth, let them pass!
                {
                    authenticated = true;
                }
            }
            if (embySettings.Enable)
            {
                if (settings.UserAuthentication) // Check against the users in Plex
                {
                    Log.Debug("Need to auth");
                    authenticated = CheckIfEmbyUser(username, embySettings);
                    if (authenticated)
                    {
                        embyUser = GetEmbyUser(username, embySettings);
                        userId   = embyUser?.Id;
                    }
                    if (embyUser?.Policy?.IsAdministrator ?? false)
                    {
                        Log.Debug("User is the account owner");
                        authenticated = true;
                        isOwner       = true;
                    }
                    Log.Debug("Friends list result = {0}", authenticated);
                }
                else if (!settings.UserAuthentication) // No auth, let them pass!
                {
                    authenticated = true;
                }
            }

            UsersModel dbUser = await IsDbuser(username);

            if (dbUser != null) // in the db?
            {
                var perms = (Permissions)dbUser.Permissions;
                authenticated = true;
                isOwner       = perms.HasFlag(Permissions.Administrator);
                userId        = dbUser.UserGuid;
            }

            if (settings.UsePassword || isOwner || Security.HasPermissions(username, Permissions.Administrator))
            {
                Session[SessionKeys.UserLoginName] = username;

                var path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Views", "UserLogin");
                var file = System.IO.Directory.GetFiles(path).FirstOrDefault(x => x.Contains("Password.cshtml"));
                var html = File.ReadAllText(file);

                return(Response.AsJson(new { result = true, usePassword = true, html }));
            }

            if (!authenticated)
            {
                return(Response.AsJson(new { result = false, message = Resources.UI.UserLogin_IncorrectUserPass }));
            }
            var result = 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 (loginGuid != Guid.Empty)
                    {
                        return(CustomModuleExtensions.LoginAndRedirect(this, result.LoginGuid, null, uri.ToString()));
                    }
                    return(Response.AsRedirect(uri.ToString()));
                }
            }


            var retVal = Linker.BuildRelativeUri(Context, "SearchIndex");

            if (result.LoginGuid != Guid.Empty)
            {
                return(CustomModuleExtensions.LoginAndRedirect(this, result.LoginGuid, null, retVal.ToString()));
            }
            return(Response.AsJson(new { result = true, url = retVal.ToString() }));
        }
예제 #29
0
        private async Task <Response> UpdateUser()
        {
            Analytics.TrackEventAsync(Category.UserManagement, Action.Update, "Updated User", Username, CookieHelper.GetAnalyticClientId(Cookies));
            var body = Request.Body.AsString();

            if (string.IsNullOrEmpty(body))
            {
                return(Response.AsJson(new JsonResponseModel {
                    Result = false, Message = "Could not save user, invalid JSON body"
                }));
            }

            var model = JsonConvert.DeserializeObject <UserManagementUpdateModel>(body);

            if (string.IsNullOrWhiteSpace(model.Id))
            {
                return(Response.AsJson(new JsonResponseModel
                {
                    Result = true,
                    Message = "Couldn't find the user"
                }));
            }

            var permissionsValue = model.Permissions.Where(c => c.Selected).Sum(c => c.Value);
            var featuresValue    = model.Features.Where(c => c.Selected).Sum(c => c.Value);

            Guid outId;

            Guid.TryParse(model.Id, out outId);
            var localUser = UserMapper.GetUser(outId);

            // Update Local User
            if (localUser != null)
            {
                localUser.Permissions = permissionsValue;
                localUser.Features    = featuresValue;

                var currentProps = ByteConverterHelper.ReturnObject <UserProperties>(localUser.UserProperties);

                // Let's check if the alias has changed, if so we need to change all the requests associated with this
                await UpdateRequests(localUser.UserName, currentProps.UserAlias, model.Alias);

                currentProps.UserAlias    = model.Alias;
                currentProps.EmailAddress = model.EmailAddress;

                localUser.UserProperties = ByteConverterHelper.ReturnBytes(currentProps);

                var user    = UserMapper.EditUser(localUser);
                var dbUser  = UserLoginsRepo.GetAll().FirstOrDefault(x => x.UserId == user.UserGuid);
                var retUser = MapLocalUser(user, dbUser?.LastLoggedIn ?? DateTime.MinValue);
                return(Response.AsJson(retUser));
            }

            var plexSettings = await PlexSettings.GetSettingsAsync();

            if (plexSettings.Enable)
            {
                var plexDbUsers = await PlexUsersRepository.GetAllAsync();

                var plexUsers  = PlexApi.GetUsers(plexSettings.PlexAuthToken);
                var plexDbUser = plexDbUsers.FirstOrDefault(x => x.PlexUserId == model.Id);
                var plexUser   = plexUsers.User.FirstOrDefault(x => x.Id == model.Id);
                var userLogin  = UserLoginsRepo.GetAll().FirstOrDefault(x => x.UserId == model.Id);
                if (plexDbUser != null && plexUser != null)
                {
                    // We have a user in the DB for this Plex Account
                    plexDbUser.Permissions = permissionsValue;
                    plexDbUser.Features    = featuresValue;

                    await UpdateRequests(plexDbUser.Username, plexDbUser.UserAlias, model.Alias);

                    plexDbUser.UserAlias    = model.Alias;
                    plexDbUser.EmailAddress = model.EmailAddress;

                    await PlexUsersRepository.UpdateAsync(plexDbUser);

                    var retUser = MapPlexUser(plexUser, plexDbUser, userLogin?.LastLoggedIn ?? DateTime.MinValue);
                    return(Response.AsJson(retUser));
                }

                // So it could actually be the admin
                var account = PlexApi.GetAccount(plexSettings.PlexAuthToken);
                if (plexDbUser != null && account != null)
                {
                    // We have a user in the DB for this Plex Account
                    plexDbUser.Permissions = permissionsValue;
                    plexDbUser.Features    = featuresValue;

                    await UpdateRequests(plexDbUser.Username, plexDbUser.UserAlias, model.Alias);

                    plexDbUser.UserAlias = model.Alias;

                    await PlexUsersRepository.UpdateAsync(plexDbUser);

                    var retUser = MapPlexAdmin(account, plexDbUser, userLogin?.LastLoggedIn ?? DateTime.MinValue);
                    return(Response.AsJson(retUser));
                }

                // We have a Plex Account but he's not in the DB
                if (plexUser != null)
                {
                    var user = new PlexUsers
                    {
                        Permissions  = permissionsValue,
                        Features     = featuresValue,
                        UserAlias    = model.Alias,
                        PlexUserId   = plexUser.Id,
                        EmailAddress = plexUser.Email,
                        Username     = plexUser.Title,
                        LoginId      = Guid.NewGuid().ToString()
                    };

                    await PlexUsersRepository.InsertAsync(user);

                    var retUser = MapPlexUser(plexUser, user, userLogin?.LastLoggedIn ?? DateTime.MinValue);
                    return(Response.AsJson(retUser));
                }
            }

            var embySettings = await EmbySettings.GetSettingsAsync();

            if (embySettings.Enable)
            {
                var embyDbUsers = await EmbyRepository.GetAllAsync();

                var embyUsers      = EmbyApi.GetUsers(embySettings.FullUri, embySettings.ApiKey);
                var selectedDbUser = embyDbUsers.FirstOrDefault(x => x.EmbyUserId == model.Id);
                var embyUser       = embyUsers.FirstOrDefault(x => x.Id == model.Id);

                var userLogin = UserLoginsRepo.GetAll().FirstOrDefault(x => x.UserId == model.Id);
                if (selectedDbUser != null && embyUser != null)
                {
                    // We have a user in the DB for this Plex Account
                    selectedDbUser.Permissions = permissionsValue;
                    selectedDbUser.Features    = featuresValue;

                    await UpdateRequests(selectedDbUser.Username, selectedDbUser.UserAlias, model.Alias);

                    selectedDbUser.UserAlias    = model.Alias;
                    selectedDbUser.EmailAddress = model.EmailAddress;

                    await EmbyRepository.UpdateAsync(selectedDbUser);

                    var retUser = MapEmbyUser(embyUser, selectedDbUser, userLogin?.LastLoggedIn ?? DateTime.MinValue);
                    return(Response.AsJson(retUser));
                }
            }
            return(null); // We should never end up here.
        }
예제 #30
0
        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() }));
        }