Beispiel #1
0
        public ValidationFailure Test(PlexServerSettings settings)
        {
            try
            {
                var sections = GetSectionKeys(new PlexServerSettings
                {
                    Host     = settings.Host,
                    Port     = settings.Port,
                    Username = settings.Username,
                    Password = settings.Password
                });

                if (sections.Empty())
                {
                    return(new ValidationFailure("Host", "At least one TV library is required"));
                }
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Unable to connect to Plex Server: " + ex.Message, ex);
                return(new ValidationFailure("Host", "Unable to connect to Plex Server"));
            }

            return(null);
        }
Beispiel #2
0
        private void CheckForError(IRestResponse response, PlexServerSettings settings)
        {
            _logger.Trace("Checking for error");

            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                if (settings.Username.IsNullOrWhiteSpace())
                {
                    throw new PlexAuthenticationException("Unauthorized - Username and password required");
                }

                //Set the token to null in the cache so we don't keep trying with bad credentials
                _authCache.Set(settings.Username + settings.Password, null);
                throw new PlexAuthenticationException("Unauthorized - Username or password is incorrect");
            }

            var error = Json.Deserialize <PlexError>(response.Content);

            if (error != null && !error.Error.IsNullOrWhiteSpace())
            {
                throw new PlexException(error.Error);
            }

            _logger.Trace("No error detected");
        }
Beispiel #3
0
        private bool PartialUpdatesAllowed(PlexServerSettings settings)
        {
            try
            {
                var rawVersion = GetVersion(settings);
                var version    = new Version(Regex.Match(rawVersion, @"^(\d+\.){4}").Value.Trim('.'));

                if (version >= new Version(0, 9, 12, 0))
                {
                    var preferences           = GetPreferences(settings);
                    var partialScanPreference = preferences.SingleOrDefault(p => p.Id.Equals("FSEventLibraryPartialScanEnabled"));

                    if (partialScanPreference == null)
                    {
                        return(false);
                    }

                    return(Convert.ToBoolean(partialScanPreference.Value));
                }
            }
            catch (Exception ex)
            {
                _logger.Warn(ex, "Unable to check if partial updates are allowed");
            }

            return(false);
        }
Beispiel #4
0
        public List <PlexSection> GetMovieSections(PlexServerSettings settings)
        {
            var request  = GetPlexServerRequest("library/sections", Method.GET, settings);
            var client   = GetPlexServerClient(settings);
            var response = client.Execute(request);

            _logger.Trace("Sections response: {0}", response.Content);
            CheckForError(response, settings);

            if (response.Content.Contains("_children"))
            {
                return(Json.Deserialize <PlexMediaContainerLegacy>(response.Content)
                       .Sections
                       .Where(d => d.Type == "movie")
                       .Select(s => new PlexSection
                {
                    Id = s.Id,
                    Language = s.Language,
                    Locations = s.Locations,
                    Type = s.Type
                })
                       .ToList());
            }

            return(Json.Deserialize <PlexResponse <PlexSectionsContainer> >(response.Content)
                   .MediaContainer
                   .Sections
                   .Where(d => d.Type == "movie")
                   .ToList());
        }
Beispiel #5
0
        public void UpdateLibrary(Series series, PlexServerSettings settings)
        {
            try
            {
                _logger.Debug("Sending Update Request to Plex Server");

                var version = _versionCache.Get(settings.Host, () => GetVersion(settings), TimeSpan.FromHours(2));
                ValidateVersion(version);

                var sections       = GetSections(settings);
                var partialUpdates = _partialUpdateCache.Get(settings.Host, () => PartialUpdatesAllowed(settings, version), TimeSpan.FromHours(2));

                if (partialUpdates)
                {
                    UpdatePartialSection(series, sections, settings);
                }

                else
                {
                    sections.ForEach(s => UpdateSection(s.Id, settings));
                }
            }

            catch (Exception ex)
            {
                _logger.Warn(ex, "Failed to Update Plex host: " + settings.Host);
                throw;
            }
        }
