public WikiInfo(string userAgent, string baseUrl = null, string apiPath = null, IEnumerable<Namespace> namespaces = null) { PagesSourcePageSize = 50; if (string.IsNullOrWhiteSpace(userAgent)) throw new ArgumentException("User agent has to be set.", "userAgent"); UserAgent = userAgent; if (baseUrl == null) baseUrl = "en.wikipedia.org"; if (!baseUrl.StartsWith("http")) baseUrl = "http://" + baseUrl; BaseUrl = new Uri(baseUrl); if (apiPath == null) apiPath = "/w/api.php"; ApiUrl = new Uri(BaseUrl, apiPath); Downloader = new Downloader(this); if (namespaces == null) Namespaces = new NamespaceInfo(this); else Namespaces = new NamespaceInfo(namespaces); }
public void Add(Downloader downloader) { lock (this) { queue.Enqueue(downloader); } }
public async Task ファイルをダウンロードできる() { var downloader = new Downloader(); await downloader.Download(DownloadUri, DownloadDestinationPath); Assert.IsTrue(File.Exists(DownloadDestinationPath)); Assert.IsTrue(new FileInfo(DownloadDestinationPath).Length > 100000); }
/// <summary> /// ctor /// </summary> /// <param name="downloader">download for view</param> public DownloadViewerVM(Downloader downloader) { try { if (downloader != null) this.download = downloader; this.StartDownloadCommand = new Command(this.StartDownload); this.PauseDownloadCommand = new Command(this.PauseDownload); this.ShowInFolderCommand = new Command(this.ShowInFolder); this.RemoveCommand = new Command(this.RemoveDownload); this.DownloadSettingsCommand = new Command(this.DownloadSettings); //// Attach EventHandler if (download != null) { this.download.StateChanged += Download_StateChanged; this.download.ThreadAdded += Download_ThreadAdded; this.download.SegmentChanged += Download_SegmentChanged; } //this.download.LocalFileInfoChanged += download_LocalFileInfoChanged; //this.download.RemoteFileInfoChanged += download_RemoteFileInfoChanged; } catch (NullReferenceException) { } }
private void SyncProperty() { _layoutRoot = FindName("LayoutRoot") as Canvas; _imageBorder = FindName("ImageBorder") as Rectangle; _mainImage = FindName("MainImage") as Image; _contentHolder = FindName("ContentHolder") as Canvas; _shadowCover = FindName("ShadowCover") as Rectangle; _fadeInStoryboard = FindName("FadeIn") as Storyboard; _fadeInShadowStory = FindName("FadeInShadow") as Storyboard; _fadeOutStoryboard = FindName("FadeOut") as Storyboard; _fadeOutStoryboard.Completed += new EventHandler(_fadeOutStoryboard_Completed); _fadeInShadowStory.Completed += new EventHandler(_fadeInShadowStory_Completed); _downloader = new Downloader(); _downloader.DownloadFailed += new ErrorEventHandler(_downloader_DownloadFailed); _downloader.Completed += new EventHandler(_downloader_Completed); _imageTimer = new HtmlTimer(); _imageTimer.Interval = 20; _imageTimer.Tick += new EventHandler(_imageTimer_Tick); _mainImage.MouseLeftButtonUp += new MouseEventHandler(_mainImage_MouseLeftButtonUp); _mainImage.Cursor = Cursors.Hand; // hide this instance. _imageBorder.Fill = null; _imageBorder.Stroke = null; // make event _mainImage.MouseEnter += new MouseEventHandler(_mainImage_MouseEnter); _mainImage.MouseLeave += new EventHandler(_mainImage_MouseLeave); }
public void DownloaderDownload() { bool finished = false; using (ManualResetEvent handle = new ManualResetEvent(false)) { using (Downloader downloader = new Downloader()) { downloader.Download( new Uri("http://www.gravatar.com/avatar/aeb98450c2ecffb91d20afc296f70238.png"), result => { Assert.IsNotNull(result); Assert.IsNull(result.Error); Assert.IsTrue(result.IsComplete); Assert.IsFalse(result.WasCached); Assert.IsNotNull(result.Content); finished = true; handle.Set(); }); handle.WaitOne(10000); Assert.IsTrue(finished); } } }
public TankstellenUsecaseController(Downloader downloader, HTMLParser htmlParser, string ort, EntryAuditor entryAuditor) { this.downloader = downloader; this.htmlParser = htmlParser; downloadUrl = Url + ort; this.entryAuditor = entryAuditor; }
public BaseDownloader(string url) { Downloader downloader = new Downloader(); downloader.Completed += new EventHandler(download_Completed); downloader.DownloadFailed += new System.Windows.ErrorEventHandler(this.downloader_DownloadFailed); downloader.Open("GET", new Uri(HtmlPage.DocumentUri, url)); downloader.Send(); }
public Form1() { InitializeComponent(); d = new Downloader(); d.DownloadStartEvent += new DownloadStartEventHandler(d_DownloadStartEvent); d.DownloadProgressEvent += new DownloadProgressEventHandler(d_DownloadProgressEvent); d.DownloadCompleteEvent += new DownloadCompleteEventHandler(d_DownloadCompleteEvent); d.Start(); }
static void Main() { var repository = WebPageRepository.GetInstance(); var downloader = new Downloader(); while (!repository.IsEmpty) { var url = repository.Remove(); downloader.Download(url, GenerateFileNameFromUrl(url)); } }
public void AddItem(string item, string name, IProgressBar progress) { if (Running) throw new Exception("Resource Downloader was already started."); string resourceUrl = UrlResourceName(category, item, name); Downloader downloader = new Downloader(); downloader.Open("GET", new Uri(resourceUrl, UriKind.RelativeOrAbsolute)); Descriptor descriptor = new Descriptor(this, downloader, progress); descriptors.Add(resourceUrl, descriptor); }
public bool TryLookup(double latitude, double longitude, out LocationInfo locationInfo) { var downloader = new Downloader { EnableCompression = true }; ReverseGeoCodeResult result = downloader.Download<ReverseGeoCodeResult>(BuildUrl(latitude, longitude)); if (result == null) { locationInfo = null; return false; } locationInfo = result.ToLocation(); return !string.IsNullOrWhiteSpace(locationInfo.Country) || !string.IsNullOrWhiteSpace(locationInfo.State) || !string.IsNullOrWhiteSpace(locationInfo.City); }
public SlideImage (Canvas canvas, String uri, Downloader downloader) { this.canvas = canvas; image.Height = canvas.Height; image.Width = canvas.Width; downloader.Completed += delegate { this.ready = true; if (ImageReady != null) ImageReady (this, null); }; image.Stretch = Stretch.Uniform; image.SetSource (downloader, uri); }
static void Main(string[] args) { var downloader = new Downloader(); var presentations = downloader.DownloadJson<Presentation[]>(new Uri("http://app.pechakuchaavl.org/api/app/presentations")); var presentationLoader = new PresentationLoader(presentations[0], 5); presentationLoader.NextSlide += (o, e) => { Console.WriteLine("Slide loaded with [{0}] bytes", e.ImageStream.Length); }; presentationLoader.Run(); Console.ReadLine(); }
/// <summary> /// Lookup the address at the given coordinates. /// </summary> /// <param name="coordinates">Coordinates to lookup.</param> /// <param name="address">Address of the coordinates given.</param> /// <returns>If lookup is successful.</returns> public bool TryResolveCivicAddress(GeoCoordinate coordinates, out CivicAddress address) { var downloader = new Downloader { EnableCompression = true }; GeocoderResponse result = downloader.Download<GeocoderResponse>(BuildUrl(coordinates.Latitude, coordinates.Longitude)); if (result == null) { address = null; return false; } address = result.ToCivicAddress(); return !string.IsNullOrWhiteSpace(address.CountryRegion) || !string.IsNullOrWhiteSpace(address.StateProvince) || !string.IsNullOrWhiteSpace(address.City); }
public MainWindow() : base(Gtk.WindowType.Toplevel) { Build (); webView = new WebView (); this.scrolledWebWindow.Add(webView); this.text_adress.Text = HOME_PAGE; webView.LoadFinished += new LoadFinishedHandler (OnLoadFinished); webView.Open (text_adress.Text); pathFolderSave = Environment.GetFolderPath (Environment.SpecialFolder.MyMusic); downloadList = new DownloadList (this.scrolledListDownlaods); downloader = new Downloader (downloadList); downloader.SavePath = pathFolderSave; }
/// <summary> /// Determine the address of the given coordinates. /// </summary> /// <param name="coordinates">Coordinates to lookup.</param> /// <param name="address">Address corresponding to the coordinates.</param> /// <returns>If lookup is successful.</returns> public bool TryResolveCivicAddress(GeoCoordinate coordinates, out CivicAddress address) { var downloader = new Downloader { EnableCompression = true }; downloader.Headers["Accept"] = "application/json"; // Google enables compressed output only, if a valid User-Agent is sent! downloader.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0"; MapsApiGeocodeResponse results = downloader.Download<MapsApiGeocodeResponse>(BuildUrl(coordinates.Latitude, coordinates.Longitude)); if (results == null || results.Results == null || results.Results.Count == 0) { address = null; return false; } address = results.Results[0].ToCivicAddress(); return true; }
public void DownloadImage (int idx) { Console.WriteLine ("Downloading "+idx); //Download images in a pipelines fashion //FIXME: use only one downloader instance once it supports been used multiple times. Downloader downloader = new Downloader (); if (idx + 1 < urls.Length) downloader.Completed += delegate { DownloadImage (idx + 1); }; SlideImage img = new SlideImage (this, urls [idx], downloader); images.Add (img); if (images.Count == 1) DisplayNextImage (); }
public static VhdDownloadContext Download(DownloaderParameters downloadParameters, ServiceManagementBaseCmdlet cmdlet) { Program.SyncOutput = new PSSyncOutputEvents(cmdlet); downloadParameters.ProgressDownloadComplete = Program.SyncOutput.ProgressDownloadComplete; downloadParameters.ProgressDownloadStatus = Program.SyncOutput.ProgressDownloadStatus; var downloader = new Downloader(downloadParameters); downloader.Download(); return new VhdDownloadContext { LocalFilePath = new FileInfo(downloadParameters.LocalFilePath), Source = downloadParameters.BlobUri.Uri }; }
public SortNavigator(Canvas pAssembly) { _assemblyCanvas = pAssembly; _speed = 0; // no animation by default. _moveTimer = _assemblyCanvas.FindName("ScrollTimer") as Storyboard; _thumHolder = _assemblyCanvas.FindName("ThumHolder") as Canvas; _holderClip = _assemblyCanvas.FindName("HolderClip") as Canvas; _btnLeft = _assemblyCanvas.FindName("BtnLeft") as Canvas; _btnRight = _assemblyCanvas.FindName("BtnRight") as Canvas; _topNaviLeft = _assemblyCanvas.FindName("TopNaviLeft") as Image; _topNaviMiddle = _assemblyCanvas.FindName("TopNaviMiddle") as Image; _topNaviRight = _assemblyCanvas.FindName("TopNaviRight") as Image; _btnLeftImage = _assemblyCanvas.FindName("BtnLeftImage") as Image; _btnRightImage = _assemblyCanvas.FindName("BtnRightImage") as Image; _dividorA = _assemblyCanvas.FindName("DividorA") as Image; _dividorB = _assemblyCanvas.FindName("DividorB") as Image; _indexDivider = _assemblyCanvas.FindName("IndexDivider") as TextBlock; _indexText1 = _assemblyCanvas.FindName("IndexText1") as TextBlock; _indexText2 = _assemblyCanvas.FindName("IndexText2") as TextBlock; _btnLeft.Cursor = Cursors.Hand; _btnRight.Cursor = Cursors.Hand; // Regist hover event _btnLeft.MouseEnter += new MouseEventHandler(_btnLeft_MouseEnter); _btnLeft.MouseLeave += new EventHandler(_btnLeft_MouseLeave); _btnRight.MouseEnter += new MouseEventHandler(_btnRight_MouseEnter); _btnRight.MouseLeave += new EventHandler(_btnRight_MouseLeave); // Regist click event _btnLeft.MouseLeftButtonDown += new MouseEventHandler(_btnLeft_MouseLeftButtonDown); _btnLeft.MouseLeftButtonUp += new MouseEventHandler(_btnLeft_MouseLeftButtonUp); _btnRight.MouseLeftButtonDown += new MouseEventHandler(_btnRight_MouseLeftButtonDown); _btnRight.MouseLeftButtonUp += new MouseEventHandler(_btnRight_MouseLeftButtonUp); // download font _fontDownloader = new Downloader(); _fontDownloader.DownloadFailed += new ErrorEventHandler(_fontDownloader_DownloadFailed); _fontDownloader.Completed += new EventHandler(_fontDownloader_Completed); Uri fontUri = new Uri("Assets/Font/FuturaStd-Heavy.otf", UriKind.RelativeOrAbsolute); _fontDownloader.Open("GET", fontUri); _fontDownloader.Send(); }
public bool TryLookup(double latitude, double longitude, out LocationInfo locationInfo) { var downloader = new Downloader { EnableCompression = true }; downloader.Headers["Accept"] = "application/json"; // Google enables compressed output only, if a valid User-Agent is sent! downloader.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0"; GoogleResults results = downloader.Download<GoogleResults>(BuildUrl(latitude, longitude)); if (results == null || results.Results == null || results.Results.Count == 0) { locationInfo = null; return false; } locationInfo = results.Results[0].ToLocation(); locationInfo.Latitude = latitude; locationInfo.Longitude = longitude; return true; }
private bool TryLookupInternal(IPAddress ip, out CivicAddress address, out GeoCoordinate coordinates) { var downloader = new Downloader { EnableCompression = true }; downloader.Headers["Accept"] = "application/json"; downloader.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0"; FreeGeoIPResponse result = downloader.Download<FreeGeoIPResponse>(BuildUrl(ip)); if (result == null) { address = null; coordinates = null; return false; } address = result.ToCivicAddress(); coordinates = result.ToGeoCoordinates(); return true; }
/// <summary> /// Creates a new SelectableImage /// </summary> public SelectableImage() { System.IO.Stream s = this.GetType().Assembly.GetManifestResourceStream( "Next2Friends.Swoosher.SelectableImage.xaml" ); root = this.InitializeFromXaml( new System.IO.StreamReader( s ).ReadToEnd() ); progress = (ProgressBar)root.FindName( "progress" ); content = (Canvas)root.FindName( "content" ); outline = (Rectangle)root.FindName( "outline" ); border = (Rectangle)root.FindName( "border" ); selection = (Rectangle)root.FindName( "selection" ); image = (Image)root.FindName( "image" ); //webImage = (Image)root.FindName( "webImage" ); root.Loaded += OnLoaded; downloader = new Downloader(); downloader.DownloadProgressChanged += image_DownloadProgressChanged; downloader.DownloadFailed += image_Failed; downloader.Completed += image_Completed; }
public async Task ダウンロードの進行状況を取得できる() { var downloader = new Downloader(); long? downloadedLength = null; long? totalLength = null; var progress = new Progress<DownloadProgress>((p) => { downloadedLength = p.DownloadedLength; totalLength = p.TotalLength; } ); await downloader.Download(DownloadUri, DownloadDestinationPath, progress); Assert.IsNotNull(downloadedLength); Assert.IsNotNull(totalLength); Assert.IsTrue(downloadedLength >= totalLength); }
public void DownloaderCancel() { using (ManualResetEvent handle = new ManualResetEvent(false)) { using (Downloader downloader = new Downloader()) { DownloadResult result = downloader.Download( new Uri("http://www.gravatar.com/avatar/aeb98450c2ecffb91d20afc296f70238.png"), r => { Assert.Fail(); handle.Set(); }); Assert.IsTrue(downloader.Cancel(result)); handle.WaitOne(1000); Assert.AreEqual(0, downloader.ProcessingCount); Assert.AreEqual(0, downloader.QueuedCount); } } }
public void ReceiveFile(string filePath) { var downloader = new Downloader(_connection); downloader.Download(filePath); }
private void DownloadFinished(Downloader downloader) { downloader.Job.OnDownloadingComplete(); }
public void OnDestroy() { _instance = null; }
private void LoadSubmission() { if (current == null) { return; } string user = (string)usernameList1.Tag; string uid = LocalDatabase.GetUserid(user); submissionStatus.ClearObjects(); long start, stop; string url = "", format; switch (_curSubType) { case SubViewType.LastSubmission: start = UnixTimestamp.ToUnixTime(dateTimePicker1.Value); stop = UnixTimestamp.ToUnixTime(DateTime.Now); format = "http://uhunt.felix-halim.net/api/p/subs/{0}/{1}/{2}"; //pid, unix time start, stop url = string.Format(format, current.pid, start, stop); Interactivity.SetStatus("Downloading last submissions on current problem..."); break; case SubViewType.Ranklist: start = 1; stop = (long)numericUpDown1.Value; format = "http://uhunt.felix-halim.net/api/p/rank/{0}/{1}/{2}"; //pid, rank start, rank count url = string.Format(format, current.pid, start, stop); Interactivity.SetStatus("Downloading ranks on current problem..."); break; case SubViewType.UsersRank: start = stop = 10; if (string.IsNullOrEmpty(uid) || uid == "-") { return; } format = "http://uhunt.felix-halim.net/api/p/ranklist/{0}/{1}/{2}/{3}"; //pid, uid, before_count, after_count url = string.Format(format, current.pid, uid, start, stop); Interactivity.SetStatus("Downloading " + user + "'s rank-data on current problem..."); break; case SubViewType.UsersSub: if (string.IsNullOrEmpty(uid) || uid == "-") { return; } format = "http://uhunt.felix-halim.net/api/subs-nums/{0}/{1}/{2}"; //uid, pnum, last sid url = string.Format(format, uid, current.pnum, 0); Interactivity.SetStatus("Downloading " + user + "'s submission on current problem..."); break; case SubViewType.Comapre: List <string> uidcol = new List <string>(); foreach (var val in LocalDatabase.usernames.Values) { uidcol.Add(val); } if (uidcol.Count == 0) { return; } format = "http://uhunt.felix-halim.net/api/subs-nums/{0}/{1}/0"; //uids(sep = comma), pnum url = string.Format(format, string.Join(",", uidcol.ToArray()), current.pnum); Interactivity.SetStatus("Comparing user's on current problem..."); break; } Downloader.DownloadStringAsync(url, user, Priority.Normal, dt_progressChanged, dt_taskCompleted); }
/// <summary> /// /// </summary> /// <param name="提示内容"></param> /// <param name="来源">真为手动,假为自动</param> public void 刷新播放(string 提示内容, bool 来源) { this.Dispatcher.Invoke(new Action(delegate { 提示框.Visibility = Visibility.Visible; 提示文字.Content = 提示内容; })); switch (DD.DownIofo.平台) { case "bilibili": { if (bilibili.根据房间号获取房间信息.是否正在直播(DD.DownIofo.房间_频道号, true)) { new Task((() => { ///需要DEBUG:CancelAsync过后,刷新播放没有显示出来 DD.DownIofo.WC.CancelAsync(); DD.DownIofo.备注 = "播放刷新"; DD.DownIofo.载状态 = false; DD.DownIofo.结束时间 = Convert.ToInt32((DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds); Downloader 载对象 = Downloader.新建下载对象(DD.DownIofo.平台, DD.DownIofo.房间_频道号, bilibili.根据房间号获取房间信息.获取标题(DD.DownIofo.房间_频道号), Guid.NewGuid().ToString(), bilibili.根据房间号获取房间信息.载地址(DD.DownIofo.房间_频道号), "播放缓冲重连", false, DD.DownIofo.主播名称, false, null); MMPU.文件删除委托(DD.DownIofo.文件保存路径, "刷新播放窗口,删除LiveCache过期的缓存文件"); DD = 载对象; for (int i = 0; i < MMPU.播放缓冲时长; i++) { Thread.Sleep(1000); if (载对象.DownIofo.已下载大小bit > 1000) { Thread.Sleep(MMPU.播放缓冲时长 * 1000); try { Play_Open(载对象.DownIofo.文件保存路径); //this.VlcControl.SourceProvider.MediaPlayer.Play(new Uri(下载对象.DownIofo.文件保存路径)); } catch (Exception) { return; } this.Dispatcher.Invoke(new Action(delegate { DD = 载对象; 提示框.Visibility = Visibility.Collapsed; })); return; } else { this.Dispatcher.Invoke(new Action(delegate { 提示文字.Content = "直播源推流停止或卡顿,正在尝试重连,第" + (i + 1) + "次失败/一共尝试" + MMPU.播放缓冲时长 + "次"; if (i >= MMPU.播放缓冲时长 - 1) { 提示文字.Content += "\n请尝试重开播放窗口"; return; } })); } } })).Start(); } else { InfoLog.InfoPrintf(DD.DownIofo.房间_频道号 + "房间:" + DD.DownIofo.主播名称 + " 下播放,录制完成", InfoLog.InfoClass.载必要提示); this.Dispatcher.Invoke(new Action(delegate { 提示文字.Content = "======该房间/频道 直播停止,请关闭播放窗口======"; return; })); } break; } default: System.Windows.MessageBox.Show("发现了与当前版本不支持的平台,请检查更新"); this.Dispatcher.Invoke(new Action(delegate { 提示框.Visibility = Visibility.Collapsed; })); return; } }
private static string GetResumeStr(Downloader d) { return(d.RemoteFileInfo != null && d.RemoteFileInfo.AcceptRanges ? "Yes" : "No"); }
public virtual void Run(params string[] arguments) { CheckIfRunning(); CheckIfSettingsCorrect(); Stat = Status.Running; _scheduler.IsExited = false; #if !NET_CORE // 开启多线程支持 ServicePointManager.DefaultConnectionLimit = 1000; #endif InitComponent(); if (StartTime == DateTime.MinValue) { StartTime = DateTime.Now; } Parallel.For(0, ThreadNum, new ParallelOptions { MaxDegreeOfParallelism = ThreadNum }, i => { int waitCount = 0; bool firstTask = false; var downloader = Downloader.Clone(); while (Stat == Status.Running) { Request request = Scheduler.Poll(); if (request == null) { if (waitCount > _waitCountLimit && ExitWhenComplete) { Stat = Status.Finished; break; } // wait until new url added WaitNewUrl(ref waitCount); } else { waitCount = 0; try { Stopwatch sw = new Stopwatch(); ProcessRequest(sw, request, downloader); Thread.Sleep(_random.Next(Site.MinSleepTime, Site.MaxSleepTime)); _OnSuccess(request); } catch (Exception e) { OnError(request); this.Log($"采集失败: {request.Url}.", LogLevel.Error, e); } finally { if (request.GetExtra(Request.Proxy) != null) { var statusCode = request.GetExtra(Request.StatusCode); Site.ReturnHttpProxy(request.GetExtra(Request.Proxy) as UseSpecifiedUriWebProxy, statusCode == null ? HttpStatusCode.Found : (HttpStatusCode)statusCode); } } if (!firstTask) { Thread.Sleep(3000); firstTask = true; } } } }); FinishedTime = DateTime.Now; foreach (IPipeline pipeline in Pipelines) { SafeDestroy(pipeline); } SpiderClosing?.Invoke(); if (!_scheduler.IsExited) { _scheduler.IsExited = true; } this.Log($"等待监控进程退出.", LogLevel.Info); _monitorTask.Wait(); Scheduler.Dispose(); if (Stat == Status.Finished) { OnClose(); this.Log($"结束采集, 运行时间: {(FinishedTime - StartTime).TotalSeconds} 秒.", LogLevel.Info); } if (Stat == Status.Stopped) { this.Log($"暂停采集, 运行时间: {(FinishedTime - StartTime).TotalSeconds} 秒.", LogLevel.Info); } if (Stat == Status.Exited) { this.Log($"退出采集, 运行时间: {(FinishedTime - StartTime).TotalSeconds} 秒.", LogLevel.Info); } }
public abstract void Previous(Downloader downloader);
public void Init(Downloader downloader) { queryMirrorCount = 0; this.downloader = downloader; }
private IEnumerator TryToDownload() { yield return(Downloader.DownloadBundle(DownloadResourseManager.Url.Voices, OnDownload)); }
public static async Task Matestein(string[] args) { var options = new LaunchOptions { Headless = false }; Console.WriteLine("Downloading chromium"); await Downloader.CreateDefault().DownloadRevisionAsync(Downloader.DefaultRevision); Console.WriteLine("Navigating google"); using (var browser = await Puppeteer.LaunchAsync(options, Downloader.DefaultRevision)) using (var page = await browser.NewPageAsync()) { try { Directory.SetCurrentDirectory(@"C:\Sistemas"); page.DefaultNavigationTimeout = 80000; await page.GoToAsync("http://sistemasenem.inep.gov.br/EnemSolicitacao/login.seam"); await page.SetViewportAsync(new ViewPortOptions { Width = 1920, Height = 920 }); //await page.Frames.FirstOrDefault().SelectAsync("#username", "111111"); await page.TypeAsync("#username", "191010104484-98414745"); await page.TypeAsync("#password", "UniSL201655944458445547"); await page.ClickAsync("input[type='image']"); var menu = await page.WaitForSelectorAsync("#LeftMenu #menugroup_4_3 #row_menugroup_4_3"); await menu.ClickAsync(); await page.ClickAsync("#j_id50"); Thread.Sleep(2000); var inputCPF = await page.WaitForSelectorAsync("#formularioForm"); await page.TypeAsync("#formularioForm input[type='text']", "35168598811"); await page.ClickAsync("#formularioForm input[type='image']"); await page.WaitForSelectorAsync("#resultadoForm input[type='image']"); Thread.Sleep(2000); await page.ClickAsync("#j_id57"); await page.WaitForSelectorAsync("#listaSolicitacaoAtendidas"); Thread.Sleep(2000); await page.QuerySelectorAsync("#listaSolicitacaoAtendidas tbody tr td:nth-last-child(1) a"); var href = await page.EvaluateExpressionAsync("document.querySelector('#listaSolicitacaoAtendidas tbody tr td:nth-last-child(1) a').href"); //await page.ClickAsync("#listaSolicitacaoAtendidas tbody tr td:nth-last-child(1) a"); //await page.GoToAsync(href); using (WebClient webClient = new WebClient()) { webClient.DownloadFile(page.GoToAsync(href), @"c:\Sistemas\myfile.txt"); } //await page.ClickAsync("#resultadoForm input[type='image']"); Console.WriteLine("Terminou!"); await browser.CloseAsync(); Console.ReadKey(); } catch (Exception ex) { Console.Write("O erro foi: " + ex); Console.ReadKey(); } } }
/// <summary> /// Saves the movie. /// </summary> /// <param name="movieModel"> /// The movie model. /// </param> public void SaveMovie(MovieModel movieModel) { string actualTrailerFileName = string.Empty; string actualTrailerFileNameExt = string.Empty; string actualFilePath = movieModel.AssociatedFiles.Media[0].FolderPath + "\\"; string actualFileName = movieModel.AssociatedFiles.Media[0].FilenameWithOutExt; string currentTrailerUrl = movieModel.CurrentTrailerUrl; MovieSaveSettings movieSaveSettings = Get.InOutCollection.CurrentMovieSaveSettings; string nfoPath = string.IsNullOrEmpty(movieSaveSettings.NfoPath) ? actualFilePath : movieSaveSettings.NfoPath; var posterPathFrom = string.Empty; posterPathFrom = string.IsNullOrEmpty(movieModel.PosterPathOnDisk) ? Downloader.ProcessDownload( movieModel.CurrentPosterImageUrl, DownloadType.Binary, Section.Movies) : movieModel.PosterPathOnDisk; string fanartPathFrom = string.Empty; fanartPathFrom = string.IsNullOrEmpty(movieModel.FanartPathOnDisk) ? Downloader.ProcessDownload( movieModel.CurrentFanartImageUrl, DownloadType.Binary, Section.Movies) : movieModel.FanartPathOnDisk; string trailerPathFrom = Downloader.ProcessDownload( movieModel.CurrentTrailerUrl, DownloadType.AppleBinary, Section.Movies); string nfoXml = GenerateOutput.GenerateMovieOutput(movieModel); string nfoTemplate; string posterTemplate; string fanartTemplate; string trailerTemplate; string setPosterTemplate; string setFanartTemplate; if (MovieNaming.IsDVD(movieModel.GetBaseFilePath)) { actualFilePath = MovieNaming.GetDvdPath(movieModel.GetBaseFilePath); actualFileName = MovieNaming.GetDvdName(movieModel.GetBaseFilePath); nfoTemplate = movieSaveSettings.DvdNfoNameTemplate; posterTemplate = movieSaveSettings.DvdPosterNameTemplate; fanartTemplate = movieSaveSettings.DvdFanartNameTemplate; trailerTemplate = movieSaveSettings.DvdTrailerNameTemplate; setPosterTemplate = movieSaveSettings.DvdSetPosterNameTemplate; setFanartTemplate = movieSaveSettings.DvdSetFanartNameTemplate; } else if (MovieNaming.IsBluRay(movieModel.GetBaseFilePath)) { actualFilePath = MovieNaming.GetBluRayPath(movieModel.GetBaseFilePath); actualFileName = MovieNaming.GetBluRayName(movieModel.GetBaseFilePath); nfoTemplate = movieSaveSettings.BlurayNfoNameTemplate; posterTemplate = movieSaveSettings.BlurayPosterNameTemplate; fanartTemplate = movieSaveSettings.BlurayFanartNameTemplate; trailerTemplate = movieSaveSettings.BlurayTrailerNameTemplate; setPosterTemplate = movieSaveSettings.BluraySetPosterNameTemplate; setFanartTemplate = movieSaveSettings.BluraySetFanartNameTemplate; } else { nfoTemplate = movieSaveSettings.NormalNfoNameTemplate; posterTemplate = movieSaveSettings.NormalPosterNameTemplate; fanartTemplate = movieSaveSettings.NormalFanartNameTemplate; trailerTemplate = movieSaveSettings.NormalTrailerNameTemplate; setPosterTemplate = movieSaveSettings.NormalSetPosterNameTemplate; setFanartTemplate = movieSaveSettings.NormalSetFanartNameTemplate; } if (!string.IsNullOrEmpty(currentTrailerUrl)) { actualTrailerFileName = currentTrailerUrl.Substring( currentTrailerUrl.LastIndexOf('/') + 1, currentTrailerUrl.LastIndexOf('.') - currentTrailerUrl.LastIndexOf('/') - 1); actualTrailerFileNameExt = currentTrailerUrl.Substring(currentTrailerUrl.LastIndexOf('.') + 1); } string nfoOutputName = nfoTemplate.Replace("<path>", actualFilePath).Replace("<filename>", actualFileName); string posterOutputName = posterTemplate.Replace("<path>", actualFilePath).Replace("<filename>", actualFileName).Replace( "<ext>", "jpg"); string fanartOutputName = fanartTemplate.Replace("<path>", actualFilePath).Replace("<filename>", actualFileName).Replace( "<ext>", "jpg"); string trailerOutputName = trailerTemplate.Replace("<path>", actualFilePath).Replace("<filename>", actualFileName).Replace( "<trailername>", actualTrailerFileName).Replace("<ext>", actualTrailerFileNameExt); string setPosterOutputPath = setPosterTemplate.Replace("<path>", actualFilePath).Replace( "<filename>", actualFileName); string setFanartOutputPath = setFanartTemplate.Replace("<path>", actualFilePath).Replace( "<filename>", actualFileName); // Handle Set Images List <string> sets = MovieSetManager.GetSetsContainingMovie(movieModel); if (sets.Count > 0) { foreach (string setName in sets) { MovieSetModel set = MovieSetManager.GetSet(setName); MovieSetObjectModel setObjectModel = (from s in set.Movies where s.MovieUniqueId == movieModel.MovieUniqueId select s). SingleOrDefault(); string currentSetPosterPath = setPosterOutputPath.Replace("<setname>", FileSystemCharChange.To(setName, FileSystemCharChange.ConvertArea.Movie)).Replace( "<ext>", "jpg"); string currentSetFanartPath = setFanartOutputPath.Replace("<setname>", FileSystemCharChange.To(setName, FileSystemCharChange.ConvertArea.Movie)).Replace( "<ext>", "jpg"); if (setObjectModel.Order == 1) { if (File.Exists(set.PosterUrl)) { File.Copy(set.PosterUrl, currentSetPosterPath, true); } if (File.Exists(set.FanartUrl)) { File.Copy(set.FanartUrl, currentSetFanartPath, true); } } else { if (File.Exists(set.PosterUrl) && File.Exists(currentSetPosterPath)) { File.Delete(currentSetPosterPath); } if (File.Exists(set.FanartUrl) && File.Exists(currentSetFanartPath)) { File.Delete(currentSetFanartPath); } } } } if (movieSaveSettings.IoType == MovieIOType.All || movieSaveSettings.IoType == MovieIOType.Nfo) { try { this.WriteNFO(nfoXml, nfoOutputName); movieModel.ChangedText = false; Log.WriteToLog( LogSeverity.Info, 0, "NFO Saved To Disk for " + movieModel.Title, nfoPath + nfoOutputName); } catch (Exception ex) { Log.WriteToLog(LogSeverity.Error, 0, "Saving NFO Failed for " + movieModel.Title, ex.Message); } } if (movieSaveSettings.IoType == MovieIOType.All || movieSaveSettings.IoType == MovieIOType.Poster || movieSaveSettings.IoType == MovieIOType.Images) { try { if (!string.IsNullOrEmpty(posterPathFrom)) { this.CopyFile(posterPathFrom, posterOutputName); movieModel.ChangedPoster = false; Log.WriteToLog( LogSeverity.Info, 0, "Poster Saved To Disk for " + movieModel.Title, posterPathFrom + " -> " + posterOutputName); } } catch (Exception ex) { Log.WriteToLog(LogSeverity.Error, 0, "Saving Poster Failed for " + movieModel.Title, ex.Message); } } if (movieSaveSettings.IoType == MovieIOType.All || movieSaveSettings.IoType == MovieIOType.Fanart || movieSaveSettings.IoType == MovieIOType.Images) { try { if (!string.IsNullOrEmpty(fanartPathFrom)) { this.CopyFile(fanartPathFrom, fanartOutputName); movieModel.ChangedFanart = false; Log.WriteToLog( LogSeverity.Info, 0, "Fanart Saved To Disk for " + movieModel.Title, fanartPathFrom + " -> " + fanartOutputName); } } catch (Exception ex) { Log.WriteToLog(LogSeverity.Error, 0, "Saving Fanart Failed for " + movieModel.Title, ex.Message); } } if (movieSaveSettings.IoType == MovieIOType.All || movieSaveSettings.IoType == MovieIOType.Trailer) { try { if (!string.IsNullOrEmpty(movieModel.CurrentTrailerUrl)) { this.CopyFile(trailerPathFrom, trailerOutputName); movieModel.ChangedTrailer = false; Log.WriteToLog( LogSeverity.Info, 0, "Trailer Saved To Disk for " + movieModel.Title, trailerPathFrom + " -> " + trailerOutputName); } } catch (Exception ex) { Log.WriteToLog(LogSeverity.Error, 0, "Saving Trailer Failed for " + movieModel.Title, ex.Message); } } }
/// <summary> /// Loads the model. /// </summary> /// <exception cref="Exception">Invalid model selected!</exception> public void LoadModel() { try { string modelFile = ""; string baseFolder = string.Format("{0}\\SiaNet\\models", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)); switch (model) { case ImageNetModel.AlexNet: Downloader.DownloadModel(PreTrainedModelPath.ImageNetPath.AlexNet); modelFile = baseFolder + "\\" + Path.GetFileName(PreTrainedModelPath.ImageNetPath.AlexNet); break; case ImageNetModel.InceptionV3: Downloader.DownloadModel(PreTrainedModelPath.ImageNetPath.InceptionV3); modelFile = baseFolder + "\\" + Path.GetFileName(PreTrainedModelPath.ImageNetPath.InceptionV3); break; case ImageNetModel.ResNet18: Downloader.DownloadModel(PreTrainedModelPath.ImageNetPath.ResNet18); modelFile = baseFolder + "\\" + Path.GetFileName(PreTrainedModelPath.ImageNetPath.ResNet18); break; case ImageNetModel.ResNet34: Downloader.DownloadModel(PreTrainedModelPath.ImageNetPath.ResNet34); modelFile = baseFolder + "\\" + Path.GetFileName(PreTrainedModelPath.ImageNetPath.ResNet34); break; case ImageNetModel.ResNet50: Downloader.DownloadModel(PreTrainedModelPath.ImageNetPath.ResNet50); modelFile = baseFolder + "\\" + Path.GetFileName(PreTrainedModelPath.ImageNetPath.ResNet50); break; case ImageNetModel.ResNet101: Downloader.DownloadModel(PreTrainedModelPath.ImageNetPath.ResNet101); modelFile = baseFolder + "\\" + Path.GetFileName(PreTrainedModelPath.ImageNetPath.ResNet101); break; case ImageNetModel.ResNet152: Downloader.DownloadModel(PreTrainedModelPath.ImageNetPath.ResNet152); modelFile = baseFolder + "\\" + Path.GetFileName(PreTrainedModelPath.ImageNetPath.ResNet152); break; case ImageNetModel.VGG16: Downloader.DownloadModel(PreTrainedModelPath.ImageNetPath.VGG16); modelFile = baseFolder + "\\" + Path.GetFileName(PreTrainedModelPath.ImageNetPath.VGG16); break; case ImageNetModel.VGG19: Downloader.DownloadModel(PreTrainedModelPath.ImageNetPath.VGG19); modelFile = baseFolder + "\\" + Path.GetFileName(PreTrainedModelPath.ImageNetPath.VGG19); break; default: throw new Exception("Invalid model selected!"); } modelFunc = Function.Load(modelFile, GlobalParameters.Device); Logging.WriteTrace("Model loaded."); } catch (Exception ex) { Logging.WriteTrace(ex); throw ex; } }
public abstract void Next(Downloader downloader);
/// <inheritdoc /> public override void Build(BuildOptions options) { var root = options.IntermediateFolder; var packagePath = Path.Combine(root, "package.zip"); var filesToKeep = new[] { "freetype.Build.cs", }; // Get the source Downloader.DownloadFileFromUrlToPath("https://sourceforge.net/projects/freetype/files/freetype2/2.10.0/ft2100.zip/download", packagePath); using (ZipArchive archive = ZipFile.Open(packagePath, ZipArchiveMode.Read)) { archive.ExtractToDirectory(root); root = Path.Combine(root, archive.Entries.First().FullName); } var configurationMsvc = "Release Static"; var binariesToCopyMsvc = new[] { "freetype.lib", "freetype.pdb", }; var vsSolutionPath = Path.Combine(root, "builds", "windows", "vc2010", "freetype.sln"); var vcxprojPath = Path.Combine(root, "builds", "windows", "vc2010", "freetype.vcxproj"); var vcxprojContents = File.ReadAllText(vcxprojPath); var libraryFileName = "libfreetype.a"; vcxprojContents = vcxprojContents.Replace("<RuntimeLibrary>MultiThreaded</RuntimeLibrary>", "<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>"); vcxprojContents = vcxprojContents.Replace("<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>", "<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>"); foreach (var platform in options.Platforms) { switch (platform) { case TargetPlatform.Windows: { // Fix the MSVC project settings for Windows PatchWindowsTargetPlatformVersion(vcxprojPath, vcxprojContents, "8.1", "140"); // Build for Win64 Deploy.VCEnvironment.BuildSolution(vsSolutionPath, configurationMsvc, "x64"); var depsFolder = GetThirdPartyFolder(options, platform, TargetArchitecture.x64); foreach (var filename in binariesToCopyMsvc) { Utilities.FileCopy(Path.Combine(root, "objs", "x64", configurationMsvc, filename), Path.Combine(depsFolder, filename)); } break; } case TargetPlatform.UWP: { // Fix the MSVC project settings for UWP PatchWindowsTargetPlatformVersion(vcxprojPath, vcxprojContents, "10.0.17763.0", "v141"); // Build for UWP x64 Deploy.VCEnvironment.BuildSolution(vsSolutionPath, configurationMsvc, "x64"); var depsFolder = GetThirdPartyFolder(options, platform, TargetArchitecture.x64); foreach (var filename in binariesToCopyMsvc) { Utilities.FileCopy(Path.Combine(root, "objs", "x64", configurationMsvc, filename), Path.Combine(depsFolder, filename)); } break; } case TargetPlatform.Linux: { var envVars = new Dictionary <string, string> { { "CC", "clang-7" }, { "CC_FOR_BUILD", "clang-7" } }; var buildDir = Path.Combine(root, "build"); // Fix scripts Utilities.Run("sed", "-i -e \'s/\r$//\' autogen.sh", null, root, Utilities.RunOptions.None, envVars); Utilities.Run("sed", "-i -e \'s/\r$//\' configure", null, root, Utilities.RunOptions.None, envVars); Utilities.Run("chmod", "+x autogen.sh", null, root, Utilities.RunOptions.None); Utilities.Run("chmod", "+x configure", null, root, Utilities.RunOptions.None); Utilities.Run(Path.Combine(root, "autogen.sh"), null, null, root, Utilities.RunOptions.Default, envVars); // Disable using libpng even if it's found on the system var cmakeFile = Path.Combine(root, "CMakeLists.txt"); File.WriteAllText(cmakeFile, File.ReadAllText(cmakeFile) .Replace("find_package(PNG)", "") .Replace("find_package(ZLIB)", "") .Replace("find_package(BZip2)", "") ); // Build for Linux SetupDirectory(buildDir, true); var toolchain = UnixToolchain.GetToolchainName(platform, TargetArchitecture.x64); Utilities.Run("cmake", string.Format("-G \"Unix Makefiles\" -DCMAKE_POSITION_INDEPENDENT_CODE=ON -DFT_WITH_BZIP2=OFF -DFT_WITH_ZLIB=OFF -DFT_WITH_PNG=OFF -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER_TARGET={0} ..", toolchain), null, buildDir, Utilities.RunOptions.None, envVars); Utilities.Run("cmake", "--build .", null, buildDir, Utilities.RunOptions.None, envVars); var depsFolder = GetThirdPartyFolder(options, platform, TargetArchitecture.x64); Utilities.FileCopy(Path.Combine(buildDir, libraryFileName), Path.Combine(depsFolder, libraryFileName)); break; } case TargetPlatform.PS4: { // Get the build data files Utilities.DirectoryCopy( Path.Combine(GetBinariesFolder(options, platform), "Data", "freetype"), Path.Combine(root, "builds", "PS4"), false, true); // Build for PS4 var solutionPath = Path.Combine(root, "builds", "PS4", "freetype.sln"); Deploy.VCEnvironment.BuildSolution(solutionPath, "Release", "ORBIS"); var depsFolder = GetThirdPartyFolder(options, platform, TargetArchitecture.x64); Utilities.FileCopy(Path.Combine(root, "lib", "PS4", libraryFileName), Path.Combine(depsFolder, libraryFileName)); break; } case TargetPlatform.PS5: { // Get the build data files Utilities.DirectoryCopy( Path.Combine(GetBinariesFolder(options, platform), "Data", "freetype"), Path.Combine(root, "builds", "PS5"), false, true); Utilities.ReplaceInFile(Path.Combine(root, "include\\freetype\\config\\ftstdlib.h"), "#define ft_getenv getenv", "char* ft_getenv(const char* n);"); // Build for PS5 var solutionPath = Path.Combine(root, "builds", "PS5", "freetype.sln"); Deploy.VCEnvironment.BuildSolution(solutionPath, "Release", "PROSPERO"); var depsFolder = GetThirdPartyFolder(options, platform, TargetArchitecture.x64); Utilities.FileCopy(Path.Combine(root, "lib", "PS5", libraryFileName), Path.Combine(depsFolder, libraryFileName)); break; } case TargetPlatform.XboxOne: { // Fix the MSVC project settings for Xbox One PatchWindowsTargetPlatformVersion(vcxprojPath, vcxprojContents, "10.0.19041.0", "v142"); // Build for Xbox One x64 Deploy.VCEnvironment.BuildSolution(vsSolutionPath, configurationMsvc, "x64"); var depsFolder = GetThirdPartyFolder(options, platform, TargetArchitecture.x64); foreach (var filename in binariesToCopyMsvc) { Utilities.FileCopy(Path.Combine(root, "objs", "x64", configurationMsvc, filename), Path.Combine(depsFolder, filename)); } break; } case TargetPlatform.XboxScarlett: { // Fix the MSVC project settings for Xbox Scarlett PatchWindowsTargetPlatformVersion(vcxprojPath, vcxprojContents, "10.0.19041.0", "v142"); // Build for Xbox Scarlett Deploy.VCEnvironment.BuildSolution(vsSolutionPath, configurationMsvc, "x64"); var depsFolder = GetThirdPartyFolder(options, platform, TargetArchitecture.x64); foreach (var filename in binariesToCopyMsvc) { Utilities.FileCopy(Path.Combine(root, "objs", "x64", configurationMsvc, filename), Path.Combine(depsFolder, filename)); } break; } case TargetPlatform.Android: { var buildDir = Path.Combine(root, "build"); // Disable using libpng even if it's found on the system var cmakeFile = Path.Combine(root, "CMakeLists.txt"); File.WriteAllText(cmakeFile, File.ReadAllText(cmakeFile) .Replace("find_package(PNG)", "") .Replace("find_package(ZLIB)", "") .Replace("find_package(BZip2)", "") ); // Build for Android SetupDirectory(buildDir, true); RunCmake(buildDir, TargetPlatform.Android, TargetArchitecture.ARM64, ".. -DFT_WITH_BZIP2=OFF -DFT_WITH_ZLIB=OFF -DFT_WITH_PNG=OFF -DCMAKE_BUILD_TYPE=Release"); Utilities.Run("cmake", "--build .", null, buildDir, Utilities.RunOptions.None); var depsFolder = GetThirdPartyFolder(options, platform, TargetArchitecture.ARM64); Utilities.FileCopy(Path.Combine(buildDir, libraryFileName), Path.Combine(depsFolder, libraryFileName)); break; } case TargetPlatform.Switch: { // Build for Switch var buildDir = Path.Combine(root, "build"); SetupDirectory(buildDir, true); RunCmake(buildDir, platform, TargetArchitecture.ARM64, ".. -DCMAKE_BUILD_TYPE=Release"); Utilities.Run("cmake", "--build .", null, buildDir, Utilities.RunOptions.None); var depsFolder = GetThirdPartyFolder(options, platform, TargetArchitecture.ARM64); Utilities.FileCopy(Path.Combine(buildDir, libraryFileName), Path.Combine(depsFolder, libraryFileName)); break; } } } // Backup files var srcIncludePath = Path.Combine(root, "include", "freetype"); var dstIncludePath = Path.Combine(options.ThirdPartyFolder, "freetype"); foreach (var filename in filesToKeep) { var src = Path.Combine(dstIncludePath, filename); var dst = Path.Combine(options.IntermediateFolder, filename + ".tmp"); Utilities.FileCopy(src, dst); } // Setup headers directory SetupDirectory(dstIncludePath, true); // Deploy header files and restore files Utilities.DirectoryCopy(srcIncludePath, dstIncludePath, true, true); Utilities.FileCopy(Path.Combine(root, "include", "ft2build.h"), Path.Combine(dstIncludePath, "ft2build.h")); Utilities.FileCopy(Path.Combine(root, "docs", "LICENSE.TXT"), Path.Combine(dstIncludePath, "LICENSE.TXT")); foreach (var filename in filesToKeep) { var src = Path.Combine(options.IntermediateFolder, filename + ".tmp"); var dst = Path.Combine(dstIncludePath, filename); Utilities.FileCopy(src, dst); } }
public virtual void Run(params string[] arguments) { if (Stat == Status.Running) { this.Log("任务运行中...", LogLevel.Warn); return; } CheckIfSettingsCorrect(); #if !NET_CORE // 开启多线程支持 ServicePointManager.DefaultConnectionLimit = 1000; #endif InitComponent(arguments); Monitorable.IsExited = false; if (arguments.Contains("running-test")) { _scheduler.IsExited = true; return; } if (StartTime == DateTime.MinValue) { StartTime = DateTime.Now; } Stat = Status.Running; _realStat = Status.Running; while (Stat == Status.Running || Stat == Status.Stopped) { if (Stat == Status.Stopped) { _realStat = Status.Stopped; Thread.Sleep(50); continue; } Parallel.For(0, ThreadNum, new ParallelOptions { MaxDegreeOfParallelism = ThreadNum }, i => { int waitCount = 0; bool firstTask = false; var downloader = Downloader.Clone(); while (Stat == Status.Running) { Request request = Scheduler.Poll(); if (request == null) { if (waitCount > _waitCountLimit && ExitWhenComplete) { Stat = Status.Finished; _realStat = Status.Finished; _OnComplete(); OnComplete?.Invoke(); break; } // wait until new url added WaitNewUrl(ref waitCount); } else { waitCount = 0; try { Stopwatch sw = new Stopwatch(); ProcessRequest(sw, request, downloader); Thread.Sleep(Site.SleepTime); _OnSuccess(request); } catch (Exception e) { OnError(request); this.Log($"采集失败: {request.Url}.", LogLevel.Error, e); } finally { if (request.GetExtra(Request.Proxy) != null) { var statusCode = request.GetExtra(Request.StatusCode); Site.ReturnHttpProxy(request.GetExtra(Request.Proxy) as UseSpecifiedUriWebProxy, statusCode == null ? HttpStatusCode.Found : (HttpStatusCode)statusCode); } } if (!firstTask) { Thread.Sleep(3000); firstTask = true; } } } }); } FinishedTime = DateTime.Now; _realStat = Status.Exited; OnClose(); this.Log($"等待监控进程退出.", LogLevel.Info); _monitorTask.Wait(); OnClosing?.Invoke(); var msg = Stat == Status.Finished ? "结束采集" : "退出采集"; this.Log($"{msg}, 运行时间: {(FinishedTime - StartTime).TotalSeconds} 秒.", LogLevel.Info); }
async void LoadImg() { await Kit.LoadImage(Kit.DefaultUserPhoto, _imgFsm); _imgFsmNoCache.Source = await Downloader.GetImage("photo/profilephoto.jpg"); }
/// <summary> /// 建立新的播放窗口实例 /// </summary> /// <param name="DL">播放对象实例</param> /// <param name="默认音量">新建实例的默认音量</param> /// <param name="弹幕颜色">新建实例的默认弹幕颜色</param> /// <param name="字幕颜色">新建实例的默认字幕颜色</param> /// <param name="弹幕大小">新建实例的默认弹幕字体大小</param> /// <param name="字幕大小">新建实例的默认字幕字体大小</param> /// <param name="宽度">新建实例的默认窗口宽度</param> /// <param name="高度">新建实例的默认窗口高度</param> public MainWindow(Downloader DL, int 默认音量, SolidColorBrush 弹幕颜色, SolidColorBrush 字幕颜色, int 弹幕大小, int 字幕大小, int 宽度, int 高度) { InitializeComponent(); Core.Initialize(); _libVLC = new LibVLC(); _mediaPlayer = new MediaPlayer(_libVLC); VLCV.Loaded += (sender, e) => VLCV.MediaPlayer = _mediaPlayer; this.Width = 宽度; this.Height = 高度; this.Title = DL.DownIofo.标题; 窗口信息 = new SetWindow.窗口信息() { GUID = Guid.NewGuid().ToString(), X坐标 = this.Left, Y坐标 = this.Top, 宽度 = this.Width, 高度 = this.Height, 标题 = this.Title }; 窗口是否打开 = true; 音量.Value = 默认音量; this.Closed += 关闭窗口事件; DD = DL; 弹幕框.Opacity = 0.5; 字幕.Foreground = 字幕颜色; 弹幕.Foreground = 弹幕颜色; // 字幕.FontSize = 字幕大小; 字幕.字体大小 = 字幕大小; 字幕.是否居中 = true; //弹幕.FontSize = 弹幕大小; 弹幕.字体大小 = 弹幕大小; DD.DownIofo.文件保存路径 = "./tmp/LiveCache/" + DL.DownIofo.标题 + DL.DownIofo.事件GUID + "_" + 刷新次数 + ".flv"; DD.DownIofo.继承 = new Downloader.继承(); 设置框.Visibility = Visibility.Collapsed; 关闭框.Visibility = Visibility.Collapsed; if (MMPU.第一次打开播放窗口) { 设置框.Visibility = Visibility.Visible; 关闭框.Visibility = Visibility.Visible; MMPU.第一次打开播放窗口 = false; } if (MMPU.系统内核版本 != 10) { 弹幕使能 = false; 弹幕开关.IsChecked = false; 弹幕开关.Visibility = Visibility.Collapsed; 字幕使能 = false; 字幕开关.IsChecked = false; 字幕开关.Visibility = Visibility.Collapsed; 修改字幕颜色按钮.Visibility = Visibility.Collapsed; 修改弹幕颜色按钮.Visibility = Visibility.Collapsed; 弹幕输入窗口.Visibility = Visibility.Collapsed; 弹幕发送提示.Visibility = Visibility.Collapsed; 弹幕高CPU使用率警告.Visibility = Visibility.Collapsed; 发送弹幕按钮.Visibility = Visibility.Collapsed; 弹幕透明度.Visibility = Visibility.Collapsed; 字幕位置.Visibility = Visibility.Collapsed; 非win10提示.Visibility = Visibility.Visible; } else { 非win10提示.Visibility = Visibility.Collapsed; } }
public void StartTimers() { Timer t = new Timer(1000 * 60 * Constants.UpdateInterval); t.Elapsed += new ElapsedEventHandler(t_Elapsed); t.Enabled = true; if (!System.IO.File.Exists(TrackedManifestFile)) { using (JsonTextWriter wr = new JsonTextWriter(new System.IO.StreamWriter(TrackedManifestFile))) { JsonSerializer ser = new JsonSerializer(); wr.Formatting = Formatting.Indented; ser.Serialize(wr, ManifestTrackList); } } using (JsonTextReader r = new JsonTextReader(new System.IO.StreamReader(TrackedManifestFile))) { JsonSerializer ser = new JsonSerializer(); ManifestTrackList = ser.Deserialize <List <TrackData> >(r); } EventTypes["NotifyPublic"] = (data) => { string message = "SOE Patched " + data.Name + " on " + data.LastUpdated.ToString(); SendMessage("#ps-universe", message); SendMessage("#REside", message); SystemMessage(message); }; EventTypes["NotifyPrivate"] = (data) => { string message = " Tracked Manifest " + data.Name + " was modified on " + data.LastUpdated.ToString(); SendMessage("#reside_priv", message); }; EventTypes["DumpManifestToFile"] = (data) => { string[] filename = DumpManifestToFile(data.Manifest, "Manifests/Tracked/" + data.Name + "/", string.Format("{0}{1}.txt", data.Manifest.Substring(data.Manifest.LastIndexOf("/") + 1), DateTime.Now.ToString("yyyy-MM-dd"))); foreach (string s in filename) { this.SendMessage("#reside_priv", string.Format("http://testoutfit.info/lebot/{0}", s)); } }; EventTypes["DateManifest"] = (data) => { using (System.IO.StreamWriter wr = new System.IO.StreamWriter(System.IO.File.Open("output/Manifests/Tracked/" + data.Name + "UpdateDates.txt", System.IO.FileMode.Append))) { wr.WriteLine(data.LastUpdated.ToString()); this.SendMessage("#reside_priv", string.Format("Updated http://testoutfit.info/lebot/Manifests/Tracked/{0}", data.Name + "UpdateDates.txt")); } }; EventTypes["SeeTheFuture"] = (data) => { string message = ""; if (data.Name == "livenext") { message = "I predict a Live patch is going to happen in the near future"; } if (data.Name == "testnext") { message = "I predict a Test patch is going to happen in the near future"; } SendMessage("#ps-universe", message); SendMessage("#REside", message); }; EventTypes["QueueLiveDownload"] = (data) => { DateTime now = DateTime.Now; SendMessage("#reside_priv", "Live has started downloading"); string[] manifests = new string[] { "http://manifest.patch.station.sony.com/patch/sha/manifest/planetside2/planetside2-live/live/planetside2-live.sha.soe", "http://manifest.patch.station.sony.com/patch/sha/manifest/planetside2/planetside2-livecommon/live/planetside2-livecommon.sha.soe", }; foreach (string manifest in manifests) { JObject thisManifest = Downloader.GetJobjectFromManifest(manifest); PS2Downloader.DownloadPS2Job(thisManifest, null, "Live", dateTime => { SendMessage("#reside_priv", "Live has finished Downloading"); Branch b = Branch.Live; string analysis = PS2Analyzer.AnalyzePS2(Constants.Directories[b]); string branchName = "Live-" + now.ToString("yyyy-MM-dd"); AutoAnalyze("Live", analysis, branchName); SendMessage("#reside", "Live Changes: " + string.Format("http://www.testoutfit.info/lebot/RevisionReports/{0}", branchName + "Changes.txt")); SendMessage("#ps-universe", "Live Changes: " + string.Format("http://www.testoutfit.info/lebot/RevisionReports/{0}", branchName + "Changes.txt")); SendMessage("#reside_priv", "Live Changes: " + string.Format("http://www.testoutfit.info/lebot/RevisionReports/{0}", branchName + "Changes.txt")); }, "LiveDownload"); } }; EventTypes["QueueTestDownload"] = (data) => { DateTime now = DateTime.Now; SendMessage("#reside_priv", "Test has started downloading"); string[] manifests = new string[] { "http://manifest.patch.station.sony.com/patch/sha/manifest/planetside2/planetside2-test/live/planetside2-test.sha.soe", "http://manifest.patch.station.sony.com/patch/sha/manifest/planetside2/planetside2-testcommon/live/planetside2-testcommon.sha.soe", }; foreach (string manifest in manifests) { JObject thisManifest = Downloader.GetJobjectFromManifest(manifest); PS2Downloader.DownloadPS2Job(thisManifest, null, "Test", dateTime => { SendMessage("#reside_priv", "Test has finished Downloading"); Branch b = Branch.Test; string analysis = PS2Analyzer.AnalyzePS2(Constants.Directories[b]); string branchName = "Test-" + now.ToString("yyyy-MM-dd"); AutoAnalyze("Test", analysis, branchName); SendMessage("#reside", "Test Changes: " + string.Format("http://www.testoutfit.info/lebot/RevisionReports/{0}", branchName + "Changes.txt")); SendMessage("#ps-universe", "Test Changes: " + string.Format("http://www.testoutfit.info/lebot/RevisionReports/{0}", branchName + "Changes.txt")); SendMessage("#reside_priv", "Test Changes: " + string.Format("http://www.testoutfit.info/lebot/RevisionReports/{0}", branchName + "Changes.txt")); }, "TestDownload"); } }; EventTypes["QueueEQNLDownload"] = (data) => { DateTime now = DateTime.Now; SendMessage("#reside_priv", "EQNLandmark has started downloading"); string[] manifests = new string[] { "http://manifest.patch.station.sony.com/patch/eqnext/test/digest/play/test64-cdn.soe", "http://manifest.patch.station.sony.com/patch/eqnext/test/digest/play/shared-cdn.soe", "http://manifest.patch.station.sony.com/patch/eqnext/test/digest/common/shared-cdn.soe", "http://manifest.patch.station.sony.com/patch/eqnext/test/digest/common/test-cdn.soe", }; foreach (string manifest in manifests) { JObject thisManifest = Downloader.GetJobjectFromManifest(manifest); EQNDownloader.DownloadPS2Job(thisManifest, null, "EQNLandmark", dateTime => { SendMessage("#reside_priv", "EQNLandmark has finished Downloading"); Branch b = Branch.EQNLandmark; string analysis = PS2Analyzer.AnalyzePS2(Constants.Directories[b]); string branchName = "EQNLandmark-" + now.ToString("yyyy-MM-dd"); AutoAnalyze("EQNLandmark", analysis, branchName); SendMessage("#reside", "EQNLandmark Changes: " + string.Format("http://www.testoutfit.info/lebot/RevisionReports/{0}", branchName + "Changes.txt")); SendMessage("#ps-universe", "EQNLandmark Changes: " + string.Format("http://www.testoutfit.info/lebot/RevisionReports/{0}", branchName + "Changes.txt")); SendMessage("#reside_priv", "EQNLandmark Changes: " + string.Format("http://www.testoutfit.info/lebot/RevisionReports/{0}", branchName + "Changes.txt")); }, "EQNLDownload"); } }; }
/** * download file thread * * @author Happy Fish / YuQing * @version Version 1.0 */ public static void DownloadThread(object obj) { int thread_index = (int)obj; try { string file_id; Downloader downloader = new Downloader(); Console.WriteLine("download thread " + thread_index + " start"); file_id = ""; while (TestLoad.upload_thread_count != 0 || file_id != null) { file_ids.TryDequeue(out file_id); if (file_id == null) { Thread.Sleep(10); continue; } lock (counter_lock) { TestLoad.total_download_count++; } if (downloader.downloadFile(file_id) == 0) { lock (counter_lock) { TestLoad.success_download_count++; } } else { TestLoad.fail_download_count++; } } for (int i = 0; i < 3 && TestLoad.total_download_count < TestLoad.total_upload_count; i++) { file_ids.TryDequeue(out file_id); if (file_id == null) { Thread.Sleep(10); continue; } lock (counter_lock) { TestLoad.total_download_count++; } if (downloader.downloadFile(file_id) == 0) { lock (counter_lock) { TestLoad.success_download_count++; } } else { TestLoad.fail_download_count++; } } } catch (Exception ex) { Log.Error(ex.Message + ex.StackTrace); } Console.WriteLine("download thread " + thread_index + " exit, total_download_count: " + TestLoad.total_download_count + ", success_download_count: " + TestLoad.success_download_count + ", fail_download_count: " + TestLoad.fail_download_count); }
public static void SelfUpdate(UpdateRegistry reg, Downloader downloader, int[] newVersion) { try { LogMessage("INSTALLING Driveclient"); string version_text = newVersion[0].ToString() + "." + newVersion[1].ToString("00") + "." + newVersion[2].ToString("000000"); string base_name = "driveclient-setup-" + version_text + ".msi"; string msi = downloader.mStagingFolder + "\\" + base_name; if (reg.mDebug) { LogMessage("MSI: " + msi); } downloader.GetFile(reg, msi); ProcessStartInfo proc = new ProcessStartInfo(); proc.CreateNoWindow = true; proc.RedirectStandardError = true; proc.RedirectStandardInput = true; proc.RedirectStandardOutput = true; proc.UseShellExecute = false; proc.ErrorDialog = false; proc.WindowStyle = ProcessWindowStyle.Hidden; proc.FileName = "msiexec.exe"; proc.Arguments = "/qn /i " + msi + " /L*v " + downloader.mStagingFolder + "\\" + base_name + ".log"; if (reg.mDebug) { LogMessage("installing with: " + proc.Arguments); } Process child = new Process(); child.StartInfo = proc; if (child.Start()) { LogMessage("install started: " + proc.Arguments); //child.WaitForExit(); //string result = InterpretErrorCode(child.ExitCode); //LogMessage("install started: " + proc.Arguments + " exit status: \"" + result + "\""); } else { LogMessage("install failed to start: " + proc.Arguments); } } catch (System.Exception e) { LogException("install general: " + e); } }
void infoDownloader_Completed(object sender, DownloaderEventArgs e) { #region 通过XmlReader解析xml配置文件(无需额外dll,较慢) //WebClient infoDownloader = sender as WebClient; //infoDownloader.OpenReadCompleted -= wc_OpenReadCompleted; ////通过XmlReader解析配置文件 //XmlReader info = XmlReader.Create(e.Result as Stream); //while (info.Read()) { // if (info.IsStartElement("Sprite")) { // info.MoveToAttribute("RealWidth"); info.ReadAttributeValue(); RealWidth = Convert.ToDouble(info.Value); // info.MoveToAttribute("FullName"); info.ReadAttributeValue(); FullName = info.Value; // info.MoveToAttribute("ATK"); info.ReadAttributeValue(); ATK = Convert.ToInt32(info.Value); // info.MoveToAttribute("DEF"); info.ReadAttributeValue(); DEF = Convert.ToInt32(info.Value); // info.MoveToAttribute("MAG"); info.ReadAttributeValue(); MAG = Convert.ToInt32(info.Value); // info.MoveToAttribute("DEX"); info.ReadAttributeValue(); DEX = Convert.ToInt32(info.Value); // info.MoveToAttribute("Speed"); info.ReadAttributeValue(); Speed = Convert.ToDouble(info.Value); // info.MoveToAttribute("AttackType"); info.ReadAttributeValue(); AttackType = (AttackTypes)Convert.ToInt32(info.Value); // info.MoveToAttribute("GuardDistance"); info.ReadAttributeValue(); GuardDistance = Convert.ToInt32(info.Value); // info.MoveToAttribute("SightDistance"); info.ReadAttributeValue(); SightDistance = Convert.ToInt32(info.Value); // info.MoveToAttribute("AttackDistance"); info.ReadAttributeValue(); AttackDistance = Convert.ToInt32(info.Value); // info.MoveToAttribute("CastingDistance"); info.ReadAttributeValue(); CastingDistance = Convert.ToInt32(info.Value); // info.MoveToAttribute("LifeWidthMax"); info.ReadAttributeValue(); LifeWidthMax = Convert.ToDouble(info.Value); // info.MoveToAttribute("LifeCenterY"); info.ReadAttributeValue(); LifeCenterY = Convert.ToDouble(info.Value); // info.MoveToAttribute("CenterX"); info.ReadAttributeValue(); double centerX = Convert.ToDouble(info.Value); // info.MoveToAttribute("CenterY"); info.ReadAttributeValue(); double centerY = Convert.ToDouble(info.Value); // Center = new Point(centerX, centerY); // info.MoveToAttribute("ModelCode"); info.ReadAttributeValue(); ModelCode = Convert.ToInt32(info.Value); // frames = new Frames(); // info.MoveToAttribute("StandTotalFrame"); info.ReadAttributeValue(); frames.StandTotal = Convert.ToInt32(info.Value); // info.MoveToAttribute("StandEffectFrame"); info.ReadAttributeValue(); frames.StandEffect = Convert.ToInt32(info.Value); // info.MoveToAttribute("StandInterval"); info.ReadAttributeValue(); frames.StandInterval = Convert.ToInt32(info.Value); // info.MoveToAttribute("RunTotalFrame"); info.ReadAttributeValue(); frames.RunTotal = Convert.ToInt32(info.Value); // info.MoveToAttribute("RunEffectFrame"); info.ReadAttributeValue(); frames.RunEffect = Convert.ToInt32(info.Value); // info.MoveToAttribute("RunInterval"); info.ReadAttributeValue(); frames.RunInterval = Convert.ToInt32(info.Value); // info.MoveToAttribute("AttackTotalFrame"); info.ReadAttributeValue(); frames.AttackTotal = Convert.ToInt32(info.Value); // info.MoveToAttribute("AttackEffectFrame"); info.ReadAttributeValue(); frames.AttackEffect = Convert.ToInt32(info.Value); // info.MoveToAttribute("AttackInterval"); info.ReadAttributeValue(); frames.AttackInterval = Convert.ToInt32(info.Value); // info.MoveToAttribute("InjureTotalFrame"); info.ReadAttributeValue(); frames.InjureTotal = Convert.ToInt32(info.Value); // info.MoveToAttribute("InjureEffectFrame"); info.ReadAttributeValue(); frames.InjureEffect = Convert.ToInt32(info.Value); // info.MoveToAttribute("InjureInterval"); info.ReadAttributeValue(); frames.InjureInterval = Convert.ToInt32(info.Value); // info.MoveToAttribute("CastingTotalFrame"); info.ReadAttributeValue(); frames.CastingTotal = Convert.ToInt32(info.Value); // info.MoveToAttribute("CastingEffectFrame"); info.ReadAttributeValue(); frames.CastingEffect = Convert.ToInt32(info.Value); // info.MoveToAttribute("CastingInterval"); info.ReadAttributeValue(); frames.CastingInterval = Convert.ToInt32(info.Value); // } else if (info.IsStartElement("Frames")) { // while (info.Read()) { // if (info.IsStartElement("Frame")) { // info.MoveToAttribute("ID"); info.ReadAttributeValue(); string id = info.Value; // info.MoveToAttribute("OffsetX"); info.ReadAttributeValue(); int offsetX = Convert.ToInt32(info.Value); // info.MoveToAttribute("OffsetY"); info.ReadAttributeValue(); int offsetY = Convert.ToInt32(info.Value); // frameOffset.Add(id, new Point2D() { X = offsetX, Y = offsetY }); // } // } // } //} #endregion #region 通过LinqToSql解析xml配置文件(需要100多K的dll支持,快) Downloader infoDownloader = sender as Downloader; infoDownloader.Completed -= infoDownloader_Completed; string key = string.Format("SpriteInfo{0}", infoDownloader.ResCode); if (e.Stream != null) { Global.AddResInfo(key, XElement.Load(e.Stream)); } //通过LINQ2XML解析配置文件 XElement info = Global.ResInfos[key].DescendantsAndSelf("Sprite").Single(); RealWidth = (double)info.Attribute("RealWidth"); FullName = info.Attribute("FullName").Value; ATK = (int)info.Attribute("ATK"); DEF = (int)info.Attribute("DEF"); MAG = (int)info.Attribute("MAG"); DEX = (int)info.Attribute("DEX"); Speed = (double)info.Attribute("Speed"); AttackType = (AttackTypes)(int)info.Attribute("AttackType"); GuardDistance = (int)info.Attribute("GuardDistance"); SightDistance = (int)info.Attribute("SightDistance"); AttackDistance = (int)info.Attribute("AttackDistance"); CastingDistance = (int)info.Attribute("CastingDistance"); LifeWidthMax = (double)info.Attribute("LifeWidthMax"); LifeCenterY = (double)info.Attribute("LifeCenterY"); Center = new Point((double)info.Attribute("CenterX"), (double)info.Attribute("CenterY")); ModelCode = (int)info.Attribute("ModelCode"); frames = new Frames() { StandTotal = (int)info.Attribute("StandTotalFrame"), StandEffect = (int)info.Attribute("StandEffectFrame"), StandInterval = (int)info.Attribute("StandInterval"), RunTotal = (int)info.Attribute("RunTotalFrame"), RunEffect = (int)info.Attribute("RunEffectFrame"), RunInterval = (int)info.Attribute("RunInterval"), AttackTotal = (int)info.Attribute("AttackTotalFrame"), AttackEffect = (int)info.Attribute("AttackEffectFrame"), AttackInterval = (int)info.Attribute("AttackInterval"), InjureTotal = (int)info.Attribute("InjureTotalFrame"), InjureEffect = (int)info.Attribute("InjureEffectFrame"), InjureInterval = (int)info.Attribute("InjureInterval"), CastingTotal = (int)info.Attribute("CastingTotalFrame"), CastingEffect = (int)info.Attribute("CastingEffectFrame"), CastingInterval = (int)info.Attribute("CastingInterval"), }; //解析各帧偏移 IEnumerable<XElement> iFrame = Global.ResInfos[key].Element("Frames").Elements(); frameOffset.Clear(); foreach (XElement element in iFrame) { frameOffset.Add(element.Attribute("ID").Value, new Point2D() { X = (int)element.Attribute("OffsetX"), Y = (int)element.Attribute("OffsetY"), }); } #endregion if (State == States.Stand) { Stand(); } Coordinate = new Point(Coordinate.X + 0.000001, Coordinate.Y); Life = Life; HeartStart(); if (ConfigReady != null) { ConfigReady(this, null); } //开始下载所需资源 if (resList.ContainsKey(infoDownloader.ResCode)) { IsResReady = true; } else { #region 方案3 //Downloader downloadQueue = new Downloader() { Index = index, ResCode = infoDownloader.ResCode }; //EventHandler<DownloaderEventArgs> handler = null; //downloadQueue.Completed += handler = delegate { // downloadQueue.Completed -= handler; // if (downloadQueue.Index == index) { IsResReady = true; } //换装异步与呈现同步之间的协调 // loadedCodes.Add(downloadQueue.ResCode); // //解析精灵图片资源地址表 // List<string> uris = new List<string>(); // int n = 0; // for (int i = 0; i < (int)info.Attribute("StateTotal"); i++) { // switch (i) { // case 0: n = frames.StandTotal; break; // case 1: n = frames.RunTotal; break; // case 2: n = frames.AttackTotal; break; // case 3: n = frames.InjureTotal; break; // case 4: n = frames.CastingTotal; break; // } // for (int j = 0; j < (int)info.Attribute("DirectionTotal"); j++) { // for (int k = 0; k <= n; k++) { // uris.Add(Global.WebPath(string.Format("Sprite/{0}/{1}-{2}-{3}.png", Code, i, j, k))); // } // } // } //}; //downloadQueue.Download(string.Format("SpriteRes{0}", infoDownloader.ResCode), uris); #endregion #region 方案1、2 IsResReady = false; Downloader resDownloader = new Downloader() { Index = index, ResCode = infoDownloader.ResCode }; EventHandler<DownloaderEventArgs> handler = null; resDownloader.Completed += handler = (sender1, e1) => { resDownloader.Completed -= handler; if (resDownloader.Index == index) { IsResReady = true; } if (!resList.ContainsKey(resDownloader.ResCode)) { resList.Add(resDownloader.ResCode, new StreamResourceInfo(e1.Stream, "application/binary")); } }; resDownloader.Download(string.Format("Sprite{0}.xap", infoDownloader.ResCode)); #endregion } }
/// <summary> /// Executes the actual download from an URL. Does not handle exceptions, /// but takes care of proper cleanup. /// </summary> /// <exception cref="NonBinaryFileException">This exception is thrown, if the resulting file is not of a binary type</exception> /// <exception cref="TargetPathInvalidException">This exception is thrown, if the resulting target path of an application is not valid</exception> /// <param name="job">The job to process</param> /// <param name="urlToRequest">URL from which should be downloaded</param> /// <returns>true, if a new update has been found and downloaded, false otherwise</returns> protected Status DoDownload(ApplicationJob job, Uri urlToRequest) { // Lower security policies try { ServicePointManager.CheckCertificateRevocationList = false; } catch (PlatformNotSupportedException) { // .NET bug under special circumstances } ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); }; // If we want to download multiple files simultaneously // from the same server, we need to "remove" the connection limit. ServicePointManager.DefaultConnectionLimit = 50; // Determine number of segments to create int segmentCount = Convert.ToInt32(Settings.GetValue("SegmentCount", 1)); job.Variables.ResetDownloadCount(); WebRequest req = KetarinProtocolProvider.CreateRequest(urlToRequest, job, this.m_Cookies); AddRequestToCancel(req); using (WebResponse response = WebClient.GetResponse(req)) { LogDialog.Log(job, "Server source file: " + req.RequestUri.AbsolutePath); // Occasionally, websites are not available and an error page is encountered // For the case that the content type is just plain wrong, ignore it if the size is higher than 500KB HttpWebResponse httpResponse = response as HttpWebResponse; if (httpResponse != null && response.ContentLength < 500000) { if (response.ContentType.StartsWith("text/xml") || response.ContentType.StartsWith("application/xml")) { // If an XML file is served, maybe we have a PAD file ApplicationJob padJob = ApplicationJob.ImportFromPad(httpResponse); if (padJob != null) { job.CachedPadFileVersion = padJob.CachedPadFileVersion; return(this.DoDownload(job, new Uri(padJob.FixedDownloadUrl))); } } if (response.ContentType.StartsWith("text/html")) { throw NonBinaryFileException.Create(response.ContentType, httpResponse.StatusCode); } } long fileSize = GetContentLength(response); if (fileSize == 0) { throw new IOException("Source file on server is empty (ContentLength = 0)."); } string targetFileName = job.GetTargetFile(response, urlToRequest.AbsoluteUri); LogDialog.Log(job, "Determined target file name: " + targetFileName); // Only download, if the file size or date has changed if (!ForceDownload && !job.RequiresDownload(response, targetFileName)) { // If file already exists (created by user), // the download is not necessary. We still need to // set the file name. // If the file exists, but not at the target location // (after renaming), do not reset the previous location. if (File.Exists(targetFileName)) { job.PreviousLocation = targetFileName; } job.Save(); return(Status.NoUpdate); } // Skip downloading! // Installing also requires a forced download if (!ForceDownload && !m_InstallUpdated && (m_OnlyCheck || (job.CheckForUpdatesOnly && !IgnoreCheckForUpdatesOnly))) { LogDialog.Log(job, "Skipped downloading updates"); return(Status.UpdateAvailable); } // Execute: Default pre-update command string defaultPreCommand = Settings.GetValue("PreUpdateCommand", "") as string; // For starting external download managers: {preupdate-url} defaultPreCommand = UrlVariable.Replace(defaultPreCommand, "preupdate-url", urlToRequest.ToString(), job); ScriptType defaultPreCommandType = Command.ConvertToScriptType(Settings.GetValue("PreUpdateCommandType", ScriptType.Batch.ToString()) as string); int exitCode = new Command(defaultPreCommand, defaultPreCommandType).Execute(job, targetFileName); if (exitCode == 1) { LogDialog.Log(job, "Default pre-update command returned '1', download aborted"); throw new CommandErrorException(); } else if (exitCode == 2) { LogDialog.Log(job, "Default pre-update command returned '2', download skipped"); return(Status.UpdateAvailable); } // Execute: Application pre-update command exitCode = new Command(UrlVariable.Replace(job.ExecutePreCommand, "preupdate-url", urlToRequest.ToString(), job), job.ExecutePreCommandType).Execute(job, targetFileName); if (exitCode == 1) { LogDialog.Log(job, "Pre-update command returned '1', download aborted"); throw new CommandErrorException(); } else if (exitCode == 2) { LogDialog.Log(job, "Pre-update command returned '2', download skipped"); return(Status.UpdateAvailable); } else if (exitCode == 3) { LogDialog.Log(job, "Pre-update command returned '3', external download"); job.LastUpdated = DateTime.Now; job.Save(); return(Status.UpdateSuccessful); } // Read all file contents to a temporary location string tmpLocation = Path.GetTempFileName(); DateTime lastWriteTime = ApplicationJob.GetLastModified(response); // Only use segmented downloader with more than one segment. if (segmentCount > 1) { // Response can be closed now, new one will be created. response.Dispose(); m_Size[job] = fileSize; Downloader d = new Downloader(new ResourceLocation { Url = urlToRequest.AbsoluteUri, ProtocolProvider = new KetarinProtocolProvider(job, m_Cookies) }, null, tmpLocation, segmentCount); d.Start(); while (d.State < DownloaderState.Ended) { if (m_CancelUpdates) { d.Pause(); break; } this.OnProgressChanged(d.Segments.Sum(x => x.Transfered), fileSize, job); Thread.Sleep(250); } if (d.State == DownloaderState.EndedWithError) { throw d.LastError; } } else { // Read contents from the web and put into file using (Stream sourceFile = response.GetResponseStream()) { using (FileStream targetFile = File.Create(tmpLocation)) { long byteCount = 0; int readBytes; m_Size[job] = fileSize; // Only create buffer once and re-use. const int bufferSize = 1024 * 1024; byte[] buffer = new byte[bufferSize]; do { if (m_CancelUpdates) { break; } // Some adjustment for SCP download: Read only up to the max known bytes int maxRead = (fileSize > 0) ? (int)Math.Min(fileSize - byteCount, bufferSize) : bufferSize; if (maxRead == 0) { break; } readBytes = sourceFile.Read(buffer, 0, maxRead); if (readBytes > 0) { targetFile.Write(buffer, 0, readBytes); } byteCount += readBytes; this.OnProgressChanged(byteCount, fileSize, job); } while (readBytes > 0); } } } if (m_CancelUpdates) { m_Progress[job] = 0; OnStatusChanged(job); return(Status.Failure); } // If each version has a different file name (version number), // we might only want to keep one of them. Also, we might // want to free some space on the target location. if (job.DeletePreviousFile) { PathEx.TryDeleteFiles(job.PreviousLocation); } try { File.SetLastWriteTime(tmpLocation, lastWriteTime); } catch (ArgumentException) { // Invalid file date. Ignore and just use DateTime.Now } // File downloaded. Now let's check if the hash value is valid or abort otherwise! if (!string.IsNullOrEmpty(job.HashVariable) && job.HashType != HashType.None) { string varName = job.HashVariable.Trim('{', '}'); string expectedHash = job.Variables.ReplaceAllInString("{" + varName + "}").Trim(); // Compare online hash with actual current hash. if (!string.IsNullOrEmpty(expectedHash)) { string currentHash = job.GetFileHash(tmpLocation); if (string.Compare(expectedHash, currentHash, StringComparison.OrdinalIgnoreCase) != 0) { LogDialog.Log(job, string.Format("File downloaded, but hash of downloaded file {0} does not match the expected hash {1}.", currentHash, expectedHash)); File.Delete(tmpLocation); throw new IOException("Hash verification failed."); } } } try { FileInfo downloadedFileInfo = new FileInfo(tmpLocation); job.LastFileSize = downloadedFileInfo.Length; job.LastFileDate = downloadedFileInfo.LastWriteTime; } catch (Exception ex) { LogDialog.Log(job, ex); } try { // Before copying, we might have to create the directory Directory.CreateDirectory(Path.GetDirectoryName(targetFileName)); // Copying might fail if variables have been replaced with bad values. // However, we cannot rely on functions to clean up the path, since they // might actually parse the path incorrectly and return an even worse path. File.Copy(tmpLocation, targetFileName, true); } catch (ArgumentException) { throw new TargetPathInvalidException(targetFileName); } catch (NotSupportedException) { throw new TargetPathInvalidException(targetFileName); } File.Delete(tmpLocation); // At this point, the update is complete job.LastUpdated = DateTime.Now; job.PreviousLocation = targetFileName; } job.Save(); job.ExecutePostUpdateCommands(); return(Status.UpdateSuccessful); }
public virtual void Initialize(Downloader downloader) { }
/// <summary> /// Scrapes the poster image collection. /// </summary> /// <param name="id">The MovieUniqueId for the scraper.</param> /// <param name="threadID">The thread MovieUniqueId.</param> /// <param name="output">The scraped poster image collection.</param> /// <param name="logCatagory">The log catagory.</param> /// <returns>Scrape succeeded [true/false]</returns> public new bool ScrapePoster(string id, int threadID, out BindingList <ImageDetailsModel> output, string logCatagory) { output = new BindingList <ImageDetailsModel>(); try { foreach (var type in new[] { "product", "poster" }) { var individualPosterHtml = Downloader.ProcessDownload( string.Format("http://www.imdb.com/title/{0}/mediaindex?refine={1}", id, type), DownloadType.Html, Section.Movies).RemoveCharacterReturn(); var matches = YRegex.MatchesToList( @"(?<url>/rg/mediaindex/unknown-thumbnail/media/rm\d{10}/tt\d{7})", individualPosterHtml, "url"); foreach (var m in matches) { if (!m.Contains("swf")) { var newHtml = Downloader.ProcessDownload(string.Format("http://www.imdb.com{0}", m), DownloadType.Html, Section.Movies).RemoveCharacterReturn(); var match = Regex.Match( newHtml, @"src=""(?<url>http://ia\.media-imdb\.com/images/M/(?<str>[A-Za-z0-9_]+?)@@\._V1\._SX(?<width>\d{3})_SY(?<height>\d{3})_\.jpg)""\s"); if (match.Success) { var matchValue = match.Groups["url"].Value; int width; int height; int.TryParse(match.Groups["width"].Value, out width); int.TryParse(match.Groups["height"].Value, out height); if (height > width) { if (!string.IsNullOrEmpty(matchValue)) { output.Add( new ImageDetailsModel { Height = height, Width = width, UriFull = new Uri(matchValue) }); } } } } } } return(output.IsFilled()); } catch (Exception ex) { Log.WriteToLog(LogSeverity.Error, threadID, logCatagory, ex.Message); return(false); } }
public override void Initialize(Downloader downloader) { base.Initialize(downloader); downloader.Ending += new EventHandler(downloader_Ending); }
public async Task DownloadQueueAll(string path, List <VODData> list) { Debug.WriteLine("DownloadQueueAll Start"); var maxDownload = int.Parse(MaxDownloadTextBox.Text); var maxChunk = int.Parse(MaxChunkTextBox.Text); await Dispatcher.UIThread.InvokeAsync(() => { AllDownloadProgressBar.Maximum = list.Count; CurDownloadProgressBar.Maximum = 1; }); for (int i = 0; i < list.Count; i++) { var data = list[i]; var status = new Action <string>(async(message) => { if (Dispatcher.UIThread.CheckAccess()) { DownloadStatusTextBlock.Text = $"다운로드: {message} [{data.Summary}]"; } else { await Dispatcher.UIThread.InvokeAsync(() => { DownloadStatusTextBlock.Text = $"다운로드: {message} [{data.Summary}]"; }); } }); status("시작됨"); var root = Path.Combine(path, data.StreamerId); if (!Directory.Exists(root)) { Directory.CreateDirectory(root); } var downTo = Path.Combine(root, $"Fin_{data.StreamerId}_" + Regex.Replace(data.BroadcastDate, "[^0-9.]", "") + $"-TVD-{data.VODHeader}.mp4"); var downloader = new Downloader(data.VODHeader, downTo, ffmpegArg, proxy); downloader.maxDownload = maxDownload; downloader.maxChunkInMemory = maxChunk; downloader.Start(); while (!downloader.IsFinished) { await Dispatcher.UIThread.InvokeAsync(() => { status($"Delayed chunk count: {downloader.DownloadedChunk - downloader.PushedChunk}"); if (downloader.ChunkCount == 0) { CurDownloadProgressBar.Value = 0; } else { CurDownloadProgressBar.Value = downloader.PushedChunk / (double)downloader.ChunkCount; } AllDownloadProgressBar.Value = i + CurDownloadProgressBar.Value; }); await Task.Delay(100); } status("완료, 다음 작업 확인중"); } Debug.WriteLine("DownloadQueueAll End"); }
static bool sNodeid = false; //true when a nodeid has been parsed #endregion Fields #region Methods static void Main(string[] args) { bool error = false; if (args.Length < 4) { //if to few arguments then print info and quit printSyntax(); error = true; } if (!error) { //parse commandline arguments CommandLine=new Arguments(args); //check single arguments if (CommandLine["b"] == "true") { aBios = true; } if (CommandLine["r"] == "true") { aReset = true; } if (CommandLine["s"] == "true") { aStart = true; } if (CommandLine["t"] == "true") { aTerminal = true; } //check hexfile argument hexfile = CommandLine["f"]; if (hexfile != null) { sHexfile = true; } if (!aTerminal && !sHexfile && !aReset && !aStart) { if (DEBUG_LEVEL>0) { Console.WriteLine("When not in terminal mode a hexfile, a reset or a start parameter must be supplied, I quit"); } error = true; } //check nodeid argument string node = CommandLine["n"]; if (node != null) { if (!parseNodeId(node)) { error = true; } } if (!aTerminal && !sNodeid) { if (DEBUG_LEVEL>0) { Console.WriteLine("When not in terminal mode a nodeid must be supplied, I quit"); } error = true; } //check host and port arguments host = CommandLine["h"]; string sPort = CommandLine["p"]; if ((host == null) || (sPort.Length == 0)) { if (DEBUG_LEVEL>0) { printSyntax(); } error = true; } else { try { port = int.Parse(sPort); } catch { if (DEBUG_LEVEL>0) { Console.WriteLine("Was not able to parse port, I quit"); } error = true; } } } if (!error) { //commandline feedback output if (DEBUG_LEVEL>2) { Console.WriteLine("canDude settings:"); if (sNodeid) { Console.WriteLine("Nodeaddress: 0x" + String.Format("{0:x2}", nodeid)); } Console.WriteLine("Host: {0}:{1}", host, port); if (hexfile != null) { Console.WriteLine("Hexfile: {0}", hexfile); } Console.Write("Parameters: "); if (aBios) { Console.Write("Bios "); } if (aReset) { Console.Write("Reset "); } if (aStart) { Console.Write("Start "); } if (aTerminal) { Console.Write("Terminal"); } Console.WriteLine(""); } } if (!error) { //connect to candaemon dc = new DaemonConnection(); if (dc.init(host, port)) { if (DEBUG_LEVEL>1) { Console.WriteLine("Connected to candaemon"); } } else { if (DEBUG_LEVEL>0) { Console.WriteLine("Connection to candaemon could not be established, I quit"); } error = true; } } if (!error && aTerminal) { //terminal mode (==interactive mode) bool success = true; //load hexfile if one has been specified as commandline argument hf = new HexFile(); if (sHexfile && success) { if (hf.loadHex(hexfile)) { if (DEBUG_LEVEL>1) { Console.WriteLine("Hexfile loaded"); } } else { success = false; } } if (success) { if (DEBUG_LEVEL>1) { Console.WriteLine(""); printHelp(); //print available commands Console.WriteLine(""); } string instr; do { Console.Write("> "); //a command has been executed, print a new console char instr = Console.ReadLine(); //read std in } while (parseInput(instr)); //parse a line from std in //exit command } } if (!error && !aTerminal) { //not terminal mode bool success = true; if (sHexfile) { //load hexfile (a hexfile must be supplied as commandline argument) hf = new HexFile(); if (hf.loadHex(hexfile)) { if (DEBUG_LEVEL>1) { Console.WriteLine("Hexfile loaded"); } } else { success = false; if (DEBUG_LEVEL>0) { Console.WriteLine("Hexfile could not be loaded, I quit"); } } } //if a hexfile is loaded then start autodownloading sequence if (success) { bool autosuccess = true; CanNMT cpn = new CanNMT(); if (aReset) { //send a reset command (and wait for feedback) if (!cpn.doReset(dc, nodeid)) { if (DEBUG_LEVEL>0) { Console.WriteLine("Target node did not respond to reset, I quit"); } autosuccess = false; } } if (sHexfile && autosuccess) { //send application dl = new Downloader(hf, dc, nodeid, aBios); if (!dl.go()) { if (DEBUG_LEVEL>0) { Console.WriteLine("Error occured during download"); } autosuccess = false; } } if (autosuccess && aStart) { //start application cpn.doStart(dc, nodeid); } } } if (dc != null) { //stop tcp client thread dc.stop(); } }
public void Run() { CheckIfRunning(); Stat = Status.Running; IsExited = false; #if !NET_CORE // 开启多线程支持 System.Net.ServicePointManager.DefaultConnectionLimit = 1000; #endif InitComponent(); IMonitorableScheduler monitor = (IMonitorableScheduler)Scheduler; if (StartTime == DateTime.MinValue) { StartTime = DateTime.Now; } Parallel.For(0, ThreadNum, new ParallelOptions { MaxDegreeOfParallelism = ThreadNum }, i => { int waitCount = 0; bool firstTask = false; var downloader = Downloader.Clone(); while (Stat == Status.Running) { Request request = Scheduler.Poll(); if (request == null) { if (waitCount > _waitCountLimit && IsExitWhenComplete) { Stat = Status.Finished; break; } // wait until new url added WaitNewUrl(ref waitCount); } else { waitCount = 0; try { ProcessRequest(request, downloader); Thread.Sleep(_random.Next(Site.MinSleepTime, Site.MaxSleepTime)); #if TEST System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Reset(); sw.Start(); #endif OnSuccess(request); #if TEST sw.Stop(); Console.WriteLine("OnSuccess:" + (sw.ElapsedMilliseconds).ToString()); #endif } catch (Exception e) { OnError(request); Logger.Error("采集失败: " + request.Url + ".", e); } finally { #if !NET_CORE if (Site.HttpProxyPoolEnable && request.GetExtra(Request.Proxy) != null) { Site.ReturnHttpProxyToPool((HttpHost)request.GetExtra(Request.Proxy), (int)request.GetExtra(Request.StatusCode)); } #endif } if (!firstTask) { Thread.Sleep(3000); firstTask = true; } } } }); FinishedTime = DateTime.Now; SpiderClosingEvent?.Invoke(); foreach (IPipeline pipeline in Pipelines) { SafeDestroy(pipeline); } if (Stat == Status.Finished) { OnClose(); Logger.Info($"任务 {Identity} 结束, 运行时间: " + (FinishedTime - StartTime).TotalSeconds + " 秒."); } if (Stat == Status.Stopped) { Logger.Info("任务 " + Identity + " 停止成功, 运行时间: " + (FinishedTime - StartTime).TotalSeconds + " 秒."); } if (Stat == Status.Exited) { Logger.Info("任务 " + Identity + " 退出成功, 运行时间: " + (FinishedTime - StartTime).TotalSeconds + " 秒."); } Logger.Dispose(); IsExited = true; }
public static void OnPollForUpgrade(object source, ElapsedEventArgs e) { UpdateRegistry reg = new UpdateRegistry(); if (!reg.mIsValid) { return; } DateTime start_time = DateTime.Now.Date.AddMinutes(reg.mStartTime.Minute).AddHours(reg.mStartTime.Hour); if (start_time < reg.mLastTime) { LogMessage("SKIPPING UPDATE: " + start_time + " is earlier than " + reg.mLastTime); return; } // TODO: DOWNLOAD VERSION FROM RELEASE SERVER AND SEE IF WE NEED TO UPDATE Downloader downloader = new Downloader(); int[] new_version = GetNewVersion(reg, downloader); if (new_version.Length != 3) { return; } // TODO: DOWNLOAD DRIVECLIENT VERSION FROM RELEASE SERVER AND INSTALL IT // - INITIAL PROTOTYPE WILL NOT DOWNLOAD ANY FILES // - SECOND PROTOTYPE WILL ONLY DOWNLOAD VERSION FILE // - THIRD PROTOTYPE WILL DOWNLOAD MSI SelfUpdate(reg, downloader, new_version); // TODO: TO SPOOF THIS PROCESS: // - PUT DUMMY VERSION FILE IN %TMP% // - COMPILE VERSION 1.1 MSI AND RENAME IT // - COMPILE VERSION 1.2 MSI AND COPY IT TO %TMP% // - INSTALL VERSION 1.1 MSI // - VERSION 1.1 MSI SHOULD CHECK VERSION FILE IN %TMP% // - VERSION 1.1 MSI SHOULD EXECUTE VERSION 1.2 MSI FROM %TMP% }
private void Awake() { s_instance = this; this.NORMAL_SCALE = base.transform.localScale; this.HIDDEN_SCALE = (Vector3)(0.01f * this.NORMAL_SCALE); FatalErrorMgr.Get().AddErrorListener(new FatalErrorMgr.ErrorCallback(this.OnFatalError)); OverlayUI.Get().AddGameObject(base.gameObject, CanvasAnchor.CENTER, false, CanvasScaleMode.HEIGHT); if (UniversalInputManager.UsePhoneUI == null) { this.m_graphicsRes.setItemTextCallback(new DropdownControl.itemTextCallback(this.OnGraphicsResolutionDropdownText)); this.m_graphicsRes.setItemChosenCallback(new DropdownControl.itemChosenCallback(this.OnNewGraphicsResolution)); foreach (GraphicsResolution resolution in this.GetGoodGraphicsResolution()) { this.m_graphicsRes.addItem(resolution); } this.m_graphicsRes.setSelection(this.GetCurrentGraphicsResolution()); this.m_fullScreenCheckbox.AddEventListener(UIEventType.RELEASE, new UIEvent.Handler(this.OnToggleFullScreenCheckbox)); this.m_fullScreenCheckbox.SetChecked(Options.Get().GetBool(Option.GFX_FULLSCREEN, Screen.fullScreen)); this.m_graphicsQuality.addItem(GameStrings.Get("GLOBAL_OPTIONS_GRAPHICS_QUALITY_LOW")); this.m_graphicsQuality.addItem(GameStrings.Get("GLOBAL_OPTIONS_GRAPHICS_QUALITY_MEDIUM")); this.m_graphicsQuality.addItem(GameStrings.Get("GLOBAL_OPTIONS_GRAPHICS_QUALITY_HIGH")); this.m_graphicsQuality.setSelection(this.GetCurrentGraphicsQuality()); this.m_graphicsQuality.setItemChosenCallback(new DropdownControl.itemChosenCallback(this.OnNewGraphicsQuality)); } this.m_masterVolume.SetValue(Options.Get().GetFloat(Option.SOUND_VOLUME)); this.m_masterVolume.SetUpdateHandler(new ScrollbarControl.UpdateHandler(this.OnNewMasterVolume)); this.m_masterVolume.SetFinishHandler(new ScrollbarControl.FinishHandler(this.OnMasterVolumeRelease)); this.m_musicVolume.SetValue(Options.Get().GetFloat(Option.MUSIC_VOLUME)); this.m_musicVolume.SetUpdateHandler(new ScrollbarControl.UpdateHandler(this.OnNewMusicVolume)); if (this.m_backgroundSound != null) { this.m_backgroundSound.AddEventListener(UIEventType.RELEASE, new UIEvent.Handler(this.ToggleBackgroundSound)); this.m_backgroundSound.SetChecked(Options.Get().GetBool(Option.BACKGROUND_SOUND)); } this.UpdateCreditsUI(); this.m_nearbyPlayers.AddEventListener(UIEventType.RELEASE, new UIEvent.Handler(this.ToggleNearbyPlayers)); this.m_nearbyPlayers.SetChecked(Options.Get().GetBool(Option.NEARBY_PLAYERS)); this.m_spectatorOpenJoinCheckbox.AddEventListener(UIEventType.RELEASE, new UIEvent.Handler(this.ToggleSpectatorOpenJoin)); this.m_spectatorOpenJoinCheckbox.SetChecked(Options.Get().GetBool(Option.SPECTATOR_OPEN_JOIN)); this.m_languageGroup.gameObject.SetActive((bool)this.LANGUAGE_SELECTION); if (this.LANGUAGE_SELECTION != null) { if (Localization.GetLocale() == Locale.jaJP) { this.m_languageDropdown.setFontWithoutLocalization(this.m_languageDropdownFont); } else { this.m_languageDropdown.setFont(this.m_languageDropdownFont.m_Font); } IEnumerator enumerator = Enum.GetValues(typeof(Locale)).GetEnumerator(); try { while (enumerator.MoveNext()) { Locale current = (Locale)((int)enumerator.Current); switch (current) { case Locale.UNKNOWN: case Locale.enGB: { continue; } } this.m_languageDropdown.addItem(GameStrings.Get(this.StringNameFromLocale(current))); } } finally { IDisposable disposable = enumerator as IDisposable; if (disposable == null) { } disposable.Dispose(); } this.m_languageDropdown.setSelection(this.GetCurrentLanguage()); this.m_languageDropdown.setItemChosenCallback(new DropdownControl.itemChosenCallback(this.OnNewLanguage)); } if ((AssetLoader.DOWNLOADABLE_LANGUAGE_PACKS != null) && ApplicationMgr.IsInternal()) { this.m_languagePackCheckbox.gameObject.SetActive(true); this.m_languagePackCheckbox.AddEventListener(UIEventType.RELEASE, new UIEvent.Handler(this.ToggleLanguagePackCheckbox)); this.m_languagePackCheckbox.SetChecked(Downloader.Get().AllLocalizedAudioBundlesDownloaded()); } this.m_creditsButton.AddEventListener(UIEventType.RELEASE, new UIEvent.Handler(this.OnCreditsButtonReleased)); this.m_cinematicButton.AddEventListener(UIEventType.RELEASE, new UIEvent.Handler(this.OnCinematicButtonReleased)); this.m_inputBlocker.AddEventListener(UIEventType.RELEASE, e => this.Hide(true)); this.ShowOrHide(false); this.m_leftPane.UpdateSlices(); this.m_rightPane.UpdateSlices(); this.m_middlePane.UpdateSlices(); }
public static int[] GetNewVersion(UpdateRegistry reg, Downloader downloader) { try { string file_name = "agent_version.txt"; if (!downloader.GetFile(reg, file_name)) { LogMessage("ERROR: could not get: " + file_name); return new int[0]; } string upgrade_version_file = downloader.mStagingFolder + "\\" + file_name; int[] upgrade_version = GetVersionInfo(reg, upgrade_version_file); if (upgrade_version.Length == 0) { LogMessage("ERROR: getting version info from: " + upgrade_version_file); return new int[0]; } string installed_version_file = reg.mInstallFolder + file_name; int[] installed_version = GetVersionInfo(reg); // save the last time we checked for updates reg.SaveUpdateTime(); if (upgrade_version[0] != installed_version[0] || upgrade_version[1] != installed_version[1] || upgrade_version[2] != installed_version[2]) { // NOTE: installed version file is updated by the MSI return upgrade_version; } // NOTE: If we set the time here, we will continue to upgrade until we are current; // however, that could also get us into an endless loop, if we mess up the version // numbers. //reg.SaveUpdateTime(); } catch (System.ArgumentNullException e) { LogException("version null argument: " + e); } catch (System.IO.PathTooLongException e) { LogException("version path: " + e); } catch (System.IO.DirectoryNotFoundException e) { LogException("version directory: " + e); } catch (System.IO.IOException e) { LogException("version I/O: " + e); } catch (System.UnauthorizedAccessException e) { LogException("version unauthorized: " + e); } catch (System.NotSupportedException e) { LogException("version not supported: " + e); } catch (System.Security.SecurityException e) { LogException("version security: " + e); } catch (System.FormatException e) { LogException("version format: " + e); } catch (System.OverflowException e) { LogException("version overflow: " + e); } catch (System.Exception e) { LogException("version general: " + e); } return new int[0]; }
/// <summary> /// Constructor /// </summary> /// <param name="p"></param> public PeopleHtmlParser(People p) { people = p; downloader = new Downloader(People.peopleLinkHeader + people.id); }
private void App_Startup(object sender, StartupEventArgs e) { Global.StartupDateTime = DateTime.Now; //Unhandled Exceptions. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; //Increases the duration of the tooltip display. ToolTipService.ShowDurationProperty.OverrideMetadata(typeof(DependencyObject), new FrameworkPropertyMetadata(int.MaxValue)); var version = FrameworkHelper.GetFrameworkVersion(); if (version > new Version(4, 7, 2)) { SetSecurityProtocol(); } //Parse arguments. Argument.Prepare(e.Args); LocalizationHelper.SelectCulture(UserSettings.All.LanguageCode); ThemeHelper.SelectTheme(UserSettings.All.MainTheme); #region Download mode if (Argument.IsInDownloadMode) { var downloader = new Downloader { DownloadMode = Argument.DownloadMode, DestinationPath = Argument.DownloadPath }; downloader.ShowDialog(); Environment.Exit(90); return; } #endregion #region If set, it allows only one instance per user //The singleton works on a per-user and per-executable mode. //Meaning that a different user and/or a different executable intances can co-exist. //Part of this code wont work on debug mode, since the SetForegroundWindow() needs focus on the foreground window calling the method. if (UserSettings.All.SingleInstance) { try { using (var thisProcess = Process.GetCurrentProcess()) { var user = System.Security.Principal.WindowsIdentity.GetCurrent().User; var name = thisProcess.MainModule?.FileName ?? Assembly.GetEntryAssembly()?.Location ?? "ScreenToGif"; var location = Convert.ToBase64String(Encoding.UTF8.GetBytes(name)); var mutexName = (user?.Value ?? Environment.UserName) + "_" + location; _mutex = new Mutex(true, mutexName, out _accepted); //If the mutext failed to be accepted, it means that another process already openned it. if (!_accepted) { var warning = true; //Switch to the other app (get only one, if multiple available). Use name of assembly. using (var process = Process.GetProcessesByName(thisProcess.ProcessName).FirstOrDefault(f => f.MainWindowHandle != thisProcess.MainWindowHandle)) { if (process != null) { var handles = Util.Native.GetWindowHandlesFromProcess(process); //Show the window before setting focus. Util.Native.ShowWindow(handles.Count > 0 ? handles[0] : process.Handle, Util.Native.ShowWindowEnum.Show); //Set user the focus to the window. Util.Native.SetForegroundWindow(handles.Count > 0 ? handles[0] : process.Handle); warning = false; InterProcess.SendMessage(e.Args); } } //If no window available (app is in the system tray), display a warning. if (warning) { Dialog.Ok(LocalizationHelper.Get("S.Warning.Single.Title"), LocalizationHelper.Get("S.Warning.Single.Header"), LocalizationHelper.Get("S.Warning.Single.Message"), Icons.Info); } Environment.Exit(0); return; } //If this is the first instance, register the inter process channel to listen for other instances. InterProcess.RegisterServer(); } } catch (Exception ex) { LogWriter.Log(ex, "Impossible to check if another instance is running"); } } #endregion //Render mode. RenderOptions.ProcessRenderMode = UserSettings.All.DisableHardwareAcceleration ? RenderMode.SoftwareOnly : RenderMode.Default; #region Net Framework if (version < new Version(4, 8)) { var ask = Dialog.Ask(LocalizationHelper.Get("S.Warning.Net.Title"), LocalizationHelper.Get("S.Warning.Net.Header"), LocalizationHelper.Get("S.Warning.Net.Message")); if (ask) { Process.Start("http://go.microsoft.com/fwlink/?LinkId=2085155"); return; } } #endregion if (version > new Version(4, 7)) { SetWorkaroundForDispatcher(); } #region Net Framework HotFixes //Only runs on Windows 7 SP1. if (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor == 1) { Task.Factory.StartNew(() => { try { var search = new ManagementObjectSearcher("SELECT HotFixID FROM Win32_QuickFixEngineering WHERE HotFixID = 'KB4055002'").Get(); Global.IsHotFix4055002Installed = search.Count > 0; } catch (Exception ex) { LogWriter.Log(ex, "Error while trying to know if a hot fix was installed."); } }); } #endregion #region Tray icon and view model NotifyIcon = (NotifyIcon)FindResource("NotifyIcon"); if (NotifyIcon != null) { NotifyIcon.Visibility = UserSettings.All.ShowNotificationIcon || UserSettings.All.StartMinimized || UserSettings.All.StartUp == 5 ? Visibility.Visible : Visibility.Collapsed; //Replace the old option with the new setting. if (UserSettings.All.StartUp == 5) { UserSettings.All.StartMinimized = true; UserSettings.All.ShowNotificationIcon = true; UserSettings.All.StartUp = 0; } //using (var iconStream = GetResourceStream(new Uri("pack://application:,,,/Resources/Logo.ico"))?.Stream) //{ // if (iconStream != null) // NotifyIcon.Icon = new System.Drawing.Icon(iconStream); //} } MainViewModel = (ApplicationViewModel)FindResource("AppViewModel") ?? new ApplicationViewModel(); RegisterShortcuts(); #endregion //var test = new TestField(); test.ShowDialog(); return; //var test = new Windows.EditorEx(); test.ShowDialog(); return; //var test = new Windows.NewWebcam(); test.ShowDialog(); return; //var test = Settings.UserSettings.All.StartupTop; #region Tasks Task.Factory.StartNew(MainViewModel.ClearTemporaryFiles, TaskCreationOptions.LongRunning); Task.Factory.StartNew(MainViewModel.CheckForUpdates, TaskCreationOptions.LongRunning); Task.Factory.StartNew(MainViewModel.SendFeedback, TaskCreationOptions.LongRunning); #endregion #region Startup //When starting minimized, the if (UserSettings.All.StartMinimized) { return; } if (UserSettings.All.StartUp == 4 || Argument.FileNames.Any()) { MainViewModel.OpenEditor.Execute(null); return; } if (UserSettings.All.StartUp < 1 || UserSettings.All.StartUp > 4) { MainViewModel.OpenLauncher.Execute(null); return; } if (UserSettings.All.StartUp == 1) { MainViewModel.OpenRecorder.Execute(null); return; } if (UserSettings.All.StartUp == 2) { MainViewModel.OpenWebcamRecorder.Execute(null); return; } if (UserSettings.All.StartUp == 3) { MainViewModel.OpenBoardRecorder.Execute(null); } #endregion }
// Token: 0x06006074 RID: 24692 RVA: 0x0021F7B8 File Offset: 0x0021DBB8 public void SetupWorldInfo(ApiWorld world, ApiWorld.WorldInstance instance = null, bool newInstance = false, bool isPortal = false) { if (instance == null) { instance = world.GetBestInstance(null, false); } this.mWorld = world; this.worldInstance = instance; this.openedFromPortal = isPortal; ApiWorld.WorldInstance.AccessType accessType = this.worldInstance.GetAccessType(); ApiWorld.WorldInstance.AccessDetail accessDetail = ApiWorld.WorldInstance.GetAccessDetail(accessType); string str = string.Empty; this.roomName.text = world.name; string instanceCreator = this.worldInstance.GetInstanceCreator(); str = accessDetail.shortName; this.instanceStatus.text = accessDetail.fullName; if (accessType == ApiWorld.WorldInstance.AccessType.Public) { this.roomAuthor.text = world.authorName; this.roomOwner.text = world.authorName; } else if (accessType == ApiWorld.WorldInstance.AccessType.InviteOnly || accessType == ApiWorld.WorldInstance.AccessType.FriendsOnly || accessType == ApiWorld.WorldInstance.AccessType.FriendsOfGuests) { this.roomAuthor.text = world.authorName; this.roomOwner.text = "(loading...)"; APIUser.Fetch(instanceCreator, delegate(APIUser user) { this.roomOwner.text = user.displayName; }, null); } this.playerCount.text = this.worldInstance.count.ToString(); this.maxPlayers.text = world.capacity.ToString(); this.worldInstanceId.text = "#" + this.worldInstance.idOnly + " " + str; Downloader.DownloadImage(world.imageUrl, delegate(string downloadedUrl, Texture2D obj) { this.roomImage.texture = obj; }, string.Empty); this.isPortalMenu = isPortal; this.ConfigureJoinButton(instance.count >= world.capacity, instance.isPublic); this.ConfigurePortalButton(accessType, instanceCreator == APIUser.CurrentUser.id, instance.count >= world.capacity, instance.isPublic); if (isPortal) { this.backButton.GetComponentInChildren <Text>().text = "Exit"; this.backButton.onClick.AddListener(new UnityAction(this.Respawn)); VRCUiManager.Instance.ShowScreen("UserInterface/MenuContent/Backdrop/Backdrop"); VRCUiManager.Instance.HideScreen("HEADER"); QuickMenu.Instance.CanExitWithButton = false; } else { this.backButton.onClick.AddListener(new UnityAction(this.BackToWorlds)); this.backButton.GetComponentInChildren <Text>().text = "Back"; } if (this.il != null) { this.il.world = world; this.il.Refresh(); } if (world.releaseStatus == "public" || world.authorId == APIUser.CurrentUser.id) { this.newInstanceButton.interactable = true; } if (instance.count >= world.capacity) { this.playerCount.text = "Full"; } this.SetCurrentInstanceMessage(string.Empty, false); if (RoomManager.inRoom) { ApiWorld currentRoom = RoomManager.currentRoom; if (currentRoom.id == world.id && currentRoom.currentInstanceIdWithTags == this.worldInstance.idWithTags) { this.SetCurrentInstanceMessage("You are here", true); } } if (newInstance) { this.SetCurrentInstanceMessage("NEW INSTANCE", true); } }