public List <PlexTvShow> GetPlexTvShows(List <PlexSearch> libs) { var settings = Plex.GetSettings(); var shows = new List <PlexTvShow>(); if (libs != null) { var withDir = libs.Where(x => x.Directory != null); var tvLibs = withDir.Where(x => x.Directory.Any(y => y.Type.Equals(PlexMediaType.Show.ToString(), StringComparison.CurrentCultureIgnoreCase) ) ).ToArray(); foreach (var lib in tvLibs) { shows.AddRange(lib.Directory.Select(x => new PlexTvShow // shows are in the directory list { Title = x.Title, ReleaseYear = x.Year, ProviderId = x.ProviderId, Seasons = x.Seasons?.Select(d => PlexHelper.GetSeasonNumberFromTitle(d.Title)).ToArray(), Url = PlexHelper.GetPlexMediaUrl(settings.MachineIdentifier, x.RatingKey), ItemId = x.RatingKey })); } } return(shows); }
public static string transferToPlex(string data) { try { string puser = (HttpContext.Current.Session[SysConst.S_LOGIN_USER] as UsersModel).USERNAME; string plexid = (HttpContext.Current.Session[SysConst.S_LOGIN_USER] as UsersModel).PLEXID; PlexContainer model = new PlexContainer(); List <PlexContainer> listmodel = new List <PlexContainer>(); List <String> sqllist = new List <String>(); JavaScriptSerializer jssl = new JavaScriptSerializer(); listmodel = jssl.Deserialize <List <PlexContainer> >(data); if (listmodel.Count != 0) { foreach (PlexContainer m in listmodel) { string ft = m.Location + "&" + m.TLoc + "&" + "F"; FGA_NUtility.POL.ExecuteDataSourceResult esr = PlexHelper.PlexGetResult_4("27181", "Container_Update_Simple", "@Serial_No", "@Last_Action", "@Location", "@Update_By", m.SerialNO, "Updated at Inventory Update Form", m.TLoc, plexid); string sql = "insert into OEM_IR(SerialNO,FT_Location,Type,Creater,Createdate)" + " values('" + m.SerialNO + "','" + ft + "','FIFO','" + puser + "',getdate())"; sqllist.Add(sql); } int count = FGA_DAL.Base.SQLServerHelper_WMS.ExecuteSqlTran(sqllist); } } catch { return("0"); } return("1"); }
public static string confirmData(string data) { //按用户查看EDI的数据 string plexid = (HttpContext.Current.Session[SysConst.S_LOGIN_USER] as UsersModel).PLEXID; string user = (HttpContext.Current.Session[SysConst.S_LOGIN_USER] as UsersModel).USERNAME; List <string> sqllist = new List <string>(); List <PlexContainer> listmodel = new List <PlexContainer>(); JavaScriptSerializer jssl = new JavaScriptSerializer(); listmodel = jssl.Deserialize <List <PlexContainer> >(data); foreach (PlexContainer pc in listmodel) { bool rt = true; FGA_NUtility.POL.ExecuteDataSourceResult esr = PlexHelper.PlexGetResult_4("27181", "Container_Update_Simple", "@Serial_No", "@Last_Action", "@Location", "@Update_By", pc.SerialNO, "Updated at Inventory Update Form", pc.TLoc, plexid); rt = esr.Error; if (!rt) { string sql = "update [ProcessHOAudit_T] set [ContainerStatus] = 'Finish',[Receiver] ='" + user + "',[ReceptionDate] = getdate() where SERIALNO = '" + pc.SerialNO + "' AND [From_LOC] = '" + pc.Location + "' and [ContainerStatus] = 'In Progress'"; sqllist.Add(sql); } } if (FGA_DAL.Base.SQLServerHelper.ExecuteSqlTran(sqllist) > 0) { return("1"); } else { return("0"); } }
public List <PlexAlbum> GetPlexAlbums(List <PlexSearch> libs) { var settings = Plex.GetSettings(); var albums = new List <PlexAlbum>(); if (libs != null) { var albumLibs = libs.Where(x => x.Directory.Any(y => y.Type.Equals(PlexMediaType.Artist.ToString(), StringComparison.CurrentCultureIgnoreCase) ) ).ToArray(); foreach (var lib in albumLibs) { albums.AddRange(lib.Directory.Select(x => new PlexAlbum() { Title = x.Title, ProviderId = x.ProviderId, ReleaseYear = x.Year, Artist = x.ParentTitle, Url = PlexHelper.GetPlexMediaUrl(settings.MachineIdentifier, x.RatingKey) })); } } return(albums); }
private System.IO.Stream GetUnsort(int userid, HistoryInfo info) { PlexObject ret = new PlexObject(PlexHelper.NewMediaContainer(MediaContainerTypes.Video, info, true)); if (!ret.Init()) { return(new MemoryStream()); } List <Video> dirs = new List <Video>(); VideoLocalRepository repVids = new VideoLocalRepository(); List <VideoLocal> vids = repVids.GetVideosWithoutEpisode(); foreach (VideoLocal v in vids.OrderByDescending(a => a.DateTimeCreated)) { Video m = new Video(); try { PlexHelper.PopulateVideo(m, v, JMMType.File, userid); m.GrandparentKey = null; if (!string.IsNullOrEmpty(m.Duration)) { dirs.Add(m, info); } } catch (Exception e) { //Fast fix if file do not exist, and still is in db. (Xml Serialization of video info will fail on null) } } ret.Childrens = dirs; return(ret.GetStream()); }
public List <PlexMovie> GetPlexMoviesOld() { var settings = Plex.GetSettings(); var movies = new List <PlexMovie>(); var libs = Cache.Get <List <PlexSearch> >(CacheKeys.PlexLibaries); if (libs != null) { var movieLibs = libs.Where(x => x.Video.Any(y => y.Type.Equals(PlexMediaType.Movie.ToString(), StringComparison.CurrentCultureIgnoreCase) ) ).ToArray(); foreach (var lib in movieLibs) { movies.AddRange(lib.Video.Select(video => new PlexMovie { ReleaseYear = video.Year, Title = video.Title, ProviderId = video.ProviderId, Url = PlexHelper.GetPlexMediaUrl(settings.MachineIdentifier, video.RatingKey) })); } } return(movies); }
private async Task <ProviderId> GetProviderIds(string authToken, Metadata movie, CancellationToken cancellationToken) { var guids = new List <string>(); if (!movie.Guid.Any()) { var metaData = await _plexApi.GetWatchlistMetadata(movie.ratingKey, authToken, cancellationToken); var meta = metaData.MediaContainer.Metadata.FirstOrDefault(); guids.Add(meta.guid); if (meta.Guid != null) { foreach (var g in meta.Guid) { guids.Add(g.Id); } } } else { // Currently a Plex Pass feature only foreach (var g in movie.Guid) { guids.Add(g.Id); } } var providerIds = PlexHelper.GetProviderIdsFromMetadata(guids.ToArray()); return(providerIds); }
private void GenerateTvHtml(List <Metadata> tv, PlexSettings plexSettings, StringBuilder sb) { var orderedTv = tv.OrderByDescending(x => x?.addedAt.UnixTimeStampToDateTime()).ToList(); // TV sb.Append("<h1>New Episodes:</h1><br/><br/>"); sb.Append( "<table border=\"0\" cellpadding=\"0\" align=\"center\" cellspacing=\"0\" style=\"border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%;\" width=\"100%\">"); foreach (var t in orderedTv) { var plexGUID = string.Empty; try { var parentMetaData = Api.GetMetadata(plexSettings.PlexAuthToken, plexSettings.FullUri, t.parentRatingKey.ToString()); plexGUID = parentMetaData.Directory.Guid; var info = TvApi.ShowLookupByTheTvDbId(int.Parse(PlexHelper.GetProviderIdFromPlexGuid(plexGUID))); var banner = info.image?.original; if (!string.IsNullOrEmpty(banner)) { banner = banner.Replace("http", "https"); // Always use the Https banners } AddImageInsideTable(sb, banner); sb.Append("<tr>"); sb.Append( "<td align=\"center\" style=\"font-family: sans-serif; font-size: 14px; vertical-align: top;\" valign=\"top\">"); var title = $"{t.grandparentTitle} - {t.title} {t.originallyAvailableAt?.Substring(0, 4)}"; Href(sb, $"https://www.imdb.com/title/{info.externals.imdb}/"); Header(sb, 3, title); EndTag(sb, "a"); AddParagraph(sb, $"Season: {t.parentIndex}, Episode: {t.index}"); if (info.genres.Any()) { AddParagraph(sb, $"Genre: {string.Join(", ", info.genres.Select(x => x.ToString()).ToArray())}"); } AddParagraph(sb, string.IsNullOrEmpty(t.summary) ? info.summary : t.summary); } catch (Exception e) { Log.Error(e); Log.Error( "Exception when trying to process a TV Show, either in getting the metadata from Plex OR getting the information from TVMaze, Plex GUID = {0}", plexGUID); } finally { EndLoopHtml(sb); } } sb.Append("</table><br/><br/>"); }
public void GetProviderIdsFromMetadataTests(string guidInput, ProviderId expected) { var param = guidInput.Split('|', StringSplitOptions.RemoveEmptyEntries); var result = PlexHelper.GetProviderIdsFromMetadata(param); Assert.AreEqual(expected.ImdbId, result.ImdbId); Assert.AreEqual(expected.TheMovieDb, result.TheMovieDb); Assert.AreEqual(expected.TheTvDb, result.TheTvDb); }
private void GenerateMovieHtml(List <Metadata> movies, PlexSettings plexSettings, StringBuilder sb) { var orderedMovies = movies.OrderByDescending(x => x?.addedAt.UnixTimeStampToDateTime()).ToList() ?? new List <Metadata>(); sb.Append("<h1>New Movies:</h1><br/><br/>"); sb.Append( "<table border=\"0\" cellpadding=\"0\" align=\"center\" cellspacing=\"0\" style=\"border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%;\" width=\"100%\">"); foreach (var movie in orderedMovies) { var plexGUID = string.Empty; try { var metaData = Api.GetMetadata(plexSettings.PlexAuthToken, plexSettings.FullUri, movie.ratingKey.ToString()); plexGUID = metaData.Video.Guid; var imdbId = PlexHelper.GetProviderIdFromPlexGuid(plexGUID); var info = _movieApi.GetMovieInformation(imdbId).Result; if (info == null) { throw new Exception($"Movie with Imdb id {imdbId} returned null from the MovieApi"); } AddImageInsideTable(sb, $"https://image.tmdb.org/t/p/w500{info.BackdropPath}"); sb.Append("<tr>"); sb.Append( "<td align=\"center\" style=\"font-family: sans-serif; font-size: 14px; vertical-align: top;\" valign=\"top\">"); Href(sb, $"https://www.imdb.com/title/{info.ImdbId}/"); Header(sb, 3, $"{info.Title} {info.ReleaseDate?.ToString("yyyy") ?? string.Empty}"); EndTag(sb, "a"); if (info.Genres.Any()) { AddParagraph(sb, $"Genre: {string.Join(", ", info.Genres.Select(x => x.Name.ToString()).ToArray())}"); } AddParagraph(sb, info.Overview); } catch (Exception e) { Log.Error(e); Log.Error( "Exception when trying to process a Movie, either in getting the metadata from Plex OR getting the information from TheMovieDB, Plex GUID = {0}", plexGUID); } finally { EndLoopHtml(sb); } } sb.Append("</table><br/><br/>"); }
private async Task GetChildMetadata(PlexMediaItemRow mediaItem, string authToken, string plexUri, string machineIdentifier) { _logger.LogDebug($"Retrieving all seasons for show '{mediaItem.Title}'"); var seasonShowItems = await GetChildShowItems(mediaItem.MediaItemKey, authToken, plexUri); foreach (var seasonShowItem in seasonShowItems) { var plexSeason = mediaItem.PlexSeasons.FirstOrDefault(x => x.Season == seasonShowItem.Index); if (plexSeason == null) { plexSeason = new PlexSeasonRow { Identifier = Guid.NewGuid() }; mediaItem.PlexSeasons.Add(plexSeason); } plexSeason.MediaItemKey = seasonShowItem.RatingKey; plexSeason.Title = seasonShowItem.Title; plexSeason.AgentSourceId = seasonShowItem.AgentSourceId; plexSeason.AgentType = seasonShowItem.AgentType; plexSeason.Season = seasonShowItem.Index; plexSeason.MediaUri = PlexHelper.GenerateMediaItemUri(_plexSettings.PlexMediaItemUriFormat, machineIdentifier, seasonShowItem.RatingKey); _logger.LogDebug($"Retrieving all episodes for show '{mediaItem.Title}' season '{plexSeason.Season}'"); var episodeShowItems = await GetChildShowItems(seasonShowItem.RatingKey, authToken, plexUri); foreach (var episodeShowItem in episodeShowItems) { var plexEpisode = plexSeason.PlexEpisodes.FirstOrDefault(x => x.Episode == episodeShowItem.Index); if (plexEpisode == null) { plexEpisode = new PlexEpisodeRow { Identifier = Guid.NewGuid() }; plexSeason.PlexEpisodes.Add(plexEpisode); } plexEpisode.Identifier = Guid.NewGuid(); plexEpisode.MediaItemKey = episodeShowItem.RatingKey; plexEpisode.Title = episodeShowItem.Title; plexEpisode.AgentSourceId = episodeShowItem.AgentSourceId; plexEpisode.AgentType = episodeShowItem.AgentType; plexEpisode.Episode = episodeShowItem.Index; plexEpisode.Year = episodeShowItem.Year; plexEpisode.Resolution = episodeShowItem.Resolution; plexEpisode.MediaUri = PlexHelper.GenerateMediaItemUri(_plexSettings.PlexMediaItemUriFormat, machineIdentifier, episodeShowItem.RatingKey); } } }
public static string CreateDALabel(string serialno) { string label_zpl = ""; string label_f = ""; UsersModel model = (UsersModel)HttpContext.Current.Session[SysConst.S_LOGIN_USER]; //获取当前DA标签代码 FGA_NUtility.POL.ExecuteDataSourceResult result = PlexHelper.PlexGetResult_3("1953", "Web Service Get Container Label", "@SerialNo", "@PLCName", "@IPAddress", serialno, "Barcode", "172.17.190.44"); if (result.OutputParameters != null) { label_zpl = result.OutputParameters[2].Value; } //获取剩余箱签代码 FGA_NUtility.POL.ExecuteDataSourceResult rst = PlexHelper.PlexGetResult_2("33468", "Containers_By_Last_Action_Today_Get", "@Last_Action", "@Serial_No", "Split Container", serialno); if (rst.ResultSets != null) { //获取当前split最大的DA int a = 0; int b = 0; int c = 0; for (int i = 0; i < rst.ResultSets[0].RowCount; i++) { a = Int32.Parse(rst.ResultSets[0].Rows[i].Columns[0].Value.Substring(1, 7)); if (a > b) { b = a; c = i; } } string fsn = rst.ResultSets[0].Rows[c].Columns[13].Value; if (!string.IsNullOrEmpty(fsn)) { FGA_NUtility.POL.ExecuteDataSourceResult rst2 = PlexHelper.PlexGetResult_3("1953", "Web Service Get Container Label", "@SerialNo", "@PLCName", "@IPAddress", fsn, "Barcode", "172.17.190.44"); if (rst2.OutputParameters != null) { label_f = rst2.OutputParameters[2].Value; } } } return("newsn" + label_zpl + "oldsn" + label_f + "username" + model.USERNAME); }
public List <string> GetEpisodeAndSeasons(string guid) { var ep = PlexHelper.GetSeasonsAndEpisodesFromPlexGuid(guid); var list = new List <string> { ep.ProviderId, ep.SeasonNumber.ToString(), ep.EpisodeNumber.ToString(), }; return(list); }
//更新JOBNO的状态 public static string updateStatus() { string res = String.Empty; int count = 0; string puser = (HttpContext.Current.Session[SysConst.S_LOGIN_USER] as UsersModel).USERNAME; List <string> sqllist = new List <string>(); List <JobStatusModel> luw = new List <JobStatusModel>(); string jn = "\'0\'"; String sql = "SELECT * FROM [WMS_BarCode_V10].[dbo].[FGA_JobNoStatusUpt] where ISNULL(JobStatus,'') = 'Production' and Creator = '" + puser + "'"; DataSet ds = new DataSet(); ds = FGA_DAL.Base.SQLServerHelper_WMS.Query(sql); if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { foreach (DataRow row in ds.Tables[0].Rows) { JobStatusModel ERM = new JobStatusModel(row); //首先通过JOBNO获取JOBKEY--Job_Key_Get/10436 @Job_No FGA_NUtility.POL.ExecuteDataSourceResult rkey = PlexHelper.PlexGetResult_1("10436", "Job_Key_Get", "@Job_No", ERM.JobNO); if (rkey.ResultSets != null) { string _key = rkey.ResultSets[0].Rows[0].Columns[0].Value; FGA_NUtility.POL.ExecuteDataSourceResult esr = PlexHelper.PlexGetResult_2("36211", "Job_Scheduling_Details_Update", "@Job_Key", "@Job_Status", _key, "Completed"); if (esr.OutputParameters[1].Value == "Success") { jn = jn + "," + '\'' + ERM.JobNO + '\''; count++; } } } if (count > 0) { string sqlupdate = "update [FGA_JobNoStatusUpt] set JobStatus ='Completed',CompletedDate = GETDATE() where JobNO in (" + jn + ") AND Creator = '" + puser + "'"; int fin = FGA_DAL.Base.SQLServerHelper_WMS.ExecuteSql(sqlupdate); res = fin.ToString(); } } else { res = "-1"; } return(res); }
public static string GetDALabel() { string label_zpl = ""; FGA_NUtility.POL.ExecuteDataSourceResult result = PlexHelper.PlexGetResult_3("1953", "Web Service Get Container Label", "@SerialNo", "@PLCName", "@IPAddress", "DA712918", "Barcode", "172.17.190.44"); if (result.OutputParameters != null) { label_zpl = result.OutputParameters[2].Value; } return(label_zpl); }
public System.IO.Stream GetItemsFromGroup(int userid, string GroupId, HistoryInfo info) { PlexObject ret = new PlexObject(PlexHelper.NewMediaContainer(MediaContainerTypes.Show, info, false)); if (!ret.Init()) { return(new MemoryStream()); } int groupID; int.TryParse(GroupId, out groupID); List <Video> retGroups = new List <Video>(); if (groupID == -1) { return(new MemoryStream()); } using (var session = JMMService.SessionFactory.OpenSession()) { AnimeGroupRepository repGroups = new AnimeGroupRepository(); AnimeGroup grp = repGroups.GetByID(groupID); if (grp != null) { Contract_AnimeGroup basegrp = grp.ToContract(grp.GetUserRecord(session, userid)); List <AnimeSeries> sers2 = grp.GetSeries(session); foreach (AnimeGroup grpChild in grp.GetChildGroups()) { Video v = StatsCache.Instance.StatPlexGroupsCache[userid][grpChild.AnimeGroupID]; if (v != null) { retGroups.Add(v.Clone(), info); } } foreach (AnimeSeries ser in grp.GetSeries()) { Contract_AnimeSeries cserie = ser.ToContract(ser.GetUserRecord(session, userid), true); Video v = PlexHelper.FromSerieWithPossibleReplacement(cserie, ser, ser.GetAnime(), userid); v.AirDate = ser.AirDate.HasValue ? ser.AirDate.Value : DateTime.MinValue; v.Group = basegrp; retGroups.Add(v, info); } } ret.Childrens = PlexHelper.ConvertToDirectoryIfNotUnique(retGroups.OrderBy(a => a.AirDate).ToList()); return(ret.GetStream()); } }
public static string getDataBySerialNO(string data, string CycleNO, string targetLoc)//从plex获取DA号对应的信息 { string res = string.Empty; string puser = (HttpContext.Current.Session[SysConst.S_LOGIN_USER] as UsersModel).USERNAME; CycleInventory_Detail model = new CycleInventory_Detail(); FGA_NUtility.POL.ExecuteDataSourceResult esr = PlexHelper.PlexGetResult_1("10837", "Container_Get", "@Serial_No", data); string sql = null; if (esr.ResultSets != null) { model.PartNO = esr.ResultSets[0].Rows[0].Columns[23].Value; model.PartName = esr.ResultSets[0].Rows[0].Columns[42].Value; model.Location = esr.ResultSets[0].Rows[0].Columns[9].Value; model.Quantity = Decimal.Parse(esr.ResultSets[0].Rows[0].Columns[14].Value); model.ActualQty = Decimal.Parse(esr.ResultSets[0].Rows[0].Columns[14].Value); model.OperationCode = esr.ResultSets[0].Rows[0].Columns[40].Value; sql = "insert into [FGA_CycleInventory_Detail] ([CycleNO],[CycleStatus],[SerialNO],[PartNO],[Location],[Quantity]," + "[ActualQty],[creator],[createtime],[TargetLocation],[PartName],[OperationCode],[Dr]) " + "values ('" + CycleNO + "','In Process','" + data + "','" + model.PartNO + "','" + model.Location + "'," + model.Quantity + "," + model.Quantity + ",'" + puser + "',getdate()," + "'" + targetLoc + "','" + model.PartName + "','" + model.OperationCode + "','0')"; } else { sql = "insert into [FGA_CycleInventory_Detail] ([CycleNO],[CycleStatus],[SerialNO],[PartNO],[Location],[Quantity]," + "[ActualQty],[creator],[createtime],[TargetLocation],[PartName],[OperationCode],[Dr]) " + "values ('" + CycleNO + "','In Process','" + data + "','" + model.PartNO + "','" + model.Location + "'," + model.Quantity + "," + model.Quantity + ",'" + puser + "',getdate()," + "'" + targetLoc + "','" + model.PartName + "','" + model.OperationCode + "','1')"; } //将获取的信息存入数据库,保存成功才返回界面。否则报错 //Update by IT-WXL 20180502 if (FGA_DAL.Base.SQLServerHelper_WMS.ExecuteSql(sql) > 0) { JavaScriptSerializer jssl = new JavaScriptSerializer(); res = jssl.Serialize(model); } return(res); }
public async Task <MediaItemResult> GetMediaItem(int ratingKey, PlexMediaTypes mediaType, List <PlexMediaItemRow> localMedia, string authToken, string plexUri, string machineIdentifier, string plexUriFormat) { var metadata = await TryGetPlexMetadata(ratingKey, authToken, plexUri); if (metadata == null) { return(null); } var mediaItem = localMedia.FirstOrDefault(x => x.MediaItemKey == ratingKey); var isNewItem = false; if (mediaItem == null) { mediaItem = new PlexMediaItemRow { Identifier = Guid.NewGuid(), MediaItemKey = ratingKey, MediaType = mediaType, Title = metadata.Title, Year = metadata.Year }; isNewItem = true; } mediaItem.Resolution = metadata.Media?.FirstOrDefault()?.VideoResolution; var agentResult = _agentGuidParser.TryGetAgentDetails(metadata.Guid); if (agentResult == null) { return(null); } mediaItem.AgentType = agentResult.AgentType; mediaItem.AgentSourceId = agentResult.AgentSourceId; mediaItem.MediaUri = PlexHelper.GenerateMediaItemUri(plexUriFormat, machineIdentifier, ratingKey); return(new MediaItemResult(isNewItem, mediaItem)); }
private async Task GetProviderIds(PlexMetadata showMetadata, PlexServerContent existingContent) { var metadata = showMetadata.MediaContainer.Metadata.FirstOrDefault(); var guids = new List <string> { metadata.guid }; if (metadata.Guid != null) { foreach (var g in metadata.Guid) { guids.Add(g.Id); } } var providerIds = PlexHelper.GetProviderIdsFromMetadata(guids.ToArray()); if (providerIds.ImdbId.HasValue()) { existingContent.ImdbId = providerIds.ImdbId; } if (providerIds.TheMovieDb.HasValue()) { existingContent.TheMovieDbId = providerIds.TheMovieDb; } if (providerIds.TheTvDb.HasValue()) { // Lookup TheMovieDbId var findResult = await _movieApi.Find(providerIds.TheTvDb, ExternalSource.tvdb_id); var tvResult = findResult.tv_results.FirstOrDefault(); if (tvResult != null) { existingContent.TheMovieDbId = tvResult.id.ToString(); } existingContent.TvDbId = providerIds.TheTvDb; } }
private static void GetProviderIds(PlexMetadata showMetadata, PlexServerContent existingContent) { var providerIds = PlexHelper.GetProviderIdFromPlexGuid(showMetadata.MediaContainer.Metadata.FirstOrDefault() .guid); if (providerIds.Type == ProviderType.ImdbId) { existingContent.ImdbId = providerIds.ImdbId; } if (providerIds.Type == ProviderType.TheMovieDbId) { existingContent.TheMovieDbId = providerIds.TheMovieDb; } if (providerIds.Type == ProviderType.TvDbId) { existingContent.TvDbId = providerIds.TheTvDb; } }
public System.IO.Stream GetMetadata(string UserId, string TypeId, string Id, string historyinfo) { try { HistoryInfo his = HistoryInfo.FromKey(historyinfo); if (WebOperationContext.Current != null) { his.Key = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri.ToString(); } int type; int.TryParse(TypeId, out type); JMMUser user = PlexHelper.GetJMMUser(UserId); switch ((JMMType)type) { case JMMType.Group: return(GetItemsFromGroup(user.JMMUserID, Id, his)); case JMMType.GroupFilter: return(GetGroupsFromFilter(user.JMMUserID, Id, his)); case JMMType.GroupUnsort: return(GetUnsort(user.JMMUserID, his)); case JMMType.Serie: return(GetItemsFromSerie(user.JMMUserID, Id, his)); case JMMType.File: return(InternalGetFile(user.JMMUserID, Id, his)); case JMMType.Playlist: return(GetItemsFromPlaylist(user.JMMUserID, Id, his)); } return(new MemoryStream()); } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); return(new MemoryStream()); } }
public System.IO.Stream GetUsers() { PlexContract_Users gfs = new PlexContract_Users(); try { gfs.Users = new List <PlexContract_User>(); JMMUserRepository repUsers = new JMMUserRepository(); foreach (JMMUser us in repUsers.GetAll()) { PlexContract_User p = new PlexContract_User(); p.id = us.JMMUserID.ToString(); p.name = us.Username; gfs.Users.Add(p); } } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } return(PlexHelper.GetStreamFromXmlObject(gfs)); }
public string GetProviderIdFromPlexGuidTests(string guidInput, ProviderIdType type) { var result = PlexHelper.GetProviderIdFromPlexGuid(guidInput); switch (type) { case ProviderIdType.Imdb: Assert.That(result.ImdbId, Is.Not.Null); return(result.ImdbId); case ProviderIdType.TvDb: Assert.That(result.TheTvDb, Is.Not.Null); return(result.TheTvDb); case ProviderIdType.MovieDb: Assert.That(result.TheMovieDb, Is.Not.Null); return(result.TheMovieDb); default: throw new ArgumentOutOfRangeException(nameof(type), type, null); } }
public string part_mdm_add(string partno, string partname, string parttype, string partstatus, string partgroup, string partsource, string partpgroup, string unit, string desc, string dept) { string res = ""; FGA_NUtility.POL.ExecuteDataSourceResult da_rst = null; da_rst = PlexHelper.PlexGetResult_10("12564", "Part_And_Attributes_Add_Update", "@Part_No", "@Name", "@Part_Type", "@Part_Status", "@Part_Group", "@Part_Source", "@Part_Product_Group", "@Unit", "@Description", "@Department_Code", partno, partname, parttype, partgroup, partgroup, partsource, partpgroup, unit, desc, dept); if (!String.IsNullOrEmpty(da_rst.OutputParameters[0].ToString())) { res = "Successful"; } else { res = da_rst.OutputParameters[2].ToString(); } return(res); }
private System.IO.Stream InternalGetFile(int userid, string Id, HistoryInfo info) { int id; if (!int.TryParse(Id, out id)) { return(new MemoryStream()); } VideoLocalRepository repVids = new VideoLocalRepository(); PlexObject ret = new PlexObject(PlexHelper.NewMediaContainer(MediaContainerTypes.File, info, true)); VideoLocal vi = repVids.GetByID(id); if (vi == null) { return(new MemoryStream()); } List <Video> dirs = new List <Video>(); Video v2 = new Video(); PlexHelper.PopulateVideo(v2, vi, JMMType.File, userid); dirs.Add(v2, info); ret.MediaContainer.Childrens = dirs; return(ret.GetStream()); }
public static string GetDAContainer(string serialno) { string res = string.Empty; try { List <PlexContainer> luw = new List <PlexContainer>(); PlexContainer PC = new PlexContainer(); FGA_NUtility.POL.ExecuteDataSourceResult da_rst = PlexHelper.PlexGetResult_1("7836", "Containers_By_Part_Get", "@Serial_No", serialno); string location = da_rst.ResultSets[0].Rows[0].Columns[17].Value; if (location.IndexOf("FGA") < 0 && location.IndexOf("FGS") < 0) { PC.SerialNO = da_rst.ResultSets[0].Rows[0].Columns[10].Value; PC.PartNO = da_rst.ResultSets[0].Rows[0].Columns[3].Value; PC.Quantity = decimal.Parse(da_rst.ResultSets[0].Rows[0].Columns[15].Value); PC.OperationNo = da_rst.ResultSets[0].Rows[0].Columns[7].Value; PC.Location = location; PC.ContainerStatus = da_rst.ResultSets[0].Rows[0].Columns[19].Value; luw.Add(PC); JavaScriptSerializer jssl = new JavaScriptSerializer(); res = jssl.Serialize(luw); } else { res = "loc_error"; } } catch (Exception e) { } return(res); }
private T CallPlexHelper <T>(Func <PlexHelper, T> act) { JMMUser user = HttpContext.GetUser(); return(act(PlexHelper.GetForUser(user))); }
public void CacheEpisodes(PlexSettings settings) { var videoHashset = new HashSet <Video>(); // Ensure Plex is setup correctly if (string.IsNullOrEmpty(settings.PlexAuthToken)) { return; } // Get the librarys and then get the tv section var sections = PlexApi.GetLibrarySections(settings.PlexAuthToken, settings.FullUri); var tvSection = sections.Directories.FirstOrDefault(x => x.type.Equals(PlexMediaType.Show.ToString(), StringComparison.CurrentCultureIgnoreCase)); var tvSectionId = tvSection?.Key; var currentPosition = 0; int totalSize; // Get the first 25 episodes (Paged) var episodes = PlexApi.GetAllEpisodes(settings.PlexAuthToken, settings.FullUri, tvSectionId, currentPosition, ResultCount); // Parse the total amount of episodes int.TryParse(episodes.TotalSize, out totalSize); // Get all of the episodes in batches until we them all (Got'a catch 'em all!) while (currentPosition < totalSize) { videoHashset.UnionWith(PlexApi.GetAllEpisodes(settings.PlexAuthToken, settings.FullUri, tvSectionId, currentPosition, ResultCount).Video .Where(x => x.Type.Equals(PlexType, StringComparison.InvariantCultureIgnoreCase))); currentPosition += ResultCount; } var entities = new ConcurrentDictionary <PlexEpisodes, byte>(); Parallel.ForEach(videoHashset, video => { // Get the individual episode Metadata (This is for us to get the TheTVDBId which also includes the episode number and season number) var metadata = PlexApi.GetEpisodeMetaData(settings.PlexAuthToken, settings.FullUri, video.RatingKey); // Loop through the metadata and create the model to insert into the DB foreach (var metadataVideo in metadata.Video) { if (string.IsNullOrEmpty(metadataVideo.GrandparentTitle)) { continue; } var epInfo = PlexHelper.GetSeasonsAndEpisodesFromPlexGuid(metadataVideo.Guid); entities.TryAdd( new PlexEpisodes { EpisodeNumber = epInfo.EpisodeNumber, EpisodeTitle = metadataVideo.Title, ProviderId = epInfo.ProviderId, RatingKey = metadataVideo.RatingKey, SeasonNumber = epInfo.SeasonNumber, ShowTitle = metadataVideo.GrandparentTitle }, 1); } }); // Delete all of the current items Repo.DeleteAll(TableName); // Insert the new items var result = Repo.BatchInsert(entities.Select(x => x.Key).ToList(), TableName, typeof(PlexEpisodes).GetPropertyNames()); if (!result) { Log.Error("Saving the Plex episodes to the DB Failed"); } }
private List <PlexSearch> CachedLibraries(PlexSettings plexSettings, bool setCache) { var results = new List <PlexSearch>(); if (!ValidateSettings(plexSettings)) { Log.Warn("The settings are not configured"); return(results); // don't error out here, just let it go! let it goo!!! } try { // TODO what the f**k was I thinking if (setCache) { results = GetLibraries(plexSettings); if (plexSettings.AdvancedSearch) { foreach (PlexSearch t in results) { foreach (Directory1 t1 in t.Directory) { var currentItem = t1; var metaData = PlexApi.GetMetadata(plexSettings.PlexAuthToken, plexSettings.FullUri, currentItem.RatingKey); // Get the seasons for each show if (currentItem.Type.Equals(PlexMediaType.Show.ToString(), StringComparison.CurrentCultureIgnoreCase)) { var seasons = PlexApi.GetSeasons(plexSettings.PlexAuthToken, plexSettings.FullUri, currentItem.RatingKey); // We do not want "all episodes" this as a season var filtered = seasons.Directory.Where(x => !x.Title.Equals("All episodes", StringComparison.CurrentCultureIgnoreCase)); t1.Seasons.AddRange(filtered); } var providerId = PlexHelper.GetProviderIdFromPlexGuid(metaData.Directory.Guid); t1.ProviderId = providerId; } foreach (Video t1 in t.Video) { var currentItem = t1; var metaData = PlexApi.GetMetadata(plexSettings.PlexAuthToken, plexSettings.FullUri, currentItem.RatingKey); var providerId = PlexHelper.GetProviderIdFromPlexGuid(metaData.Video.Guid); t1.ProviderId = providerId; } } } if (results != null) { Cache.Set(CacheKeys.PlexLibaries, results, CacheKeys.TimeFrameMinutes.SchedulerCaching); } } else { results = Cache.GetOrSet(CacheKeys.PlexLibaries, () => GetLibraries(plexSettings), CacheKeys.TimeFrameMinutes.SchedulerCaching); } } catch (Exception ex) { Log.Error(ex, "Failed to obtain Plex libraries"); } return(results); }
private async Task ProcessTvShow(PlexServers servers, Metadata show, HashSet <PlexServerContent> contentToAdd, Dictionary <int, int> contentProcessed) { var seasonList = await PlexApi.GetSeasons(servers.PlexAuthToken, servers.FullUri, show.ratingKey); var seasonsContent = new List <PlexSeasonsContent>(); foreach (var season in seasonList.MediaContainer.Metadata) { seasonsContent.Add(new PlexSeasonsContent { ParentKey = season.parentRatingKey, SeasonKey = season.ratingKey, SeasonNumber = season.index, PlexContentId = show.ratingKey }); } // Do we already have this item? // Let's try and match var existingContent = await Repo.GetFirstContentByCustom(x => x.Title == show.title && x.ReleaseYear == show.year.ToString() && x.Type == PlexMediaTypeEntity.Show); // Just double check the rating key, since this is our unique constraint var existingKey = await Repo.GetByKey(show.ratingKey); if (existingKey != null) { // Damn son. // Let's check if they match up var doesMatch = show.title.Equals(existingKey.Title, StringComparison.CurrentCulture); if (!doesMatch) { // Something f****d up on Plex at somepoint... Damn, rebuild of lib maybe? // Lets delete the matching key await Repo.Delete(existingKey); existingKey = null; } else if (existingContent == null) { existingContent = await Repo.GetFirstContentByCustom(x => x.Key == show.ratingKey); } } if (existingContent != null) { // Let's make sure that we have some sort of ID e.g. Imdbid for this, // Looks like it's possible to not have an Id for a show // I suspect we cached that show just as it was added to Plex. if (!existingContent.HasImdb && !existingContent.HasTheMovieDb && !existingContent.HasTvDb) { var showMetadata = await PlexApi.GetMetadata(servers.PlexAuthToken, servers.FullUri, existingContent.Key); GetProviderIds(showMetadata, existingContent); await Repo.Update(existingContent); } // Just check the key if (existingKey != null) { // The rating key is all good! } else { // This means the rating key has changed somehow. // Should probably delete this and get the new one var oldKey = existingContent.Key; Repo.DeleteWithoutSave(existingContent); // Because we have changed the rating key, we need to change all children too var episodeToChange = Repo.GetAllEpisodes().Where(x => x.GrandparentKey == oldKey); if (episodeToChange.Any()) { foreach (var e in episodeToChange) { Repo.DeleteWithoutSave(e); } } await Repo.SaveChangesAsync(); existingContent = null; } } // Also make sure it's not already being processed... var alreadyProcessed = contentProcessed.Select(x => x.Value).Any(x => x == show.ratingKey); if (alreadyProcessed) { return; } // The ratingKey keeps changing... //var existingContent = await Repo.GetByKey(show.ratingKey); if (existingContent != null) { try { Logger.LogDebug("We already have show {0} checking for new seasons", existingContent.Title); // Ok so we have it, let's check if there are any new seasons var itemAdded = false; foreach (var season in seasonsContent) { var seasonExists = existingContent.Seasons.FirstOrDefault(x => x.SeasonKey == season.SeasonKey); if (seasonExists != null) { // We already have this season // check if we have the episode //if (episode != null) //{ // var existing = existingContent.Episodes.Any(x => // x.SeasonNumber == episode.parentIndex && x.EpisodeNumber == episode.index); // if (!existing) // { // // We don't have this episode, lets add it // existingContent.Episodes.Add(new PlexEpisode // { // EpisodeNumber = episode.index, // SeasonNumber = episode.parentIndex, // GrandparentKey = episode.grandparentRatingKey, // ParentKey = episode.parentRatingKey, // Key = episode.ratingKey, // Title = episode.title // }); // itemAdded = true; // } //} continue; } existingContent.Seasons.Add(season); itemAdded = true; } if (itemAdded) { await Repo.Update(existingContent); } } catch (Exception e) { Logger.LogError(LoggingEvents.PlexContentCacher, e, "Exception when adding new seasons to title {0}", existingContent.Title); } } else { try { Logger.LogDebug("New show {0}, so add it", show.title); // Get the show metadata... This sucks since the `metadata` var contains all information about the show // But it does not contain the `guid` property that we need to pull out thetvdb id... var showMetadata = await PlexApi.GetMetadata(servers.PlexAuthToken, servers.FullUri, show.ratingKey); var item = new PlexServerContent { AddedAt = DateTime.Now, Key = show.ratingKey, ReleaseYear = show.year.ToString(), Type = PlexMediaTypeEntity.Show, Title = show.title, Url = PlexHelper.GetPlexMediaUrl(servers.MachineIdentifier, show.ratingKey), Seasons = new List <PlexSeasonsContent>() }; GetProviderIds(showMetadata, item); // Let's just double check to make sure we do not have it now we have some id's var existingImdb = false; var existingMovieDbId = false; var existingTvDbId = false; if (item.ImdbId.HasValue()) { existingImdb = await Repo.GetAll().AnyAsync(x => x.ImdbId == item.ImdbId && x.Type == PlexMediaTypeEntity.Show); } if (item.TheMovieDbId.HasValue()) { existingMovieDbId = await Repo.GetAll().AnyAsync(x => x.TheMovieDbId == item.TheMovieDbId && x.Type == PlexMediaTypeEntity.Show); } if (item.TvDbId.HasValue()) { existingTvDbId = await Repo.GetAll().AnyAsync(x => x.TvDbId == item.TvDbId && x.Type == PlexMediaTypeEntity.Show); } if (existingImdb || existingTvDbId || existingMovieDbId) { // We already have it! return; } item.Seasons.ToList().AddRange(seasonsContent); contentToAdd.Add(item); } catch (Exception e) { Logger.LogError(LoggingEvents.PlexContentCacher, e, "Exception when adding tv show {0}", show.title); } } }