Exemplo n.º 1
0
        public PlexResponse HandleRequest(PlexRequest Request)
        {
            if (Request.PathSegments.Length <= 2)
            {
                return XmlResponse.NotFound();
            }
            else
            {
                Int32 Id = Convert.ToInt32(Request.PathSegments[1]);
                SpliceEntityType Type = DataAccess.GetEntityType(Id);

                switch (Type)
                {
                    case SpliceEntityType.Collection:
                        return HandleCollectionResourceRequest(Id, Request);
                    case SpliceEntityType.TVShow:
                        return HandleTVShowResourceRequest(Id, Request);
                    case SpliceEntityType.TVSeason:
                        return HandleTVSeasonResourceRequest(Id, Request);
                    case SpliceEntityType.TVEpisode:
                        return HandleTVEpisodeResourceRequest(Id, Request);
                    default:
                        return XmlResponse.NotFound();
                }
            }
        }
Exemplo n.º 2
0
        public PlexResponse HandleRequest(PlexRequest Request)
        {
            if (Request.PathSegments.Length > 2)
            {
                if (Request.PathSegments.Length >= 2 && Request.PathSegments[1] == "collections")
                {
                    return ManageCollections(Request);
                }
            }

            return XmlResponse.NotFound();
        }
Exemplo n.º 3
0
        private PlexResponse HandleTVSeasonResourceRequest(int Id, PlexRequest Request)
        {
            TVSeason Season = DataAccess.GetTVSeason(Id);

            if (Season.Art == null)
            {
                return XmlResponse.NotFound();
            }
            else
            {
                return new ImageResponse(Season.Art);
            }
        }
Exemplo n.º 4
0
        private PlexResponse HandleTVEpisodeResourceRequest(int Id, PlexRequest Request)
        {
            TVEpisode Episode = DataAccess.GetTVEpisode(Id);

            if (Episode.Thumb == null)
            {
                return XmlResponse.NotFound();
            }
            else
            {
                return new ImageResponse(Episode.Thumb);
            }
        }
Exemplo n.º 5
0
        private PlexResponse HandleCollectionResourceRequest(Int32 Id, PlexRequest Request)
        {
            VideoCollection Collection = DataAccess.GetVideoCollection(Id);

            switch (Request.PathSegments[2])
            {
                case "art":
                    ImageResponse Response = new ImageResponse();
                    Response.FilePath = Collection.Art;
                    return Response;
                default:
                    return XmlResponse.NotFound();
            }
        }
Exemplo n.º 6
0
        private PlexResponse AddCollection(PlexRequest Request)
        {
            if (Request.Headers["Expect"] != null)
            {
                throw new Exception("Received Expect Header");
            }
            if (Request.Method != "POST")
            {
                return XmlResponse.MethodNotAllowed();
            }

            if (Request.PostData["Name"] == null || Request.PostData["Name"].DataAsString.Length == 0 ||
                Request.PostData["Type"] == null)
            {
                // not all required fields provided.
                return XmlResponse.BadRequest();
            }
            else
            {
                VideoCollection Collection = new VideoCollection();

                Collection.Title = Request.PostData["Name"].DataAsString;

                try
                {
                    Collection.Type = (VideoCollectionType)Enum.Parse(typeof(VideoCollectionType), Request.PostData["Type"].DataAsString);
                }
                catch (ArgumentException)
                {
                    return XmlResponse.BadRequest();
                }

                Collection.Locations.AddRange(Request.PostData["Paths"].DataAsString.Split(',').ToList<String>());

                Collection = DataAccess.SaveCollection(Collection);

                // TODO: Handle artwork.
                string SavePath = CacheManager.GetCachePath(Collection.Id, ArtworkType.Fanart);
                FileStream FS = new FileStream(SavePath + "Artwork.jpg", FileMode.Create);
                BinaryWriter Writer = new BinaryWriter(FS);

                Writer.Write(Request.PostData["Artwork"].Data);
                Writer.Close();

                // TODO: Return correct response.
                return XmlResponse.Created();
            }
        }