Beispiel #6
0
        public void UpdateMovieSections(Movie movie, PlexServerSettings settings)
        {
            try
            {
                _logger.Debug("Sending Update Request to Plex Server");

                var version = _versionCache.Get(settings.Host, () => GetVersion(settings), TimeSpan.FromHours(2));
                ValidateVersion(version);

                var sections       = GetSections(settings);
                var partialUpdates = _partialUpdateCache.Get(settings.Host, () => PartialUpdatesAllowed(settings, version), TimeSpan.FromHours(2));

                // TODO: Investiate partial updates later, for now just update all movie sections...

                //if (partialUpdates)
                //{
                //    UpdatePartialSection(series, sections, settings);
                //}

                //else
                //{
                sections.ForEach(s => UpdateSection(s.Id, settings));
                //}
            }

            catch (Exception ex)
            {
                _logger.Warn(ex, "Failed to Update Plex host: " + settings.Host);
                throw;
            }
        }
Beispiel #7
0
        public int?GetMetadataId(int sectionId, int tvdbId, string language, PlexServerSettings settings)
        {
            var guid     = string.Format("com.plexapp.agents.thetvdb://{0}?lang={1}", tvdbId, language);
            var resource = string.Format("library/sections/{0}/all?guid={1}", sectionId, System.Web.HttpUtility.UrlEncode(guid));
            var request  = GetPlexServerRequest(resource, Method.GET, settings);
            var client   = GetPlexServerClient(settings);
            var response = client.Execute(request);

            _logger.Trace("Sections response: {0}", response.Content);
            CheckForError(response, settings);

            List <PlexSectionItem> items;

            if (response.Content.Contains("_children"))
            {
                items = Json.Deserialize <PlexSectionResponseLegacy>(response.Content)
                        .Items;
            }

            else
            {
                items = Json.Deserialize <PlexResponse <PlexSectionResponse> >(response.Content)
                        .MediaContainer
                        .Items;
            }

            if (items == null || items.Empty())
            {
                return(null);
            }

            return(items.First().Id);
        }
Beispiel #8
0
        public void UpdateLibrary(Series series, PlexServerSettings settings)
        {
            try
            {
                _logger.Debug("Sending Update Request to Plex Server");

                var sections = GetSections(settings);

                //TODO: How long should we cache this for?
                var partialUpdates = _partialUpdateCache.Get(settings.Host, () => PartialUpdatesAllowed(settings), TimeSpan.FromHours(2));

                if (partialUpdates)
                {
                    sections.ForEach(s => UpdateSeries(s.Id, series, s.Language, settings));
                }

                else
                {
                    sections.ForEach(s => UpdateSection(s.Id, settings));
                }
            }

            catch (Exception ex)
            {
                _logger.WarnException("Failed to Update Plex host: " + settings.Host, ex);
                throw;
            }
        }
Beispiel #9
0
        public void UpdateSection(PlexServerSettings settings, int key)
        {
            _logger.Trace("Updating Plex host: {0}, Section: {1}", settings.Host, key);
            var url = String.Format("http://{0}:{1}/library/sections/{2}/refresh", settings.Host, settings.Port, key);

            _httpProvider.DownloadString(url);
        }
Beispiel #10
0
        public void Update(int sectionId, PlexServerSettings settings)
        {
            var resource = String.Format("library/sections/{0}/refresh", sectionId);
            var request  = GetPlexServerRequest(resource, Method.GET, settings);
            var client   = GetPlexServerClient(settings);

            var response = client.Execute(request);
        }
Beispiel #11
0
        public void UpdateSeries(int metadataId, PlexServerSettings settings)
        {
            var resource = string.Format("library/metadata/{0}/refresh", metadataId);
            var request  = GetPlexServerRequest(resource, Method.PUT, settings);
            var client   = GetPlexServerClient(settings);
            var response = client.Execute(request);

            _logger.Trace("Update Series response: {0}", response.Content);
            CheckForError(response, settings);
        }
Beispiel #12
0
        public void Update(int sectionId, PlexServerSettings settings)
        {
            var resource = String.Format("library/sections/{0}/refresh", sectionId);
            var request  = GetPlexServerRequest(resource, Method.GET, settings);
            var client   = GetPlexServerClient(settings);
            var response = client.Execute(request);

            _logger.Trace("Update response: {0}", response.Content);
            CheckForError(response, settings);
        }
Beispiel #13
0
        private string GetAuthenticationToken(PlexServerSettings settings)
        {
            var token = _authCache.Get(settings.Username + settings.Password, () => Authenticate(settings));

            if (token.IsNullOrWhiteSpace())
            {
                throw new PlexAuthenticationException("Invalid Token - Update your username and password");
            }

            return(token);
        }
