Ejemplo n.º 1
0
        /// <summary>
        /// Gets an WebClient object for use in
        /// communication with the server.
        /// </summary>
        protected override WebClient GetWebClient()
        {
            var client = new CompressionWebClient(Timeout);

            client.Headers.Set("Accept", "*/*");
            client.Headers.Set("Accept-Encoding", "gzip,deflate,*");
            return(client);
        }
Ejemplo n.º 2
0
        public static ActionResult InstallLAVFilters(Session session)
        {
            const string LAV_DOWNLOAD_URL        = "http://install.team-mediaportal.com/LAVFilters.exe";
            const string LAV_AUDIO_REGISTRY_PATH = @"CLSID\{E8E73B6B-4CB3-44A4-BE99-4F7BCB96E491}\InprocServer32";
            const string LAV_VIDEO_REGISTRY_PATH = @"CLSID\{EE30215D-164F-4A92-A4EB-9D4C13390F9F}\InprocServer32";

            try
            {
                session.Log("LAVFilters: Checking if LAVFilters are registered");

                // 1. check if LAV Filters are registered
                RegistryKey audioKey = Registry.ClassesRoot.OpenSubKey(LAV_AUDIO_REGISTRY_PATH, false);
                RegistryKey videoKey = Registry.ClassesRoot.OpenSubKey(LAV_VIDEO_REGISTRY_PATH, false);
                if (audioKey != null && videoKey != null)
                {
                    var audioFilterPath = audioKey.GetValue(null) as string;
                    var videoFilterPath = videoKey.GetValue(null) as string;
                    if (!string.IsNullOrEmpty(audioFilterPath) && !string.IsNullOrEmpty(videoFilterPath))
                    {
                        if (File.Exists(audioFilterPath) && File.Exists(videoFilterPath))
                        {
                            session.Log("LAVFilters: Found Audio Filter at '{0}'", audioFilterPath);
                            session.Log("LAVFilters: Found Video Filter at '{0}'", videoFilterPath);
                            return(ActionResult.NotExecuted);
                        }
                    }
                }

                // 2. download installer
                string tempLAVFileName = Path.Combine(Path.GetTempPath(), "LAVFilters.exe");
                // if temp file is already present it was probably downloaded earlier - use it
                if (!File.Exists(tempLAVFileName))
                {
                    var client = new CompressionWebClient();
                    session.Log("LAVFilters: Downloading installer...");
                    client.DownloadFile(LAV_DOWNLOAD_URL, tempLAVFileName);
                    client.Dispose();
                }
                if (!File.Exists(tempLAVFileName)) // download must have failed
                {
                    return(ActionResult.NotExecuted);
                }

                // 3. run installer
                session.Log("LAVFilters: Running installer from '{0}'", tempLAVFileName);
                var process = Process.Start(tempLAVFileName, "/SILENT /SP-");
                process.WaitForExit(1000 * 60); // wait max. 1 minute for the installer to finish

                session.Log("LAVFilters: Successfully installed");

                return(ActionResult.Success);
            }
            catch (Exception ex)
            {
                session.Log("LAVFilters: Error: " + ex.Message);
                return(ActionResult.Failure);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Gets a default list of feeds for the current user's region, with a fall back to English.
        /// </summary>
        /// <returns></returns>
        public static List <FeedBookmark> GetDefaultRegionalFeeds()
        {
            if (_defaultFeeds == null)
            {
                try
                {
                    // if the default feeds haven't been loaded yet, load xml from sever
                    using (var client = new CompressionWebClient())
                    {
                        // use our special client that has a lower timeout and uses compression by default
                        string defaultFeedsData = client.DownloadString(DEFAULT_FEEDS_URL);
                        // deserialize feeds from xml file
                        var serializer = new XmlSerializer(typeof(RegionalFeedBookmarksCollection));
                        using (var reader = new StringReader(defaultFeedsData))
                        {
                            var loadedFeeds = (RegionalFeedBookmarksCollection)serializer.Deserialize(reader);
                            _defaultFeeds = new Dictionary <string, List <FeedBookmark> >();
                            foreach (var region in loadedFeeds)
                            {
                                _defaultFeeds[region.RegionCode] = region.FeedBookmarks;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    ServiceRegistration.Get <ILogger>().Warn("Unable to load default news feeds xml from server: {0}", ex.Message);
                    // return an empty list, so next time this method is called it will try to download the default feeds again
                    return(new List <FeedBookmark>());
                }
            }
            // find the best matching list of feeds for the user's culture
            List <FeedBookmark> result;
            var culture = ServiceRegistration.Get <ILocalization>().CurrentCulture;

            // first try to get feeds for this language and region
            if (_defaultFeeds.TryGetValue(culture.Name, out result))
            {
                return(result.ToList());
            }
            // then try to get feeds for this language
            if (_defaultFeeds.TryGetValue(culture.TwoLetterISOLanguageName, out result))
            {
                return(result.ToList());
            }
            // fallback is always the generic english feeds
            return(_defaultFeeds["en"].ToList());
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Loads the image from the given path
 /// </summary>
 /// <param name="path">Path of image that should be used for this banner</param>
 /// <returns>True if successful, false otherwise</returns>
 protected Image LoadImage(String path)
 {
     try
     {
         WebClient    client  = new CompressionWebClient();
         byte[]       imgData = client.DownloadData(path);
         MemoryStream ms      = new MemoryStream(imgData);
         Image        img     = Image.FromStream(ms, true, true);
         return(img);
     }
     catch (Exception ex)
     {
         Log.Error("Error while loading image ", ex);
         return(null);
     }
 }
        private void DownloadThumbnail()
        {
            try
            {
                if (!Directory.Exists(Package.LocationFolder))
                {
                    Directory.CreateDirectory(Package.LocationFolder);
                }

                string url = Package.GeneralInfo.Params[ParamNamesConst.ONLINE_ICON].Value;
                if (url.IndexOf("://") < 0)
                {
                    url = "http://" + url;
                }
                var    client  = new CompressionWebClient();
                byte[] imgData = client.DownloadData(url);
                var    ms      = new MemoryStream(imgData);
                var    image   = Image.FromStream(ms);
                img_logo.Image = image;
                string fileName = "";
                if (ImageFormat.Jpeg.Equals(image.RawFormat))
                {
                    fileName = "icon.jpg";
                }
                else if (ImageFormat.Png.Equals(image.RawFormat))
                {
                    fileName = "icon.png";
                }
                else if (ImageFormat.Gif.Equals(image.RawFormat))
                {
                    fileName = "icon.gif";
                }
                else if (ImageFormat.Icon.Equals(image.RawFormat))
                {
                    fileName = "icon.ico";
                }
                else if (ImageFormat.Bmp.Equals(image.RawFormat))
                {
                    fileName = "icon.bmp";
                }
                if (!string.IsNullOrEmpty(fileName))
                {
                    File.WriteAllBytes(Path.Combine(Package.LocationFolder, fileName), imgData);
                }
            }
            catch (Exception) { } // invalid url or image file or no internet connection
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Loads the image from the given path
        /// </summary>
        /// <param name="path">Path of image that should be used for this banner</param>
        /// <returns>True if successful, false otherwise</returns>
        protected async Task <Image> LoadImageAsync(String path)
        {
            try
            {
                WebClient client  = new CompressionWebClient();
                byte[]    imgData = await client.DownloadDataTaskAsync(path).ConfigureAwait(false);

                MemoryStream ms  = new MemoryStream(imgData);
                Image        img = Image.FromStream(ms, true, true);
                return(img);
            }
            catch (Exception ex)
            {
                Log.Error("Error while loading image ", ex);
                return(null);
            }
        }
Ejemplo n.º 7
0
        public async Task <byte[]> LoadImageDataAsync()
        {
            string url = TvdbLinkCreator.CreateBannerLink(BannerPath);

            try
            {
                WebClient client = new CompressionWebClient();
                return(await client.DownloadDataTaskAsync(url).ConfigureAwait(false));
            }
            catch (WebException ex)
            {
                //Server probably returned an error/not found, just log at debug level
                Log.Debug($"TvdbBanner: WebException while loading image from '{url}' - {ex.Message}");
            }
            catch (Exception ex)
            {
                Log.Error($"TvdbBanner: Error while loading image from '{url}'", ex);
            }
            return(null);
        }
Ejemplo n.º 8
0
 /// <summary>
 /// Gets a default list of feeds for the current user's region, with a fall back to English.
 /// </summary>
 /// <returns></returns>
 public static List<FeedBookmark> GetDefaultRegionalFeeds()
 {
   if (_defaultFeeds == null)
   {
     try
     {
       // if the default feeds haven't been loaded yet, load xml from sever
       using (var client = new CompressionWebClient())
       {
         // use our special client that has a lower timeout and uses compression by default
         string defaultFeedsData = client.DownloadString(DEFAULT_FEEDS_URL);
         // deserialize feeds from xml file
         var serializer = new XmlSerializer(typeof(RegionalFeedBookmarksCollection));
         using (var reader = new StringReader(defaultFeedsData))
         {
           var loadedFeeds = (RegionalFeedBookmarksCollection) serializer.Deserialize(reader);
           _defaultFeeds = new Dictionary<string, List<FeedBookmark>>();
           foreach (var region in loadedFeeds)
             _defaultFeeds[region.RegionCode] = region.FeedBookmarks;
         }
       }
     }
     catch (Exception ex)
     {
       ServiceRegistration.Get<ILogger>().Warn("Unable to load default news feeds xml from server: {0}", ex.Message);
       // return an empty list, so next time this method is called it will try to download the default feeds again
       return new List<FeedBookmark>();
     }
   }
   // find the best matching list of feeds for the user's culture
   List<FeedBookmark> result;
   var culture = ServiceRegistration.Get<ILocalization>().CurrentCulture;
   // first try to get feeds for this language and region
   if (_defaultFeeds.TryGetValue(culture.Name, out result))
     return result.ToList();
   // then try to get feeds for this language
   if (_defaultFeeds.TryGetValue(culture.TwoLetterISOLanguageName, out result))
     return result.ToList();
   // fallback is always the generic english feeds
   return _defaultFeeds["en"].ToList();
 }
Ejemplo n.º 9
0
        protected override string DownloadJSON(string url)
        {
            var webClient = new CompressionWebClient(EnableCompression)
            {
                Encoding = Encoding.UTF8
            };

            foreach (var headerEntry in Headers)
            {
                webClient.Headers[headerEntry.Key] = headerEntry.Value;
            }

            LIMITER.RateLimit().Wait();
            try
            {
                return(webClient.DownloadString(url));
            }
            finally
            {
                LIMITER.RequestDone();
            }
        }
Ejemplo n.º 10
0
        protected override async Task <string> DownloadJSON(string url)
        {
            var webClient = new CompressionWebClient(EnableCompression)
            {
                Encoding = Encoding.UTF8
            };

            foreach (var headerEntry in Headers)
            {
                webClient.Headers[headerEntry.Key] = headerEntry.Value;
            }

            await LIMITER.RateLimit().ConfigureAwait(false);

            try
            {
                return(await webClient.DownloadStringTaskAsync(url).ConfigureAwait(false));
            }
            finally
            {
                LIMITER.RequestDone();
            }
        }
Ejemplo n.º 11
0
 void DownloadThread()
 {
     lock (this) { runningThreads++; }
     try
     {
         string tempFile             = Path.GetTempFileName();
         CompressionWebClient client = new CompressionWebClient();
         int index = -1;
         while (index < onlineFiles.Count && !cancel)
         {
             lock (this)
             {
                 counter++;
                 index = counter;
             }
             if (index >= onlineFiles.Count)
             {
                 return;
             }
             string onlineFile = onlineFiles[index];
             bool   success    = false;
             try
             {
                 client.DownloadFile(onlineFile, tempFile);
                 var extCol = ExtensionCollection.Load(tempFile);
                 lock (this)
                 {
                     MpeCore.MpeInstaller.KnownExtensions.Add(extCol);
                 }
                 success = true;
             }
             catch (Exception ex)
             {
                 System.Diagnostics.Debug.WriteLine(string.Format("Error downloading '{0}': {1}", onlineFile, ex.Message));
             }
             Invoke((Action)(() =>
             {
                 progressBar1.Value++;
                 listBox1.Items.Add(string.Format("{0}{1}", success ? "+" : "-", onlineFile));
                 listBox1.SelectedIndex = listBox1.Items.Count - 1;
                 listBox1.SelectedIndex = -1;
             }));
             if (File.Exists(tempFile))
             {
                 File.Delete(tempFile);
             }
         }
     }
     catch { }
     finally
     {
         lock (this)
         {
             runningThreads--;
             if (runningThreads <= 0)
             {
                 MpeCore.MpeInstaller.Save();
                 Invoke((Action)(() =>
                 {
                     DialogResult = cancel ? DialogResult.Cancel : DialogResult.OK;
                     Close();
                 }));
             }
         }
     }
 }
Ejemplo n.º 12
0
    public static ActionResult InstallLAVFilters(Session session)
    {
      const string LAV_DOWNLOAD_URL = "http://install.team-mediaportal.com/LAVFilters.exe";
      const string LAV_AUDIO_REGISTRY_PATH = @"CLSID\{E8E73B6B-4CB3-44A4-BE99-4F7BCB96E491}\InprocServer32";
      const string LAV_VIDEO_REGISTRY_PATH = @"CLSID\{EE30215D-164F-4A92-A4EB-9D4C13390F9F}\InprocServer32";

      try
      {
        session.Log("LAVFilters: Checking if LAVFilters are registered");
        
        // 1. check if LAV Filters are registered
        RegistryKey audioKey = Registry.ClassesRoot.OpenSubKey(LAV_AUDIO_REGISTRY_PATH, false);
        RegistryKey videoKey = Registry.ClassesRoot.OpenSubKey(LAV_VIDEO_REGISTRY_PATH, false);
        if (audioKey != null && videoKey != null)
        {
          var audioFilterPath = audioKey.GetValue(null) as string;
          var videoFilterPath = videoKey.GetValue(null) as string;
          if (!string.IsNullOrEmpty(audioFilterPath) && !string.IsNullOrEmpty(videoFilterPath))
          {
            if (File.Exists(audioFilterPath) && File.Exists(videoFilterPath))
            {
              session.Log("LAVFilters: Found Audio Filter at '{0}'", audioFilterPath);
              session.Log("LAVFilters: Found Video Filter at '{0}'", videoFilterPath);
              return ActionResult.NotExecuted;
            }
          }
        }

        // 2. download installer
        string tempLAVFileName = Path.Combine(Path.GetTempPath(), "LAVFilters.exe");
        // if temp file is already present it was probably downloaded earlier - use it
        if (!File.Exists(tempLAVFileName))
        {
          var client = new CompressionWebClient();
          session.Log("LAVFilters: Downloading installer...");
          client.DownloadFile(LAV_DOWNLOAD_URL, tempLAVFileName);
          client.Dispose();
        }
        if (!File.Exists(tempLAVFileName)) // download must have failed
          return ActionResult.NotExecuted;

        // 3. run installer
        session.Log("LAVFilters: Running installer from '{0}'", tempLAVFileName);
        var process = Process.Start(tempLAVFileName, "/SILENT /SP-");
        process.WaitForExit(1000 * 60); // wait max. 1 minute for the installer to finish

        session.Log("LAVFilters: Successfully installed");

        return ActionResult.Success;
      }
      catch (Exception ex)
      {
        session.Log("LAVFilters: Error: " + ex.Message);
        return ActionResult.Failure;
      }
    }
Ejemplo n.º 13
0
        protected override async Task <string> DownloadJSON(string url)
        {
            bool retry = false;

            lock (_requestSync)
            {
                if (_denyRequestsUntilTime.HasValue)
                {
                    if (RequestsDisabled)
                    {
                        return(null);
                    }
                    _failedRequests        = 0;
                    _denyRequestsUntilTime = null;
                }
            }
            var webClient = new CompressionWebClient(EnableCompression)
            {
                Encoding = Encoding.UTF8
            };

            foreach (var headerEntry in Headers)
            {
                webClient.Headers[headerEntry.Key] = headerEntry.Value;
            }

            await LIMITER.RateLimit().ConfigureAwait(false);

            try
            {
                string fullUrl = Mirrors[_currentMirror] + url;
                string json    = await webClient.DownloadStringTaskAsync(fullUrl).ConfigureAwait(false);

                if (_failedRequests > 0)
                {
                    _failedRequests--;
                }
                return(json);
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.Timeout ||
                    (ex.Response != null &&
                     (
                         (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.ServiceUnavailable ||
                          ((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.RequestTimeout)
                     )))
                {
                    //Rate limiting
                    _failedRequests++;
                    if (_failedRequests >= MAX_FAILED_REQUESTS)
                    {
                        DisableRequestsTemporarily();
                        return(null);
                    }
                    _currentMirror = (_currentMirror + 1) % Mirrors.Count;
                    retry          = true;
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                LIMITER.RequestDone();
            }

            if (retry)
            {
                return(await DownloadJSON(url).ConfigureAwait(false));
            }
            return(null);
        }