Exemplo n.º 7
0
        public async Task <PhosResponse> PostWebhook()
        {
            if (!ModelState.IsValid)
            {
                return(new PhosResponse {
                    MalResult = false, AniListResult = false
                });
            }

            var content = await this.Request.Content.ReadAsStringAsync();

            PlexRequest plexRequest = new PlexRequest();

            try
            {
                plexRequest = JsonConvert.DeserializeObject <PlexRequest>(PlexManager.ParseJsonFromWebhook(content));
            }
            catch (JsonSerializationException jse)
            {
                Logger.CreateLogEntry(Enumerations.LogType.Error, jse, DateTime.Now);
                return(new PhosResponse {
                    MalResult = false, AniListResult = false
                });
            }

            Logger.CreateLogEntry(Enumerations.LogType.Info, $"Incoming event ({plexRequest.Event}) from {plexRequest.Account.Title} for episode {plexRequest.Metadata.Index} of {plexRequest.Metadata.GrandparentTitle}", DateTime.Now);

            values = RegisterValues.GetRegisteredValues();

            bool malResult = false, aniListResult = false;

            if (plexRequest.Event.Equals("media.scrobble"))
            {
                // MAL
                malResult = MyAnimeListManager.UpdateList(values, plexRequest);

                // AniList
                aniListResult = await AniListManager.UpdateListAsync(values, plexRequest);

                Logger.CreateLogEntry(Enumerations.LogType.Scrobble, $"Finished watching episode {plexRequest.Metadata.Index} of {plexRequest.Metadata.GrandparentTitle}", DateTime.Now);
            }

            return(new PhosResponse {
                MalResult = malResult, AniListResult = aniListResult
            });
        }
Exemplo n.º 8
0
        public PlexResponse SectionListing(int sectionId, PlexRequest request)
        {
            VideoCollection collection = DataAccess.GetVideoCollection(sectionId);
            List<Filter> filters = Filter.GetTVFilterList();
            XmlDocument xml = new XmlDocument();
            XmlDeclaration dec = xml.CreateXmlDeclaration("1.0", "UTF-8", null);
            xml.AppendChild(dec);
            XmlElement root = xml.CreateElement("MediaContainer");
            //size="11"
            root.SetAttribute("size", filters.Count.ToString());
            //content="secondary"
            root.SetAttribute("content", "secondary");
            //mediaTagPrefix="/system/bundle/media/flags/"
            root.SetAttribute("mediaTagPrefix", "/system/bundle/media/flags/");
            //mediaTagVersion="1283229604"
            root.SetAttribute("mediaTagVersion", "1283229604");
            //nocache="1"
            root.SetAttribute("nocache", "1");
            //viewGroup="secondary"
            root.SetAttribute("viewGroup", "secondary");
            //viewMode="65592"
            root.SetAttribute("viewMode", "65592");
            //art="/:/resources/show-fanart.jpg"
            root.SetAttribute("art", String.Format("/resources/{0}/art", collection.Id));
            //identifier="com.plexapp.plugins.library"
            root.SetAttribute("identifier", "com.plexapps.plugins.library");
            //title1="TV Shows"
            root.SetAttribute("title1", collection.Title);
            xml.AppendChild(root);

            foreach (Filter filter in filters)
            {
                XmlElement directory = xml.CreateElement("Directory");
                directory.SetAttribute("key", filter.Key);
                directory.SetAttribute("title", filter.Name);
                root.AppendChild(directory);
            }

            XmlResponse xmlResponse = new XmlResponse();
            xmlResponse.XmlDoc = xml;
            return xmlResponse;
        }
Exemplo n.º 9
0
        private PlexResponse HandleTVShowResourceRequest(int Id, PlexRequest Request)
        {
            TVShow Show = DataAccess.GetTVShow(Id);

            ImageResponse Response = new ImageResponse();
            switch (Request.PathSegments[2])
            {
                case "art":
                    Response.FilePath = Show.Art;
                    return Response;
                case "thumb":
                    Response.FilePath = Show.Thumb;
                    return Response;
                case "banner":
                    Response.FilePath = Show.Banner;
                    return Response;
                default:
                    return XmlResponse.NotFound();
            }
        }
Exemplo n.º 10
0
        public PlexResponse Index(PlexRequest request)
        {
            XmlDocument xml = new XmlDocument();
            XmlElement root = xml.CreateElement("MediaContainer");
            root.SetAttribute("size", "1");
            root.SetAttribute("mediaTagPrefix", "/system/bundle/media/flags");
            root.SetAttribute("mediaTagVersion", "1283229604");
            root.SetAttribute("art", "/resources/library-art.png");
            root.SetAttribute("title1", "WinPlex Library");
            root.SetAttribute("identify", "com.plexapp.plugins.library");
            xml.AppendChild(root);

            XmlElement directory = xml.CreateElement("Directory");
            directory.SetAttribute("key", "sections");
            directory.SetAttribute("title", "Library Sections");
            root.AppendChild(directory);

            XmlResponse xmlResponse = new XmlResponse();
            xmlResponse.XmlDoc = xml;
            return xmlResponse;
        }
Exemplo n.º 11
0
 public PlexResponse HandleRequest(PlexRequest request)
 {
     if (request.PathSegments.Length == 1)
     {
         return Index(request);
     }
     else if (request.PathSegments.Length >= 2 && request.PathSegments[1] == "sections")
     {
         return Sections(request);
     }
     else if (request.PathSegments.Length >= 2 && request.PathSegments[1] == "metadata")
     {
         return MetaData(request);
     }
     else if (request.PathSegments.Length >= 2 && request.PathSegments[1] == "parts")
     {
         return Parts(request);
     }
     else
     {
         return XmlResponse.NotFound();
     }
 }