Beispiel #14
0
        public string Version(PlexServerSettings settings)
        {
            var request  = GetPlexServerRequest("identity", Method.GET, settings);
            var client   = GetPlexServerClient(settings);
            var response = client.Execute(request);

            _logger.Trace("Version response: {0}", response.Content);
            CheckForError(response, settings);

            return(Json.Deserialize <PlexIdentity>(response.Content).Version);
        }
Beispiel #15
0
        public List <PlexPreference> Preferences(PlexServerSettings settings)
        {
            var request  = GetPlexServerRequest(":/prefs", Method.GET, settings);
            var client   = GetPlexServerClient(settings);
            var response = client.Execute(request);

            _logger.Trace("Preferences response: {0}", response.Content);
            CheckForError(response, settings);

            return(Json.Deserialize <PlexPreferences>(response.Content).Preferences);
        }
Beispiel #16
0
        public List <int> GetSectionKeys(PlexServerSettings settings)
        {
            _logger.Trace("Getting sections from Plex host: {0}", settings.Host);
            var url            = String.Format("http://{0}:{1}/library/sections", settings.Host, settings.Port);
            var xmlStream      = _httpProvider.DownloadStream(url, null);
            var xDoc           = XDocument.Load(xmlStream);
            var mediaContainer = xDoc.Descendants("MediaContainer").FirstOrDefault();
            var directories    = mediaContainer.Descendants("Directory").Where(x => x.Attribute("type").Value == "show");

            return(directories.Select(d => Int32.Parse(d.Attribute("key").Value)).ToList());
        }
Beispiel #17
0
        private Version GetVersion(PlexServerSettings settings)
        {
            _logger.Debug("Getting version from Plex host: {0}", settings.Host);

            var rawVersion = _plexServerProxy.Version(settings);
            var version    = new Version(Regex.Match(rawVersion, @"^(\d+[.-]){4}").Value.Trim('.', '-'));



            return(version);
        }
Beispiel #18
0
        public List <PlexDirectory> GetTvSections(PlexServerSettings settings)
        {
            var request = GetPlexServerRequest("library/sections", Method.GET, settings);
            var client  = GetPlexServerClient(settings);

            var response = client.Execute(request);

            return(Json.Deserialize <PlexMediaContainer>(response.Content)
                   .Directories
                   .Where(d => d.Type == "show")
                   .ToList());
        }
Beispiel #19
0
        private RestRequest GetPlexServerRequest(string resource, Method method, PlexServerSettings settings)
        {
            var request = new RestRequest(resource, method);

            request.AddHeader("Accept", "application/json");

            if (!settings.Username.IsNullOrWhiteSpace())
            {
                request.AddParameter("X-Plex-Token", GetAuthenticationToken(settings.Username, settings.Password));
            }

            return(request);
        }
Beispiel #20
0
        private string Authenticate(PlexServerSettings settings)
        {
            var request = GetPlexTvRequest("users/sign_in.json", Method.POST);
            var client  = GetPlexTvClient(settings.Username, settings.Password);

            var response = client.Execute(request);

            _logger.Debug("Authentication Response: {0}", response.Content);
            CheckForError(response, settings);

            var user = Json.Deserialize <PlexUser>(JObject.Parse(response.Content).SelectToken("user").ToString());

            return(user.AuthenticationToken);
        }
Beispiel #21
0
        public void UpdateLibrary(PlexServerSettings settings)
        {
            try
            {
                _logger.Trace("Sending Update Request to Plex Server");
                var sections = GetSectionKeys(settings);
                sections.ForEach(s => UpdateSection(settings, s));
            }

            catch (Exception ex)
            {
                _logger.WarnException("Failed to Update Plex host: " + settings.Host, ex);
                throw;
            }
        }
Beispiel #22
0
        private void UpdateSeries(int sectionId, Series series, string language, PlexServerSettings settings)
        {
            _logger.Debug("Updating Plex host: {0}, Section: {1}, Series: {2}", settings.Host, sectionId, series);

            var metadataId = GetMetadataId(sectionId, series, language, settings);

            if (metadataId.HasValue)
            {
                _plexServerProxy.UpdateSeries(metadataId.Value, settings);
            }

            else
            {
                UpdateSection(sectionId, settings);
            }
        }
