public MPPictureShares(IPluginData data) : base(data) { if (!Mediaportal.HasValidConfigFile()) { Supported = false; return; } IEnumerable <KeyValuePair <string, string> > list = Mediaportal.ReadSectionFromConfigFile("pictures"); Extensions = list.Where(x => x.Key == "extensions").Select(x => x.Value).First().Split(','); shares = new List <Share>(); int count = list.Where(x => x.Key.StartsWith("sharename")).Count(); for (int i = 0; i < count; i++) { if (list.Where(x => x.Key == "sharetype" + i).Select(x => x.Value).First() == "yes") { continue; } shares.Add(new Share() { Name = list.Where(x => x.Key == "sharename" + i).Select(x => x.Value).First(), Path = Path.GetFullPath(list.Where(x => x.Key == "sharepath" + i).Select(x => x.Value).First()), Index = i }); } shareCache = new Dictionary <string, Share>(); Supported = true; }
public IEnumerable <string> GetSearchDirectories() { string cacheDir = GetCacheDirectory(); if (!Directory.Exists(cacheDir)) { Directory.CreateDirectory(cacheDir); } List <string> dirs = new List <string>() { Configuration.Streaming.TVLogoDirectory, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Team MediaPortal", "MediaPortal", "thumbs", "tv", "logos"), Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Team MediaPortal", "MediaPortal", "thumbs", "tv", "logo"), Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Team MediaPortal", "MediaPortal", "thumbs", "Radio"), cacheDir }; if (Mediaportal.GetLocation(MediaportalDirectory.Skin) != null) { dirs.Add(Path.Combine(Mediaportal.GetLocation(MediaportalDirectory.Skin), "aMPed", "Media", "Logos", "Channels")); } return(dirs .Where(dir => Directory.Exists(dir)) .Distinct()); }
public static void Enable() { if (watcher != null) { return; } string path = Mediaportal.GetConfigFilePath(); watcher = new FileSystemWatcher(Path.GetDirectoryName(path), Path.GetFileName(path)); watcher.NotifyFilter = NotifyFilters.LastWrite; watcher.Changed += delegate(object sender, FileSystemEventArgs e) { try { if (ConfigurationChanged != null) { ConfigurationChanged(); } } catch (Exception ex) { Log.Warn("Failed to reload MPShares configuration", ex); } }; watcher.EnableRaisingEvents = true; }
protected IPEndPoint ReadConfiguredTVServerAddress() { // Try to read the TV server IP address from MediaPortal's configuration if (!Mediaportal.HasValidConfigFile()) { return(null); } // read the hostname Dictionary <string, string> tvSection = Mediaportal.ReadSectionFromConfigFile("tvservice"); if (tvSection == null || !tvSection.ContainsKey("hostname") || string.IsNullOrWhiteSpace(tvSection["hostname"])) { return(null); } string hostname = tvSection["hostname"]; try { // Return as IP addresses var address = Dns.GetHostAddresses(hostname).First(); return(new IPEndPoint(address, Configuration.DEFAULT_PORT)); } catch (SocketException) { Log.Info("Failed to resolve hostname {0} configured as default TV Server", hostname); return(null); } }
internal static string FolderSubstitution(string input) { // program data input = input.Replace("%ProgramData%", Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)); // streaming directory string streamingDirectory = Installation.GetFileLayoutType() == FileLayoutType.Source ? Path.Combine(Installation.GetSourceRootDirectory(), "Libraries", "Streaming") : Path.Combine(Installation.GetInstallDirectory(), "Streaming"); input = input.Replace("%mpextended-streaming%", streamingDirectory); // mp settings input = Regex.Replace(input, @"%mp-([^-]+)-([^-]+)%", delegate(Match match) { var section = Mediaportal.ReadSectionFromConfigFile(match.Groups[1].Value); if (!section.ContainsKey(match.Groups[2].Value)) { Log.Info("Replacing unknown Mediaportal path substitution %mp-{0}-{1}% with empty string", match.Groups[1].Value, match.Groups[2].Value); return(String.Empty); } else { return(section[match.Groups[2].Value]); } }); return(input); }
public bool Open() { try { ServiceState.RegisterStartupCondition(STARTUP_CONDITION); Log.Debug("Opening MPExtended ServiceHost version {0}", VersionUtil.GetFullVersionString()); // always log uncaught exceptions that cause the program to exit AppDomain.CurrentDomain.UnhandledException += delegate(object sender, UnhandledExceptionEventArgs e) { Log.Error("Unhandled exception", (Exception)e.ExceptionObject); if (e.IsTerminating) { Log.Fatal("Terminating because of previous exception"); } }; // set the thread locale to English; we don't output any user-facing messages from the service anyway. Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; // TODO: Set CultureInfo.DefaultThreadCurrent{,UI}Culture when we switch to .NET4.5 // setup our environment EnvironmentSetup.SetupEnvironment(); // start watching the configuration files for changes Configuration.Load(); Configuration.EnableChangeWatching(); // reload logger configuration, now that we can load the diagnostic section from the configuration Log.TraceLogging = Configuration.Services.Diagnostic.EnableTraceLogging; Log.Setup(); // load and host all services foreach (var service in ServiceInstallation.Instance.GetServices()) { Task.Factory.StartNew(StartService, (object)service); } wcfHost = new WCFHost(); wcfHost.Start(ServiceInstallation.Instance.GetWcfServices()); // ensure a service dependency on the TVEngine is set Task.Factory.StartNew(() => TVEDependencyInstaller.EnsureDependencyStatus(TVEDependencyInstaller.DependencyStatus.NoDependencySet)); // log system version details Mediaportal.LogVersionDetails(); Log.Debug("Running on CLR {0} on {1}", Environment.Version, Environment.OSVersion); // finish ServiceState.StartupConditionCompleted(STARTUP_CONDITION); Log.Trace("Opened MPExtended ServiceHost"); return(true); } catch (Exception ex) { Log.Error("Failed to open MPExtended ServiceHost", ex); return(false); } }
public UserSessionService() { var mpdir = Mediaportal.GetClientInstallationDirectory(); if (mpdir == null) { mpdir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Team MediaPortal", "MediaPortal"); } MPPath = Path.Combine(mpdir, "MediaPortal.exe"); }
public ShareLibrary(IPluginData data, string[] sections) { this.data = data; this.configuration = data.GetConfiguration("MP Shares"); if (!Mediaportal.HasValidConfigFile()) { Supported = false; return; } var localsharelist = new List <Share>(); foreach (string section in sections) { IEnumerable <KeyValuePair <string, string> > list = Mediaportal.ReadSectionFromConfigFile(section); string[] extensions = list.Where(x => x.Key == "extensions").Select(x => x.Value).First().Split(','); int count = list.Where(x => x.Key.StartsWith("sharename")).Count(); for (int i = 0; i < count; i++) { if (list.Where(x => x.Key == "sharetype" + i).Select(x => x.Value).First() == "yes") { continue; } string path = list.Where(x => x.Key == "sharepath" + i).Select(x => x.Value).First(); localsharelist.Add(new Share() { Name = list.Where(x => x.Key == "sharename" + i).Select(x => x.Value).First(), Path = path, Extensions = extensions.ToList(), }); } } // make shares unique shares = localsharelist.GroupBy(x => x.Path, (path, gshares) => new Share() { Name = gshares.First().Name, Path = path, Extensions = gshares.SelectMany(x => x.Extensions).ToList() }).ToList(); int shareNr = 0; foreach (Share share in shares) { share.Id = "s" + (shareNr++); } Supported = true; }
public ShareLibrary(IPluginData data, string[] sections) { this.data = data; this.configuration = data.GetConfiguration("MP Shares"); this.sections = sections; Supported = Mediaportal.HasValidConfigFile(); if (Supported) { ReadConfiguration(); ConfigurationChangeListener.ConfigurationChanged += ReadConfiguration; ConfigurationChangeListener.Enable(); } }
public bool Open() { try { ServiceState.RegisterStartupCondition(STARTUP_CONDITION); Log.Debug("Opening MPExtended ServiceHost version {0}", VersionUtil.GetFullVersionString()); // always log uncaught exceptions that cause the program to exit AppDomain.CurrentDomain.UnhandledException += delegate(object sender, UnhandledExceptionEventArgs e) { Log.Error("Unhandled exception", (Exception)e.ExceptionObject); if (e.IsTerminating) { Log.Fatal("Terminating because of previous exception"); } }; // start watching the configuration files for changes Configuration.Load(); Configuration.EnableChangeWatching(); // start the WCF services wcf.Start(Installation.GetAvailableServices().Where(x => x.WCFType != null)); // init all services var services = Installation.GetAvailableServices().Where(x => x.InitClass != null && x.InitMethod != null); foreach (var service in services) { BindingFlags flags = BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod; service.InitClass.InvokeMember(service.InitMethod, flags, null, null, null); } // ensure a service dependency on the TVEngine is set Task.Factory.StartNew(TVEDependencyInstaller.EnsureDependencyIsInstalled); // log MP version details Mediaportal.LogVersionDetails(); // finish ServiceState.StartupConditionCompleted(STARTUP_CONDITION); Log.Trace("Opened MPExtended ServiceHost"); return(true); } catch (Exception ex) { Log.Error("Failed to open MPExtended ServiceHost", ex); return(false); } }
private void ReadConfiguration() { var localsharelist = new List <Share>(); foreach (string section in sections) { IEnumerable <KeyValuePair <string, string> > list = Mediaportal.ReadSectionFromConfigFile(section); if (!list.Any()) { Log.Warn("MPShares: Failed to read section {0} from MediaPortal configuration file, aborting configuration reading", section); return; } string[] extensions = list.Where(x => x.Key == "extensions").Select(x => x.Value).First().Split(','); int count = list.Where(x => x.Key.StartsWith("sharename")).Count(); for (int i = 0; i < count; i++) { if (list.Where(x => x.Key == "sharetype" + i).Select(x => x.Value).First() == "yes") { continue; } string path = list.Where(x => x.Key == "sharepath" + i).Select(x => x.Value).First(); localsharelist.Add(new Share() { Name = list.Where(x => x.Key == "sharename" + i).Select(x => x.Value).First(), Path = path, Extensions = extensions.ToList(), }); } } // make shares unique shares = localsharelist.GroupBy(x => x.Path, (path, gshares) => new Share() { Name = gshares.First().Name, Path = path, Extensions = gshares.SelectMany(x => x.Extensions).ToList() }).ToList(); int shareNr = 0; foreach (Share share in shares) { share.Id = "s" + (shareNr++); } }
private LazyQuery <T> LoadMovies <T>() where T : WebMovieBasic, new() { string mp13Fields = Mediaportal.GetVersion() >= Mediaportal.MediaPortalVersion.MP1_3 ? "i.strDirector, i.dateAdded, " : String.Empty; string sql = "SELECT m.idMovie, i.strTitle, i.iYear, i.fRating, i.runtime, i.IMDBID, i.strPlot, i.strPictureURL, i.strCredits, i.iswatched, " + mp13Fields + "GROUP_CONCAT(p.strPath || f.strFilename, '|') AS fullpath, " + "GROUP_CONCAT(a.strActor, '|') AS actors, " + "GROUP_CONCAT(g.strGenre, '|') AS genres " + "FROM movie m " + "INNER JOIN movieinfo i ON m.idMovie = i.idMovie " + "LEFT JOIN files f ON m.idMovie = f.idMovie " + "LEFT JOIN path p ON f.idPath = p.idPath " + "LEFT JOIN actorlinkmovie alm ON m.idMovie = alm.idMovie " + "LEFT JOIN actors a ON alm.idActor = a.idActor " + "LEFT JOIN genrelinkmovie glm ON m.idMovie = glm.idMovie " + "LEFT JOIN genre g ON glm.idGenre = g.idGenre " + "WHERE %where " + "GROUP BY m.idMovie, i.strTitle, i.iYear, i.fRating, i.runtime, i.IMDBID, i.strPlot, i.strPictureURL"; return(new LazyQuery <T>(this, sql, new List <SQLFieldMapping>() { new SQLFieldMapping("m", "idMovie", "Id", DataReaders.ReadIntAsString), new SQLFieldMapping("fullpath", "Path", DataReaders.ReadPipeList), new SQLFieldMapping("actors", "Actors", ActorReader), new SQLFieldMapping("genres", "Genres", DataReaders.ReadPipeList), new SQLFieldMapping("i", "strPictureURL", "Artwork", ArtworkRetriever.ArtworkReader), new SQLFieldMapping("i", "strTitle", "Title", DataReaders.ReadString), new SQLFieldMapping("i", "iYear", "Year", DataReaders.ReadInt32), new SQLFieldMapping("i", "fRating", "Rating", DataReaders.ReadStringAsFloat), new SQLFieldMapping("i", "runtime", "Runtime", DataReaders.ReadInt32), new SQLFieldMapping("i", "IMDBID", "IMDBId", DataReaders.ReadString), new SQLFieldMapping("i", "strPlot", "Summary", DataReaders.ReadString), new SQLFieldMapping("i", "strCredits", "Writers", CreditsReader), new SQLFieldMapping("i", "iswatched", "Watched", DataReaders.ReadBoolean), new SQLFieldMapping("i", "strDirector", "Directors", DataReaders.ReadStringAsList), new SQLFieldMapping("i", "dateAdded", "DateAdded", DataReaders.ReadDateTime) })); }
public WebBoolResult IsMediaPortalRunning() { return(new WebBoolResult(Mediaportal.IsMediaPortalRunning())); }
public UserSessionService() { MPPath = Mediaportal.GetMediaPortalPath(); }
public MyFilms(IPluginData data) { try { // load database path if (!Mediaportal.HasValidConfigFile()) { Supported = false; return; } string configPath = Path.Combine(Mediaportal.GetLocation(MediaportalDirectory.Config), "MyFilms.xml"); if (!File.Exists(configPath)) { Supported = false; return; } // load config file XElement configFile = XElement.Load(configPath); string currentConfigNode = configFile .Elements("section") .First(x => x.Attribute("name").Value == "MyFilms") .Elements("entry") .First(x => x.Attribute("name").Value == "Current_Config") .Value; if (currentConfigNode != "pelis") { Log.Info("MyFilms: currently selected config is {0}, only pelis (Ant Movie Catalog) is supported at the moment", currentConfigNode); Supported = false; return; } var pelis = configFile .Elements("section") .First(x => x.Attribute("name").Value == "pelis"); DatabasePath = pelis .Elements("entry") .First(x => x.Attribute("name").Value == "AntCatalog") .Value; if (!File.Exists(DatabasePath)) { Log.Info("MyFilms: cannot find database {0}", DatabasePath); Supported = false; return; } PicturePath = pelis .Elements("entry") .First(x => x.Attribute("name").Value == "AntPicture") .Value; Supported = true; } catch (Exception ex) { Log.Warn("MyFilms: failed to load database path", ex); Supported = false; return; } // initialize some regular expressions stripActorName = new Regex(@"^([^(]*)(\(.*\))*", RegexOptions.Compiled); imdbId = new Regex(@"^.*imdb.[a-z]+/title/(tt[0-9]+)/*$", RegexOptions.Compiled); }
public WebAccessRequestResponse CreateAccessRequest(string clientName) { // generate the request string ip = WCFUtil.GetClientIPAddress(); string token = RandomGenerator.GetRandomString(40); WebAccessRequestResponse request = new WebAccessRequestResponse() { ClientName = clientName, IsAllowed = false, UserHasResponded = false, Token = token }; if (!Configuration.Services.AccessRequestEnabled) { Log.Info("User access request from {0} (claims to be client {1}) denied because user access requests are disabled on this system (check configuration)", ip, clientName); request.UserHasResponded = true; request.Token = null; return(request); } requests[token] = request; Log.Info("Received access request from {0} (claims to be client {1}), gave it token {2}", ip, clientName, token); CancellationTokenSource cancelToken = new CancellationTokenSource(); cancelTokens[token] = cancelToken; // ask the user askUserTasks[token] = Task.Factory.StartNew(delegate() { String result = null; if (Mediaportal.IsMediaPortalRunning() && WifiRemote.IsInstalled) { Log.Debug("Requesting user response through WifiRemote"); result = RequestAccessThroughWifiRemote(clientName, ip, cancelToken); } else { Log.Debug("Requesting user response through USS"); result = RequestAccessThroughPrivateUSS(token, clientName, ip, cancelToken); } Log.Debug("Finish asking user about access request with token {0}: {1}", token, result); // make sure that the request is still active (not cancelled) if (requests.ContainsKey(token)) { lock (requests[token]) { // set the necessary flags var matchingUsers = Configuration.Authentication.Users.Where(x => x.Username == result); requests[token].ErrorDuringProcessing = result == ERROR || !matchingUsers.Any(); requests[token].IsAllowed = !requests[token].ErrorDuringProcessing && result != null; requests[token].UserHasResponded = true; if (matchingUsers.Any()) { Log.Info("Sending account {0} in response to access request {1}", matchingUsers.First().Username, token); requests[token].Username = matchingUsers.First().Username; requests[token].Password = matchingUsers.First().GetPassword(); } else if (result == ERROR) { Log.Error("Failure during access request for token {0}", token); } else if (result != null) { Log.Warn("Didn't find a user named '{0}' - something strange is going on!", result); } } } return(true); }, cancelToken.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); // return the token to the client return(request); }
public MyFilms(IPluginData data) { Supported = false; try { // load MyFilms.xml path if (!Mediaportal.HasValidConfigFile()) { return; } string configPath = Path.Combine(Mediaportal.GetLocation(MediaportalDirectory.Config), "MyFilms.xml"); if (!File.Exists(configPath)) { return; } // load current config section XElement configFile; using (var handle = File.Open(configPath, FileMode.Open, FileAccess.Read, FileShare.Read)) configFile = XElement.Load(handle); var entries = configFile.Elements("section").First(x => x.Attribute("name").Value == "MyFilms").Elements("entry"); if (!entries.Any(x => x.Attribute("name").Value == "Default_Config") && !entries.Any(x => x.Attribute("name").Value == "Current_Config")) { Log.Info("MyFilms: couldn't find Current_Config or Default_Config value in MyFilms.xml"); return; } var configSectionName = entries.Any(x => x.Attribute("name").Value == "Current_Config") ? entries.First(x => x.Attribute("name").Value == "Current_Config").Value : entries.First(x => x.Attribute("name").Value == "Default_Config").Value; // look for database path var thisSection = configFile.Elements("section").First(x => x.Attribute("name").Value == configSectionName); if (!thisSection.Elements("entry").Any(x => x.Attribute("name").Value == "AntCatalog")) { Log.Info("MyFilms: couldn't find AntCatalog entry in current section ({0})", configSectionName); return; } // load database DatabasePath = thisSection.Elements("entry").FirstOrDefault(x => x.Attribute("name").Value == "AntCatalog").Value; if (!File.Exists(DatabasePath)) { Log.Info("MyFilms: cannot find database {0}", DatabasePath); return; } PicturePath = thisSection.Elements("entry").Any(x => x.Attribute("name").Value == "AntPicture") ? thisSection.Elements("entry").FirstOrDefault(x => x.Attribute("name").Value == "AntPicture").Value : String.Empty; sourcePrefix = thisSection.Elements("entry").Any(x => x.Attribute("name").Value == "PathStorage") ? thisSection.Elements("entry").FirstOrDefault(x => x.Attribute("name").Value == "PathStorage").Value : String.Empty; Supported = true; } catch (Exception ex) { Log.Warn("MyFilms: failed to load database path", ex); return; } // initialize some regular expressions stripActorName = new Regex(@"^([^(]*)(\(.*\))*", RegexOptions.Compiled); imdbId = new Regex(@"^.*imdb.[a-z]+/title/(tt[0-9]+)/*$", RegexOptions.Compiled); }