Exemplo n.º 12
0
        private PlexResponse Parts(PlexRequest request)
        {
            if (request.PathSegments.Length < 3)
            {
                return XmlResponse.NotFound();
            }
            else
            {
                int PartId = Convert.ToInt32(request.PathSegments[2]);

                VideoFileInfo vidFile = DataAccess.GetVideoFile(PartId);

                VideoResponse resp = new VideoResponse();
                resp.FilePath = vidFile.Path;

                if (request.Headers["Range"] != null)
                {
                    string[] range = request.Headers["Range"].Substring(6).Split('-');
                    resp.Start = Convert.ToInt64(range[0]);
                    if (range[1] != "")
                    {
                        resp.End = Convert.ToInt64(range[1]);
                    }
                }

                return resp;
            }
        }
Exemplo n.º 13
0
 private PlexResponse MetaData(PlexRequest request)
 {
     if (request.PathSegments.Length == 2)
     {
         return XmlResponse.NotFound();
     }
     else if (request.PathSegments.Length == 3)
     {
         return GetMetaData(Convert.ToInt32(request.PathSegments[2]), request);
     }
     else if (request.PathSegments.Length == 4 && request.PathSegments[3] == "children")
     {
         int id = Convert.ToInt32(request.PathSegments[2]);
         return GetMetaDataChildren(id, request);
     }
     else
     {
         return XmlResponse.NotFound();
     }
 }
Exemplo n.º 14
0
        private PlexResponse GetMetaDataChildren(int Id, PlexRequest request)
        {
            SpliceEntityType Type = DataAccess.GetEntityType(Id);

            if (Type == SpliceEntityType.TVShow)
            {
                return GetShowMetaDataChildren(Id);
            }
            else if (Type == SpliceEntityType.TVSeason)
            {
                return GetSeasonMetaDataChildren(Id);
            }
            else
            {
                return XmlResponse.NotFound();
            }
        }
Exemplo n.º 15
0
 private PlexResponse GetMetaData(int id, PlexRequest request)
 {
     return XmlResponse.NotFound();
 }
Exemplo n.º 16
0
        public PlexResponse SectionsIndex(PlexRequest request)
        {
            XmlDocument xml = new XmlDocument();
            XmlDeclaration dec = xml.CreateXmlDeclaration("1.0", "UTF-8", null);
            xml.AppendChild(dec);
            XmlElement root = xml.CreateElement("MediaContainer");
            List<VideoCollection> collections = DataAccess.GetVideoCollections();
            root.SetAttribute("size", collections.Count.ToString());
            xml.AppendChild(root);

            foreach (VideoCollection collection in collections)
            {
                XmlElement directory = xml.CreateElement("Directory");
                directory.SetAttribute("key", collection.Id.ToString());
                directory.SetAttribute("type", collection.Type.ToString());
                directory.SetAttribute("title", collection.Title);
                directory.SetAttribute("art", String.Format("/resources/{0}/art", collection.Id));
                root.AppendChild(directory);
            }

            XmlResponse xmlResponse = new XmlResponse();
            xmlResponse.XmlDoc = xml;
            return xmlResponse;
        }