Beispiel #23
0
        public List <PlexPreference> Preferences(PlexServerSettings settings)
        {
            var request  = GetPlexServerRequest(":/prefs", Method.GET, settings);
            var client   = GetPlexServerClient(settings);
            var response = client.Execute(request);

            _logger.Trace("Preferences response: {0}", response.Content);
            CheckForError(response, settings);

            if (response.Content.Contains("_children"))
            {
                return(Json.Deserialize <PlexPreferencesLegacy>(response.Content)
                       .Preferences);
            }

            return(Json.Deserialize <PlexResponse <PlexPreferences> >(response.Content)
                   .MediaContainer
                   .Preferences);
        }
Beispiel #24
0
        public int?GetMetadataId(int sectionId, int tvdbId, string language, PlexServerSettings settings)
        {
            var guid     = String.Format("com.plexapp.agents.thetvdb://{0}?lang={1}", tvdbId, language);
            var resource = String.Format("library/sections/{0}/all?guid={1}", sectionId, System.Web.HttpUtility.UrlEncode(guid));
            var request  = GetPlexServerRequest(resource, Method.GET, settings);
            var client   = GetPlexServerClient(settings);
            var response = client.Execute(request);

            _logger.Trace("Sections response: {0}", response.Content);
            CheckForError(response, settings);

            var item = Json.Deserialize <PlexSectionResponse>(response.Content)
                       .Items
                       .FirstOrDefault();

            if (item == null)
            {
                return(null);
            }

            return(item.Id);
        }
Beispiel #25
0
        public ValidationFailure Test(PlexServerSettings settings)
        {
            try
            {
                if (!GetSectionKeys(new PlexServerSettings
                {
                    Host = settings.Host,
                    Port = settings.Port,
                    Username = settings.Username,
                    Password = settings.Password
                }).Any())
                {
                    throw new Exception("Unable to connect to Plex Server");
                }
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Unable to connect to Plex Server: " + ex.Message, ex);
                return(new ValidationFailure("Host", "Unable to connect to Plex Server"));
            }

            return(null);
        }
Beispiel #26
0
        private void UpdatePartialSection(Movie movie, List <PlexSection> sections, PlexServerSettings settings)
        {
            var partiallyUpdated = false;

            foreach (var section in sections)
            {
                var metadataId = GetMetadataId(section.Id, movie, section.Language, settings);

                if (metadataId.HasValue)
                {
                    _logger.Debug("Updating Plex host: {0}, Section: {1}, Movie: {2}", settings.Host, section.Id, movie);
                    _plexServerProxy.UpdateItem(metadataId.Value, settings);

                    partiallyUpdated = true;
                }
            }

            // Only update complete sections if all partial updates failed
            if (!partiallyUpdated)
            {
                _logger.Debug("Unable to update partial section, updating all TV sections");
                sections.ForEach(s => UpdateSection(s.Id, settings));
            }
        }
Beispiel #27
0
        public ValidationFailure Test(PlexServerSettings settings)
        {
            try
            {
                var sections = GetSections(settings);

                if (sections.Empty())
                {
                    return(new ValidationFailure("Host", "At least one movie library is required"));
                }
            }
            catch (PlexAuthenticationException ex)
            {
                _logger.Error(ex, "Unable to connect to Plex Server: " + ex.Message);
                return(new ValidationFailure("Username", "Incorrect username or password"));
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Unable to connect to Plex Server: " + ex.Message);
                return(new ValidationFailure("Host", "Unable to connect to Plex Server"));
            }

            return(null);
        }
Beispiel #28
0
 private RestClient GetPlexServerClient(PlexServerSettings settings)
 {
     return(new RestClient(String.Format("http://{0}:{1}", settings.Host, settings.Port)));
 }
Beispiel #29
0
        private List <PlexSection> GetSections(PlexServerSettings settings)
        {
            _logger.Debug("Getting sections from Plex host: {0}", settings.Host);

            return(_plexServerProxy.GetMovieSections(settings).ToList());
        }
Beispiel #30
0
        private int?GetMetadataId(int sectionId, Series series, string language, PlexServerSettings settings)
        {
            _logger.Debug("Getting metadata from Plex host: {0} for series: {1}", settings.Host, series);

            return(_plexServerProxy.GetMetadataId(sectionId, series.TvdbId, language, settings));
        }