private async Task ProcessEvent(string eventName, string message) { message = Gzip.Decompress(message); if (_subsManager.HasSubscriptionsForEvent(eventName)) { using (var scope = _autofac.BeginLifetimeScope(AUTOFAC_SCOPE_NAME)) { var subscriptions = _subsManager.GetHandlersForEvent(eventName); foreach (var subscription in subscriptions) { if (subscription.IsDynamic) { var handler = scope.ResolveOptional(subscription.HandlerType) as IDynamicEventHandler; dynamic eventData = JObject.Parse(message); await handler.Handle(eventData); } else { var eventType = _subsManager.GetEventTypeByName(eventName); var integrationEvent = JsonConvert.DeserializeObject(message, eventType); var handler = scope.ResolveOptional(subscription.HandlerType); var concreteType = typeof(IEventHandler <>).MakeGenericType(eventType); await(Task) concreteType.GetMethod("Handle").Invoke( handler, new object[] { integrationEvent }); } } } } }
/// <summary> /// Loads the movie DB. /// </summary> private static void LoadMovieDB() { string path = Get.FileSystemPaths.PathDatabases + OutputName.MovieDb + Path.DirectorySeparatorChar; Directory.CreateDirectory(path); FileData[] files = FastDirectoryEnumerator.GetFiles(path, "*.movie.gz", SearchOption.TopDirectoryOnly); MovieDBFactory.MovieDatabase.Clear(); foreach (FileData file in files) { string json = Gzip.Decompress(file.Path); var movieModel = JsonConvert.DeserializeObject(json, typeof(MovieModel)) as MovieModel; MovieDBFactory.MovieDatabase.Add(movieModel); string title = FileNaming.RemoveIllegalChars(movieModel.Title); string poster = path + title + ".poster.jpg"; string fanart = path + title + ".fanart.jpg"; if (File.Exists(poster)) { movieModel.SmallPoster = ImageHandler.LoadImage(poster); } if (File.Exists(fanart)) { movieModel.SmallFanart = ImageHandler.LoadImage(fanart); } } }
private void ButtonBase_OnClick(object sender, RoutedEventArgs e) { var messageData = JsonConvert.DeserializeObject <PartyPhaseMessage>( Encoding.UTF8.GetString(Gzip.Decompress(Convert.FromBase64String("H4sIAAAAAAAA/+VYTU/jMBC98yuinKkU5zt7a0vFVgttRXtDCDnJQCMcuxs7sBXiv6+dNiH9wOwiUFbaXtJ6ZjzPL/bMq59PDMNMWEkFFOY3wz9Vv1dLzGGCc5Aj5vB7/3I2nk5u56OL0XBhVh4/SyhhnEq761jVSLLE+SpjdA4EEjEXWKjoZ2mSRgE4r7xN5N3ZXhxHPdv2cM/F4PVCP3B6gR/FyAl8cANUpdhGDZdYXDH2gWhextU6VNygP7mdjYc/ahtORAVVXGRcSIfrathonsYW+Oazda8goNM9AyuGQMgRm1ivqtytvFtLTVUVZO2aWL4iIEBZ7jDh0BhfTt/F5mmweR1jizTYoo6xBRpsQcfYHA02p2Nslgab9RFsoft54FwNOLdj4nwNNr9jbKEGW9gxNluDzf5SbNtvN9XzZttFkrIogIp+3UzGNIVfr7OaCRSQM5oBH6wPnJ5fGi9CeNMq1boIySBdyObX6kx7pDQNdbfnJMePHy9ziQOKuqXjOGVGxo0cJ9m9edR1U5gjy7FcPzpK4CxLHsZSNlBxSOTbHGPOs3sK6YzxTDGi4Eymk9EeipVcCNos0D202EdOMX/Itvne3VHvkYe05PWfgLMcRmm61lDn+shFked2Sd2bzO1z+nnU2VrqVkzKQoZspNtzge9Zdoj+M+IcLXHnxjlLjUBHWxhECHnOP0mbjb6KNldL21mB7xm9yOgDijTc+YEbRnLTdVrm0Fvkvb/l6uZUO5pAIV//YQOxjxPraYnVkPkX7/SN1H53qYPuUofdpY4+IfWOQKqlDWEJJjOC13DwJ7kWTwvZEsgiy+Eyk7JH6aDIkp89J2m/ghxnNKP3jWPgO35QXxUUOAU1eF2LM6mi2NN0JWTEtBTTuwGmKrqWdm2vuTxTm2uLzUkVRbljPytXJEuwAFUL+N4MBRSMkN37jjrwqrIdZG2ieLOohsyauhgLQWDAGBfH5x68OhzMHqtRHBNQKxuqy512gWrPrWTpI25J3sYJbywthd1rSpRZUvlqHyCdV9WozXsloytIPbSzoLpYDoAmy4MlxWp0RBXmQyivdXaT6aTecdXcZslhTB/lNmHFeobF0rZQ2Cj4l9/w94A44RIAAA==")))); UserInterfaceCore.ChangeMainPageView <ChampionSelectPage>(messageData); }
public void OnRiotMessagingServiceReceived(object sender, MessageEventArgs message) { if (!HasEnabledRmsGzip) { var data = JsonConvert.DeserializeObject <RiotMessageService>(Encoding.Default.GetString(message.RawData)); if (data.Subject == "rms:session") { RiotMessagingService.Send(Encoding.UTF8.GetBytes("{\r\n " + $"\"id\": \"{Guid.NewGuid():D}\",\r\n " + "\"payload\": " + "{\r\n " + "\"enable\": \"true\"\r\n " + "},\r\n " + "\"subject\": \"rms:gzip\",\r\n " + "\"type\": \"request\"\r\n}")); } else if (data.Subject == "rms:gzip" && data.Payload.Enabled == "true") { HasEnabledRmsGzip = true; } Debugger.Log(0, "", Encoding.Default.GetString(message.RawData) + "\n"); } else { var data = Encoding.UTF8.GetString(Gzip.Decompress(message.RawData)); Debugger.Log(0, "", data); } }
private static void Main(string[] args) { try { bool isCompress = true; if (args.Length < 3) { throw new Exception("Вы не ввели команду программы,имя исходного и результирующего файла"); } if (args[0] != "compress") { isCompress = false; if (args[0] != "decompress") { throw new Exception($"Команда \"{args[0]}\" не существует"); } } if (args.Length < 2) { throw new Exception("Вы не ввели имя исходного и результирующего файла"); } if (args.Length < 3) { throw new Exception("Вы не ввели имя результирующего файла"); } var readingFile = args[1]; var writingFile = args[2]; var gzip = new Gzip(); if (isCompress) { gzip.Compress(readingFile, writingFile); } else { gzip.Decompress(readingFile, writingFile); } Console.WriteLine("0"); Console.ReadKey(); } catch (Exception e) { Console.WriteLine($"Error message: {e.Message}"); Console.WriteLine("1"); Console.ReadKey(); } }
public void GzippingWorks() { var input = "{'IsPrimitive':true,'IsArray':true,'IsNumeric':false,'Type':'Array','Value':[{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'65'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'80'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'71'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'33'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'48'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'81'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'94'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'67'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'26'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'55'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'29'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'68'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'53'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'53'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'30'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'84'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'15'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'25'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'76'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'45'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'49'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'96'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'4'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'40'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'84'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'39'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'73'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'1'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'18'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'6'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'14'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'57'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'71'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'33'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'23'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'32'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'50'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'14'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'74'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'24'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'45'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'52'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'90'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'40'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'33'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'66'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'38'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'28'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'10'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'98'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'81'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'45'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'76'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'79'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'91'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'69'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'76'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'32'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'49'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'9'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'8'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'94'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'49'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'21'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'42'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'72'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'97'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'21'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'31'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'98'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'34'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'2'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'50'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'52'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'1'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'96'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'6'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'63'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'7'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'18'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'2'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'46'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'90'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'19'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'24'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'68'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'80'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'91'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'41'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'54'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'55'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'19'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'64'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'66'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'16'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'50'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'4'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'70'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'98'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'60'}]}"; var gzipped = Gzip.Compress(input); var decompressed = Gzip.Decompress(gzipped); Assert.AreEqual(decompressed, input); double inputByteCount = Encoding.UTF8.GetBytes(input).Length; double gzippedByteCount = Convert.FromBase64String(gzipped).Length; Assert.IsTrue(gzippedByteCount < (inputByteCount * 5)); }
private async void ReadRtmpResp(object sender, MessageReceivedEventArgs eventArgs) { if (eventArgs.Body is LcdsServiceProxyResponse proxy) { if (proxy.MessageId == null && proxy.MethodName == "tbdGameDtoV1" && proxy.ServiceName == "teambuilder-draft") { var messageData = JsonConvert.DeserializeObject <PartyPhaseMessage>( Encoding.UTF8.GetString(Gzip.Decompress(Convert.FromBase64String(proxy.Payload)))); if (messageData.PhaseName == "MATCHMAKING") { await Dispatcher.BeginInvoke(DispatcherPriority.Render, (Action)(() => StartGameButton.Content = "Matchmaking")); } else if (messageData.PhaseName == "AFK_CHECK") { if (_autoAccept) { var acceptData = await StaticVars.ActiveClient.RiotProxyCalls.DoLcdsProxyCallWithResponse( "teambuilder-draft", "indicateAfkReadinessV1", "{\"afkReady\":true}"); await Dispatcher.BeginInvoke(DispatcherPriority.Render, (Action)(() => { if (acceptData.Status != "ACK") { UserInterfaceCore.HolderPage.ShowNotification( UserInterfaceCore.ShortNameToString("UnknownResult")); } UserInterfaceCore.Flash?.Invoke(); UserInterfaceCore.HolderPage.ShowNotification( UserInterfaceCore.ShortNameToString("AcceptedGame")); })); } else { //U piece of shit. No. just no } } else if (messageData.PhaseName == "CHAMPION_SELECT") { await Dispatcher.BeginInvoke(DispatcherPriority.Render, (Action)(() => { //Really bad method. Don't think that this can play more than one game at a time. Will fix UserInterfaceCore.ChangeMainPageView <ChampionSelectPage>(messageData); })); } } } }
/// <summary> /// Loads the movie DB. /// </summary> private static void LoadMovieDB() { string path = Get.FileSystemPaths.PathDatabases + OutputName.MovieDb + Path.DirectorySeparatorChar; Directory.CreateDirectory(path); var files = FileHelper.GetFilesRecursive(path, "*.movie.gz").ToArray(); MovieDBFactory.MovieDatabase.Clear(); foreach (var file in files) { string json = Gzip.Decompress(file); var movieModel = JsonConvert.DeserializeObject(json, typeof(MovieModel)) as MovieModel; if (json.Contains(@"ChangedText"":false")) { movieModel.ChangedText = false; } if (json.Contains(@"ChangedPoster"":false")) { movieModel.ChangedPoster = false; } if (json.Contains(@"ChangedFanart"":false")) { movieModel.ChangedFanart = false; } movieModel.DatabaseSaved = true; MovieDBFactory.MovieDatabase.Add(movieModel); string title = FileNaming.RemoveIllegalChars(movieModel.Title); string poster = path + title + ".poster.jpg"; string fanart = path + title + ".fanart.jpg"; if (File.Exists(poster)) { movieModel.SmallPoster = ImageHandler.LoadImage(poster); } if (File.Exists(fanart)) { movieModel.SmallFanart = ImageHandler.LoadImage(fanart); } } }
private async void RiotConnection_MessageReceived(object sender, RtmpSharp.Messaging.MessageReceivedEventArgs e) { if (e.Body is LcdsServiceProxyResponse proxy) { if (proxy.MessageId == null && proxy.MethodName == "tbdGameDtoV1" && proxy.ServiceName == "teambuilder-draft") { var messageData = JsonConvert.DeserializeObject <PartyPhaseMessage>( Encoding.UTF8.GetString(Gzip.Decompress(Convert.FromBase64String(proxy.Payload)))); if (messageData.PhaseName == "CHAMPION_SELECT") { await Dispatcher.BeginInvoke(DispatcherPriority.Render, (Action)(() => { UpdateChampSelect(messageData); })); } } } }
/// <summary> /// Loads the scan series pick db /// </summary> private static void LoadScanSeriesPick() { string path = Get.FileSystemPaths.PathDatabases + OutputName.ScanSeriesPick + Path.DirectorySeparatorChar; Directory.CreateDirectory(path); if (File.Exists(path + "SeriesPickSeriesPick.gz")) { string json = Gzip.Decompress(path + "SeriesPickSeriesPick.gz"); ImportTvFactory.ScanSeriesPicks = JsonConvert.DeserializeObject(json, typeof(BindingList <ScanSeriesPick>)) as BindingList <ScanSeriesPick>; } }
public void OnRtmpMessage(object sender, MessageReceivedEventArgs eventArgs) { if (eventArgs.Body is ClientDynamicConfigurationNotification notif) { Configs = JsonConvert.DeserializeObject <Dictionary <string, Dictionary <string, object> > >( Encoding.UTF8.GetString(Gzip.Decompress(Convert.FromBase64String(notif.Configs)))); } else if (eventArgs.Body is PlayerCredentialsDTO cred) { StartGame(cred); } else if (eventArgs.Body is EndOfGameStats stats) { UserInterfaceCore.ChangeMainPageView <EndOfGameStats>(stats); } }
public void CompressTestCompatibility() { var rnd = new Random(); var inputFile = Path.GetTempFileName(); var compressedFile = Path.GetTempFileName(); var decompressedFile = Path.GetTempFileName(); try { using (var fileStream = new FileStream(inputFile, FileMode.Create)) { var buffer = new byte[3 * 1024 * 1024]; rnd.NextBytes(buffer); fileStream.Write(buffer); } var watch = new Stopwatch(); watch.Start(); Gzip.Compress(inputFile, compressedFile, 1, true); watch.Stop(); output.WriteLine("Compress Compatibility: " + watch.ElapsedMilliseconds); watch.Restart(); Gzip.Decompress(compressedFile, decompressedFile); watch.Stop(); output.WriteLine("Decompress Compatibility: " + watch.ElapsedMilliseconds); Assert.True(FileCompare(inputFile, decompressedFile)); } finally { if (File.Exists(inputFile)) { File.Delete(inputFile); } if (File.Exists(compressedFile)) { File.Delete(compressedFile); } if (File.Exists(decompressedFile)) { File.Delete(decompressedFile); } } }
private static async Task DownloadSubtitlesAsync(IEnumerable <SubtitleSelection> subs) { if (!subs.Any()) { return; } var downloads = await client.DownloadSubtitlesAsync(subs.Select(s => s.Selection.Id).ToArray()); foreach (var file in downloads) { var sub = subs.First(s => s.Selection.Id == file.Id); // Same subtitle might be used for multiple files var path = Path.ChangeExtension(sub.File, sub.Selection.FileFormat); var data = Convert.FromBase64String(file.Base64Data); File.WriteAllBytes(path, Gzip.Decompress(data)); } }
/// <summary> /// Loads the movie sets db. /// </summary> private static void LoadMovieSets() { string path = Get.FileSystemPaths.PathDatabases + OutputName.MovieSets + Path.DirectorySeparatorChar; Directory.CreateDirectory(path); var files = FileHelper.GetFilesRecursive(path, "*.MovieSet.gz").ToArray(); MovieSetManager.CurrentDatabase.Clear(); foreach (var file in files) { string json = Gzip.Decompress(file); var set = JsonConvert.DeserializeObject(json, typeof(MovieSetModel)) as MovieSetModel; MovieSetManager.CurrentDatabase.Add(set); } }
/// <summary> /// Loads the movie sets db. /// </summary> private static void LoadMovieSets() { string path = Get.FileSystemPaths.PathDatabases + OutputName.MovieSets + Path.DirectorySeparatorChar; Directory.CreateDirectory(path); FileData[] files = FastDirectoryEnumerator.GetFiles(path, "*.MovieSet.gz", SearchOption.TopDirectoryOnly); MovieSetManager.CurrentDatabase.Clear(); foreach (FileData file in files) { string json = Gzip.Decompress(file.Path); var set = JsonConvert.DeserializeObject(json, typeof(MovieSetModel)) as MovieSetModel; MovieSetManager.CurrentDatabase.Add(set); } }
/// <summary> /// Loads the TV DB db /// </summary> private static void LoadTvDB() { string path = Get.FileSystemPaths.PathDatabases + OutputName.TvDb + Path.DirectorySeparatorChar; Directory.CreateDirectory(path); var files = FileHelper.GetFilesRecursive(path, "*.Series.gz"); TvDBFactory.TvDatabase.Clear(); foreach (var file in files) { string json = Gzip.Decompress(file); var series = JsonConvert.DeserializeObject(json, typeof(Series)) as Series; string title = FileNaming.RemoveIllegalChars(series.SeriesName); string poster = path + title + ".poster.jpg"; string fanart = path + title + ".fanart.jpg"; string banner = path + title + ".banner.jpg"; if (File.Exists(poster)) { series.SmallPoster = ImageHandler.LoadImage(poster); } if (File.Exists(fanart)) { series.SmallFanart = ImageHandler.LoadImage(fanart); } if (File.Exists(banner)) { series.SmallBanner = ImageHandler.LoadImage(banner); } TvDBFactory.TvDatabase.Add(series.SeriesName, series); } TvDBFactory.GeneratePictureGallery(); TvDBFactory.GenerateMasterSeriesList(); }
/// <summary> /// Loads the media path db. /// </summary> private static void LoadMediaPathDb() { if (MediaPathDBFactory.MediaPathDB == null) { MediaPathDBFactory.MediaPathDB = new BindingList <MediaPathModel>(); } string path = Get.FileSystemPaths.PathDatabases + OutputName.MediaPathDb + Path.DirectorySeparatorChar; Directory.CreateDirectory(path); IEnumerable <string> files = Directory.EnumerateFiles(path, "*.MediaPath.gz", SearchOption.TopDirectoryOnly); foreach (string file in files) { string json = Gzip.Decompress(file); var mediaPath = JsonConvert.DeserializeObject(json, typeof(MediaPathModel)) as MediaPathModel; MediaPathDBFactory.MediaPathDB.Add(mediaPath); } }
/// <summary> /// Deserialize xml. /// </summary> /// <param name="scraperGroupName">The scraper group name</param> /// <returns> /// A MovieScraperGroupModel object /// </returns> public static MovieScraperGroupModel DeserializeXml(string scraperGroupName) { string path = Get.FileSystemPaths.PathDirScraperGroupsMovies + scraperGroupName + ".gz"; try { if (File.Exists(path)) { string json = Gzip.Decompress(path); var scraperGroupModel = JsonConvert.DeserializeObject(json, typeof(MovieScraperGroupModel)) as MovieScraperGroupModel; return(scraperGroupModel); } } catch (Exception ex) { Log.WriteToLog( LogSeverity.Error, 0, "Could not load scraper group", path + Environment.NewLine + ex.Message); } return(null); }
private async void DownloadButtonClick(object sender, EventArgs e) { var sub = subtitleGrid.SelectedSubtitle; if (sub == null) { return; } StatusText = "Downloading subtitle..."; var file = await DownloadSubtitle(sub.Id); if (file == null) { StatusText = string.Empty; return; } var data = Convert.FromBase64String(file.Base64Data); var subFilePath = Path.ChangeExtension(fileNameTextBox.Text, sub.FileFormat); SaveSubtitle(subFilePath, Gzip.Decompress(data)); }
public void DecompressIncorrectFileTest() { var rnd = new Random(); var inputFile = Path.GetTempFileName(); var decompressedFile = Path.GetTempFileName(); try { using (var fileStream = new FileStream(inputFile, FileMode.Create)) { var buffer = new byte[3 * 1024 * 1024]; rnd.NextBytes(buffer); fileStream.Write(buffer); } var exceptions = Assert.Throws <AggregateException>(() => Gzip.Decompress(inputFile, decompressedFile)); Assert.NotNull(exceptions.InnerExceptions); Assert.NotEmpty(exceptions.InnerExceptions); var exception = exceptions.InnerExceptions.FirstOrDefault(ex => ex is InvalidDataException); Assert.True(exception != null, "Gzip need throw InvalidDataException exception"); } finally { if (File.Exists(inputFile)) { File.Delete(inputFile); } if (File.Exists(decompressedFile)) { File.Delete(decompressedFile); } } }
private static void LoadMovies(string path, string[] files, BindingList <MovieModel> database) { var parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = 6 }; Parallel.ForEach( files, parallelOptions, file => { string json = Gzip.Decompress(file); var movieModel = JsonConvert.DeserializeObject(json, typeof(MovieModel)) as MovieModel; if (json.Contains(@"ChangedText"":false")) { movieModel.ChangedText = false; } if (json.Contains(@"ChangedPoster"":false")) { movieModel.ChangedPoster = false; } if (json.Contains(@"ChangedFanart"":false")) { movieModel.ChangedFanart = false; } movieModel.DatabaseSaved = true; if (movieModel.AssociatedFiles.GetMediaCollection().Count > 0) { if (!File.Exists(movieModel.AssociatedFiles.GetMediaCollection()[0].PathAndFilename)) { Log.WriteToLog( LogSeverity.Info, LoggerName.GeneralLog, "Internal > DatabaseIOFactory > LoadMovieDB", string.Format( "Deleting {0}. Movie not found on the filesystem", movieModel.AssociatedFiles.GetMediaCollection()[0].FileName)); // We should check for network path and make sure the file has actually been deleted or removed File.Delete(file); } } if (movieModel != null) { lock (database) { database.Add(movieModel); } } string title = FileNaming.RemoveIllegalChars(movieModel.Title); string poster = path + title + ".poster.jpg"; string fanart = path + title + ".fanart.jpg"; if (File.Exists(poster)) { movieModel.SmallPoster = ImageHandler.LoadImage(poster); } if (File.Exists(fanart)) { movieModel.SmallFanart = ImageHandler.LoadImage(fanart); } }); }
public static async Task Login(object sender, Dispatcher disp, string user, string pass, string region, RiotAuthOpenIdConfiguration openId, bool save, Action callback) { var regionData = RiotClientData.ReadSystemRegionData(Path.Combine(StaticVars.IcyWindLocation, "IcyWindAssets", "system", "system.yaml"), region); var loginDataAuthToken = GetLoginToken(user, pass, regionData, openId); if (loginDataAuthToken.Result != RiotAuthResult.Success) { await disp.BeginInvoke(DispatcherPriority.Render, (Action)(() => { UserInterfaceCore.HolderPage.ShowNotification(UserInterfaceCore.ShortNameToString("InvalidRiotCred").Replace("{User}", user)); if (sender.GetType() == typeof(LoginPage)) { ((LoginPage)sender).LoginProgressBar.Visibility = Visibility.Hidden; } })); return; } var userInfo = GetLoginUserInfo(loginDataAuthToken, openId); //I have no idea why this is called, it doesn't seem to be used for much but it simulates the //Connections that riot has. Don't question riot, they do funny things. var loginEnt = GetLoginEntitlements(regionData, loginDataAuthToken); var rsoAuth = GetLoginLcdsRsoLoginQueue(regionData, loginDataAuthToken, userInfo); var userClient = await LoginRtmps(regionData, JsonConvert.SerializeObject(rsoAuth.Lqt), loginDataAuthToken.AccessTokenJson.AccessToken, user); if (userClient.Success) { userClient.Client.RiotMessagingService = new WebSocket(regionData.Servers.Rms.RmsUrl.Replace(":443", "") + $"/rms/v1/session?token={loginDataAuthToken.AccessTokenJson.AccessToken}&id={Guid.NewGuid():D}&token_type=access"); userClient.Client.Token = loginDataAuthToken; userClient.Client.Region = regionData; userClient.Client.OpenId = openId; var ping = new Thread(() => { Thread.Sleep(TimeSpan.FromSeconds(60)); userClient.Client.RiotMessagingService.Ping(); }); userClient.Client.RiotMessagingService.OnMessage += userClient.Client.OnRiotMessagingServiceReceived; userClient.Client.RiotMessagingService.OnOpen += (o, args) => ping.Start(); //userClient.Client.RiotMessagingService.Connect(); userClient.Client.SaveToServer = save; var str1 = $"gn-{userClient.Client.RiotSession.AccountSummary.AccountId}"; var str2 = $"cn-{userClient.Client.RiotSession.AccountSummary.AccountId}"; var str3 = $"bc-{userClient.Client.RiotSession.AccountSummary.AccountId}"; Task <bool>[] taskArray = { userClient.Client.RiotConnection.SubscribeAsync("my-rtmps", "messagingDestination", str1, str1), userClient.Client.RiotConnection.SubscribeAsync("my-rtmps", "messagingDestination", str2, str2), userClient.Client.RiotConnection.SubscribeAsync("my-rtmps", "messagingDestination", "bc", str3) }; await Task.WhenAll(taskArray); var plainTextbytes = Encoding.UTF8.GetBytes(userClient.Client.RiotSession.AccountSummary.Username + ":" + userClient.Client.RiotSession.Token); var reconnectToken = Convert.ToBase64String(plainTextbytes); userClient.Client.RiotConnection.MessageReceived += userClient.Client.OnRtmpMessage; await userClient.Client.RiotConnection.LoginAsync(user, userClient.Client.RiotSession.Token); userClient.Client.RiotProxyCalls = new LcdsRiotCalls((RiotCalls)userClient.Client); userClient.Client.RegionData.RegionName = region; userClient.Client.LoginDataPacket = await((RiotCalls)userClient.Client).GetLoginDataPacketForUser(); var pref = GetPlayerPref(loginDataAuthToken, userClient.Client.Configs["PlayerPreferences"]["ServiceEndpoint"].ToString(), regionData.PlatformId.ToString(), userClient.Client.LoginDataPacket.AllSummonerData.Summoner.AcctId.ToString()); var jsonPref = JsonConvert.DeserializeObject <Dictionary <string, string> >(pref); var deserializer = new Deserializer(); var tempData = Encoding.UTF8.GetString(Deflate.Uncompress(Convert.FromBase64String(jsonPref["data"]))); TextReader sr = new StringReader(tempData); var yamlObject = deserializer.Deserialize(sr); var serializer = new JsonSerializer(); var w = new StringWriter(); serializer.Serialize(w, yamlObject); var jsonAsRunesReforaged = JsonConvert.DeserializeObject <RunesReforaged>(w.ToString()); userClient.Client.RunesReforaged = jsonAsRunesReforaged; //Connect to chat now await ChatAuth.ConnectToChat(regionData, userClient.Client, Convert.ToBase64String(Encoding.UTF8.GetBytes(loginDataAuthToken.AccessTokenJson.AccessToken))); userClient.Client.DoHeartbeatShit(); userClient.Client.ActiveBoots = await((RiotCalls)userClient.Client).GetSummonerActiveBoosts(); userClient.Client.ChampionList = await((RiotCalls)userClient.Client).GetAvailableChampions(); var da = await userClient.Client.RiotProxyCalls.WithMoreThanOneResponce("teambuilder-draft", "retrieveGameloopPlayerInfoV1", 2, ""); userClient.Client.RiotQueues = await((RiotCalls)userClient.Client).GetAllQueues(); //Create a game var inventoryToken = GetInventoryFromType(regionData, loginDataAuthToken, userClient.Client.Configs["Inventory"]["BaseServiceUrl"].ToString(), userClient.Client.LoginDataPacket.AllSummonerData.Summoner.Puuid.ToString("D"), userClient.Client.LoginDataPacket.AllSummonerData.Summoner.AcctId.ToString(), "QUEUE_ENTRY"); var leaguesTierRankToken = await userClient.Client.RiotProxyCalls.DoLcdsProxyCallWithResponse("leagues", "getMySignedQueueTierRank", ""); var simpleInventoryToken = GetInventorySimpleFromType(regionData, loginDataAuthToken, userClient.Client.Configs["Inventory"]["BaseServiceUrl"].ToString(), userClient.Client.LoginDataPacket.AllSummonerData.Summoner.Puuid.ToString("D"), userClient.Client.LoginDataPacket.AllSummonerData.Summoner.AcctId.ToString(), "CHAMPION&inventoryTypes=CHAMPION_SKIN"); userClient.Client.InvToken = simpleInventoryToken; var summonerToken = await userClient.Client.RiotProxyCalls.DoLcdsProxyCallWithResponse("summoner", "getMySummoner", ""); //userInfo :D var party = new CreatePartyService { AccountId = userClient.Client.LoginDataPacket.AllSummonerData.Summoner.AcctId, CreatedAt = 0, CurrentParty = null, EligibilityHash = 0, Parties = null, PlatformId = regionData.PlatformId.ToString(), Puuid = userClient.Client.LoginDataPacket.AllSummonerData.Summoner.Puuid.ToString("D"), Registration = new Registration { InventoryToken = null, InventoryTokens = new[] { JsonConvert.DeserializeObject <InventoryService>(inventoryToken).Data.ItemsJwt, }, LeaguesTierRankToken = Encoding.UTF8.GetString( Gzip.Decompress(Convert.FromBase64String(leaguesTierRankToken.Payload))), SimpleInventoryToken = JsonConvert.DeserializeObject <InventoryService>(simpleInventoryToken) .Data .ItemsJwt, SummonerToken = summonerToken.Payload, UserInfoToken = userInfo }, ServerUtcMillis = 0, SummonerId = userClient.Client.LoginDataPacket.AllSummonerData.Summoner.SumId, Version = 0 }; var sendPartyHelper = new BodyHelper { body = JsonConvert.SerializeObject(party), url = $"v1/players/{userClient.Client.LoginDataPacket.AllSummonerData.Summoner.Puuid:D}" }; var partyRtmp = await userClient.Client.RiotProxyCalls.DoLcdsProxyCallWithResponse("parties.service", "proxy", JsonConvert.SerializeObject(sendPartyHelper)); userClient.Client.CurrentParty = JsonConvert.DeserializeObject <PartyPayload>(partyRtmp.Payload); //New restricted queue method sendPartyHelper = new BodyHelper { body = "", method = "GET", url = $"v1/parties/{userClient.Client.CurrentParty.Payload.CurrentParty.PartyId}/eligibility" }; var partyElg = await userClient.Client.RiotProxyCalls.DoLcdsProxyCallWithResponse("parties.service", "proxy", JsonConvert.SerializeObject(sendPartyHelper)); //F*****g removed by riot /* * //Get restricted Queues * var activeQueues = userClient.Client.RiotQueues.Where(x => x.QueueState == "ON"); * * var str = string.Empty; * var queueArr = activeQueues.Select(queue => (int)queue.Id).OrderBy(i => i); * str = queueArr.Aggregate(str, (current, queue) => current + (queue + ",")); * * str = str.Remove(str.Length - 1); * * var resp = await userClient.Client.RiotProxyCalls.DoLcdsProxyCallWithResponse("gatekeeper", * "getQueueRestrictionsForQueuesV2", $"{{\"queueIds\":[{str}],\"queueRestrictionsToExclude\":" + * "[\"QUEUE_DODGER\",\"LEAVER_BUSTED\",\"LEAVER_BUSTER" + * $"_TAINTED_WARNING\"],\"summonerIds\":[{userClient.Client.LoginDataPacket.AllSummonerData.Summoner.SumId}]}}"); * //*/ if (StaticVars.UserClientList == null) { StaticVars.UserClientList = new List <UserClient>(); } StaticVars.UserClientList.Add(userClient.Client); if (sender.GetType() == typeof(AccountSelectorPage) && save) { var acc = new IcyWindRiotAccountInfo { Password = pass, Region = region, Username = user, SumIcon = userClient.Client.LoginDataPacket.AllSummonerData.Summoner.ProfileIconId, SumLevel = userClient.Client.LoginDataPacket.AllSummonerData.SummonerLevelAndPoints.SummonerLevel, SumName = userClient.Client.LoginDataPacket.AllSummonerData.Summoner.InternalName, }; if (StaticVars.AccountInfo == null) { return; } if (StaticVars.AccountInfo.Accounts == null) { StaticVars.AccountInfo.Accounts = string.Empty; } var crypto = AES.EncryptBase64(StaticVars.Password, JsonConvert.SerializeObject(acc)); /* * if (StaticVars.LoginCred.AccountData.All(x => x.CryptString != crypto)) * { * StaticVars.LoginCred.AccountData.Add(new IcyWindRiotAccountCrypted * { * CryptString = crypto, * Region = region, * SumUuid = userClient.Client.LoginDataPacket.AllSummonerData.Summoner.Puuid.ToString(), * SumId = userClient.Client.LoginDataPacket.AllSummonerData.Summoner.SumId * }); * if (callback != null) * { * await disp.BeginInvoke(DispatcherPriority.Render, callback); * } * } * else * { * return; * } * * if (StaticVars.UserClientList.Count(x => x.SaveToServer) > 4 && !(StaticVars.AccountInfo.IsDev || * StaticVars.AccountInfo.IsPaid || * StaticVars.AccountInfo.IsPro)) * { * return; * } * var output = await AccountManager.UpdateAccountInfo(StaticVars.LoginCred); * * //*/ } } }
/// <summary> /// Gets the specified download item. /// </summary> /// <param name="downloadItem">The download item.</param> public void Get(DownloadItem downloadItem) { Log.WriteToLog(LogSeverity.Info, downloadItem.ThreadID, string.Format("Processing HTML Started"), string.Format("{0}", downloadItem.Url)); downloadItem.Result = new HtmlResult(); downloadItem.Progress.Message = "Downloading " + downloadItem.Url; var cachePath = WebCache.GetPathFromUrl(downloadItem.Url, downloadItem.Section); Folders.CheckExists(cachePath, true); if (!downloadItem.IgnoreCache && !downloadItem.Url.Contains("YNoCache")) { if (File.Exists(cachePath + ".txt.gz")) { Log.WriteToLog(LogSeverity.Info, downloadItem.ThreadID, string.Format(CultureInfo.CurrentCulture, "Url Found in Cache"), string.Format(CultureInfo.CurrentCulture, "{0}", downloadItem.Url)); downloadItem.Result = new HtmlResult { Result = Gzip.Decompress(cachePath + ".txt.gz"), Success = true }; return; } } if (InternalHandlers.Check(downloadItem)) { InternalHandlers.Process(downloadItem, cachePath); return; } try { Log.WriteToLog( LogSeverity.Info, downloadItem.ThreadID, string.Format(CultureInfo.CurrentCulture, "Downloading"), string.Format(CultureInfo.CurrentCulture, "{0}", downloadItem.Url)); downloadItem.Url = downloadItem.Url.Replace(" ", "+").Replace("%20", "+"); var webClient = new WebClient { Proxy = null }; if (Settings.Get.Web.EnableProxy) { webClient.Proxy = new WebProxy(Settings.Get.Web.ProxyUserName, (int)Settings.Get.Web.ProxyPort); } webClient.Headers.Add("user-agent", Settings.Get.Web.UserAgent); var encode = Encoding.GetEncoding(1252); foreach (var encoding in Settings.Get.Web.WebEncodings) { if (downloadItem.Url.Contains(encoding.Key)) { encode = encoding.Value; break; } } webClient.Encoding = encode; var outputString = webClient.DownloadString(downloadItem.Url); Log.WriteToLog( LogSeverity.Info, downloadItem.ThreadID, string.Format(CultureInfo.CurrentCulture, "Download Complete. Saving to Cache"), string.Format(CultureInfo.CurrentCulture, "{0}", downloadItem.Url)); if (encode != Encoding.UTF8) { var origBytes = encode.GetBytes(outputString); var newBytes = Encoding.Convert(encode, Encoding.UTF8, origBytes); outputString = Encoding.UTF8.GetString(newBytes); encode = Encoding.UTF8; } File.WriteAllText(cachePath + ".txt.tmp", outputString, encode); Gzip.Compress(cachePath + ".txt.tmp", cachePath + ".txt.gz"); File.Delete(cachePath + ".txt.tmp"); Log.WriteToLog( LogSeverity.Info, downloadItem.ThreadID, string.Format(CultureInfo.CurrentCulture, "Process Complete."), string.Format(CultureInfo.CurrentCulture, "{0}", downloadItem.Url)); downloadItem.Result.Result = outputString; downloadItem.Result.Success = true; return; } catch (Exception ex) { Log.WriteToLog(LogSeverity.Error, LoggerName.GeneralLog, string.Format("Download Html {0}", downloadItem.Url), ex.Message); return; } }
/// <summary> /// Loads the TV DB db /// </summary> private static void LoadTvDB() { string path = Get.FileSystemPaths.PathDatabases + OutputName.TvDb + Path.DirectorySeparatorChar; Directory.CreateDirectory(path); List <string> files = FileHelper.GetFilesRecursive(path, "*.Series.gz"); TvDBFactory.TvDatabase.Clear(); var hidden = path + "hidden.hiddenSeries.gz"; if (File.Exists(hidden)) { var json = Gzip.Decompress(hidden); TvDBFactory.HiddenTvDatabase = JsonConvert.DeserializeObject(json, typeof(BindingList <Series>)) as BindingList <Series>; } var parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = 6 }; Parallel.ForEach( files, parallelOptions, file => { var json = Gzip.Decompress(file); var series = JsonConvert.DeserializeObject(json, typeof(Series)) as Series; string title = FileNaming.RemoveIllegalChars(series.SeriesName); string poster = path + title + ".poster.jpg"; string fanart = path + title + ".fanart.jpg"; string banner = path + title + ".banner.jpg"; if (File.Exists(poster)) { series.SmallPoster = ImageHandler.LoadImage(poster); } if (File.Exists(fanart)) { series.SmallFanart = ImageHandler.LoadImage(fanart); } if (File.Exists(banner)) { series.SmallBanner = ImageHandler.LoadImage(banner); } foreach (var season in series.Seasons) { for (int index = 0; index < season.Value.Episodes.Count; index++) { var episode = season.Value.Episodes[index]; if (episode.FilePath.PathAndFilename != string.Empty && !File.Exists(episode.FilePath.PathAndFilename)) { Log.WriteToLog( LogSeverity.Info, LoggerName.GeneralLog, "Internal > DatabaseIOFactory > LoadTvDB", string.Format( "Deleting {0}. Episode not found on the filesystem", episode.FilePath.PathAndFilename)); // We should check for network path and make sure the file has actually been deleted or removed File.Delete(file); series.Seasons[season.Key].Episodes.Remove(episode); } } } lock (TvDBFactory.TvDatabase) { TvDBFactory.TvDatabase.Add(series.SeriesName, series); } }); TvDBFactory.GeneratePictureGallery(); TvDBFactory.GenerateMasterSeriesList(); }
public async Task <RiotQueue[]> GetAllQueues() { var str = await InvokeAsync <string>("matchmakerService", "getAllQueuesCompressed"); return(JsonConvert.DeserializeObject <RiotQueue[]>(Encoding.UTF8.GetString(Gzip.Decompress(Convert.FromBase64String(str))))); }
/// <summary> /// Gets the specified download item. /// </summary> /// <param name="downloadItem">The download item.</param> public void Get(DownloadItem downloadItem) { Log.WriteToLog(LogSeverity.Info, downloadItem.ThreadID, string.Format("Processing HTML Started"), string.Format("{0}", downloadItem.Url)); downloadItem.Result = new HtmlResult(); downloadItem.Progress.Message = "Downloading " + downloadItem.Url; var cachePath = WebCache.GetPathFromUrl(downloadItem.Url, downloadItem.Section); Folders.CheckExists(cachePath, true); if (!downloadItem.IgnoreCache && !downloadItem.Url.Contains("YNoCache")) { if (File.Exists(cachePath + ".txt.gz")) { Log.WriteToLog(LogSeverity.Info, downloadItem.ThreadID, string.Format(CultureInfo.CurrentCulture, "Url Found in Cache"), string.Format(CultureInfo.CurrentCulture, "{0}", downloadItem.Url)); downloadItem.Result = new HtmlResult { Result = Gzip.Decompress(cachePath + ".txt.gz"), Success = true }; return; } } try { Log.WriteToLog( LogSeverity.Info, downloadItem.ThreadID, string.Format(CultureInfo.CurrentCulture, "Downloading"), string.Format(CultureInfo.CurrentCulture, "{0}", downloadItem.Url)); downloadItem.Url = downloadItem.Url.Replace(" ", "+").Replace("%20", "+"); var webClient = new WebClient { Proxy = null }; webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); var outputString = webClient.DownloadString(downloadItem.Url); var encode = Encoding.GetEncoding(1252); if (downloadItem.Url.IndexOf("ofdb", StringComparison.CurrentCultureIgnoreCase) != -1 || downloadItem.Url.Contains("sratim") || downloadItem.Url.Contains("filmweb") || downloadItem.Url.Contains("allocine")) { encode = Encoding.GetEncoding("UTF-8"); } if (downloadItem.Url.Contains("filmaffinity") || downloadItem.Url.Contains("filmdelta")) { encode = Encoding.GetEncoding("ISO-8859-1"); } if (downloadItem.Url.Contains("kinopoisk")) { encode = Encoding.GetEncoding("windows-1251"); } Log.WriteToLog( LogSeverity.Info, downloadItem.ThreadID, string.Format(CultureInfo.CurrentCulture, "Download Complete. Saving to Cache"), string.Format(CultureInfo.CurrentCulture, "{0}", downloadItem.Url)); File.WriteAllText(cachePath + ".txt.tmp", outputString, encode); Gzip.Compress(cachePath + ".txt.tmp", cachePath + ".txt.gz"); File.Delete(cachePath + ".txt.tmp"); Log.WriteToLog( LogSeverity.Info, downloadItem.ThreadID, string.Format(CultureInfo.CurrentCulture, "Process Complete."), string.Format(CultureInfo.CurrentCulture, "{0}", downloadItem.Url)); downloadItem.Result.Result = outputString; downloadItem.Result.Success = true; return; } catch (Exception ex) { Log.WriteToLog(LogSeverity.Error, LoggerName.GeneralLog, string.Format("Download Html {0}", downloadItem.Url), ex.Message); return; } }