Exemplo n.º 17
0
        public static async Task <bool> UpdateListAsync(RegisterValues values, PlexRequest plexRequest)
        {
            var entries = await GetListForUser(values.UserName);

            var title = plexRequest.Metadata.GrandparentTitle;

            AniListAnime currentShow = new AniListAnime();

            try
            {
                currentShow = entries.Entries
                              .Where(x => TitleComparer.Compute(x.MediaItem.Title.UserPreferred, title) < 5 ||
                                     x.MediaItem.Title.UserPreferred.ToLower().Contains(title.ToLower())).First();
            }
            catch
            {
                try
                {
                    currentShow = entries.Entries.Select(x => x)
                                  .OrderByDescending(x => TitleComparer.Compute(x.MediaItem.Title.UserPreferred.ToLower(), title.ToLower()))
                                  .First();
                }
                catch (Exception ex)
                {
                    Logger.CreateLogEntry(LogType.Error, ex, DateTime.Now);
                    currentShow = null;
                }
            }

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

            var query = FormUpdateQuery(currentShow.EntryId, currentShow.MediaItem.Id, plexRequest.Metadata.Index);

            var            token   = values.AniListAccessToken;
            HttpWebRequest request = WebRequest.Create(BaseUrl + query) as HttpWebRequest;

            request.Method = "POST";
            request.Headers["Authorization"] = "Bearer " + token;

            AniListSearchResponse aniListResponse;

            try
            {
                var response = (HttpWebResponse)await request.GetResponseAsync();

                using (var reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
                {
                    var aniListResponseString = reader.ReadToEnd();
                    aniListResponse = JsonConvert.DeserializeObject <AniListSearchResponse>(aniListResponseString);
                }
            }
            catch (Exception ex)
            {
                return(false);
            }

            return(true);
        }
Exemplo n.º 18
0
 private PlexResponse ManageCollections(PlexRequest Request)
 {
     if (Request.PathSegments[2] == "list")
     {
         return CollectionsList();
     }
     else if (Request.PathSegments[2] == "add")
     {
         return AddCollection(Request);
     }
     else if (Request.PathSegments[2] == "delete")
     {
         return DeleteCollection(Request);
     }
     else
     {
         return XmlResponse.NotFound();
     }
 }
Exemplo n.º 19
0
        private PlexResponse DeleteCollection(PlexRequest Request)
        {
            if (Request.Method != "POST")
            {
                return XmlResponse.MethodNotAllowed();
            }

            if (Request.PostData["CollectionId"] == null)
            {
                return XmlResponse.BadRequest();
            }

            DataAccess.DeleteCollection(Convert.ToInt32(Request.PostData["CollectionId"].DataAsString));

            return XmlResponse.OK("Collection Deleted");
        }
Exemplo n.º 20
0
        public static bool UpdateList(RegisterValues values, PlexRequest plexRequest)
        {
            if (!(plexRequest.Account.Title == values.Email))
            {
                return(false);
            }

            MalAnime show = SearchListForShow(values.UserName, plexRequest.Metadata.GrandparentTitle);

            if (!(show is MalAnime) || string.IsNullOrEmpty(show.Title))
            {
                Logger.CreateLogEntry(Enumerations.LogType.Error, new ArgumentException("Show was not found through MAL API search or some other error occured."), DateTime.Now);
            }

            var episodeCompleted = plexRequest.Metadata.Index;
            var isFinished       = (episodeCompleted == show.Episodes) ? true : false;

            if (!ValidateMalCredentials(values.UserName, values.Password))
            {
                Logger.CreateLogEntry(LogType.Error, "Failed to verify MAL credentials.", DateTime.UtcNow);
                return(false);
            }

            MalAnimeValues add = new MalAnimeValues
            {
                Episode = show.MyWatchedEpisodes++,
                Status  = (isFinished) ? (int)Enumerations.MalStatus.Completed : (int)Enumerations.MalStatus.Watching
            };
            string      json = JsonConvert.SerializeObject(add);
            XmlDocument doc  = JsonConvert.DeserializeXmlNode(json, "entry");

            HttpWebRequest updateRequest = WebRequest.Create($"{MalApiBaseUrl}/update/{show.Id}.xml?data={doc.OuterXml}") as HttpWebRequest;

            updateRequest.Method = "GET";
            updateRequest.Headers["Authorization"] = "Basic " +
                                                     Convert.ToBase64String(Encoding.ASCII.GetBytes($"{values.UserName}:{values.Password}"));
            updateRequest.ContentType = "application/x-www-form-urlencoded";

            bool updated = false;

            try
            {
                HttpWebResponse updateResponse = (HttpWebResponse)updateRequest.GetResponse();
            }
            catch (Exception ex)
            {
                Logger.CreateLogEntry(LogType.Error, ex, createdOn: DateTime.Now);
                updated = false;
            }

            Logger.CreateLogEntry(LogType.Success, $"Successfully updated show on {values.UserName}'s list.", DateTime.Now);
            updated = true;

            if (!updated)
            {
                Logger.CreateLogEntry(Enumerations.LogType.Error, "Failed to update list with show.", DateTime.Now);
                return(updated);
            }
            else
            {
                TwilioClient.Init(values.TwilioUserName, values.TwilioPassword);
                MessageResource.Create(
                    to: new Twilio.Types.PhoneNumber(values.UserPhoneNumber),
                    from: new Twilio.Types.PhoneNumber(values.TwilioPhoneNumber),
                    body: $"Successfully updated MAL with episode {episodeCompleted} of {show.Title}");
                return(updated);
            }
        }
Exemplo n.º 21
0
 public PlexResponse Sections(PlexRequest request)
 {
     if (request.PathSegments.Length == 2)
     {
         return SectionsIndex(request);
     }
     else if (request.PathSegments.Length == 3)
     {
         return SectionListing(Convert.ToInt32(request.PathSegments[2]), request);
     }
     else if (request.PathSegments.Length == 4)
     {
         int collectionId = Convert.ToInt32(request.PathSegments[2]);
         string filterKey = request.PathSegments[3];
         return FilteredSection(collectionId, filterKey);
     }
     else
     {
         return XmlResponse.NotFound();
     }
 }