private static void DeletePayloadParts(int nrParts, string payloadName) { for (int id = 0; id < nrParts; ++id) { System.IO.File.Delete(LegacyDownloader.MakePartFileName(payloadName, id)); } }
private PayloadInfo GetRemotePayloadInfo(string url) { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Method = "Head"; req.KeepAlive = false; HttpWebResponse response; PayloadInfo payloadInfo; try { LegacyDownloader.Add64BitRange(req, 0L, 0L); response = (HttpWebResponse)req.GetResponse(); string httpResponseHeaders = LegacyDownloader.GetHTTPResponseHeaders(response); this.mResponseHeaders = response.Headers; Logger.Warning(httpResponseHeaders); payloadInfo = response.StatusCode != HttpStatusCode.PartialContent ? (response.StatusCode != HttpStatusCode.OK ? new PayloadInfo(false, 0L, true) : (!httpResponseHeaders.Contains("Accept-Ranges: bytes") ? new PayloadInfo(false, response.ContentLength, false) : new PayloadInfo(true, response.ContentLength, false))) : new PayloadInfo(true, LegacyDownloader.GetSizeFromContentRange(response), false); } catch (Exception ex) { Logger.Error(ex.ToString()); throw; } response.Close(); return(payloadInfo); }
public void DownloadApk( string apkUrl, string packageName, bool isLaunchAfterInstall, bool isDeleteApk, string timestamp = "") { string str = Path.Combine(RegistryStrings.DataDir, "DownloadedApk"); if (!Directory.Exists(str)) { Directory.CreateDirectory(str); } string path2 = Regex.Replace(packageName + ".apk", "[\\x22\\\\\\/:*?|<>]", " "); string apkFilePath = Path.Combine(str, path2); Logger.Info("Downloading Apk file to: " + apkFilePath); this.ParentWindow.mWelcomeTab.mHomeAppManager.DownloadStarted(packageName); ClientStats.SendClientStatsAsync("download", "unknown", "app_install", packageName, "", ""); this.mDownloadThread = new Thread((ThreadStart)(() => { string apkUrl1 = apkUrl; if (DownloadInstallApk.IsContainsGoogleAdId(apkUrl1)) { apkUrl = this.AddGoogleAdidWithApk(apkUrl1); } apkUrl = BlueStacksUIUtils.GetFinalRedirectedUrl(apkUrl); if (string.IsNullOrEmpty(apkUrl)) { return; } this.mIsDownloading = true; this.mDownloader = new LegacyDownloader(3, apkUrl, apkFilePath); this.mDownloader.Download((LegacyDownloader.UpdateProgressCallback)(percent => this.ParentWindow.mWelcomeTab.mHomeAppManager.UpdateAppDownloadProgress(packageName, percent)), (LegacyDownloader.DownloadCompletedCallback)(filePath => { ClientStats.SendClientStatsAsync("download", "success", "app_install", packageName, "", ""); this.mIsDownloading = false; this.ParentWindow.mWelcomeTab.mHomeAppManager.DownloadCompleted(packageName, filePath); this.InstallApk(packageName, filePath, isLaunchAfterInstall, isDeleteApk, timestamp); DownloadInstallApk.sDownloadedApkList.Add(packageName); }), (LegacyDownloader.ExceptionCallback)(ex => { ClientStats.SendClientStatsAsync("download", "fail", "app_install", packageName, "", ""); this.ParentWindow.mWelcomeTab.mHomeAppManager.DownloadFailed(packageName); Logger.Error("Failed to download file: {0}. err: {1}", (object)apkFilePath, (object)ex.Message); }), (LegacyDownloader.ContentTypeCallback)null, (LegacyDownloader.SizeDownloadedCallback)null, (LegacyDownloader.PayloadInfoCallback)null); })) { IsBackground = true }; this.mDownloadThread.Start(); }
private static void MakePayload(int nrWorkers, string payloadName) { Stream stream1 = (Stream) new FileStream(payloadName, FileMode.Create, FileAccess.Write, FileShare.None); int count1 = 16384; byte[] buffer = new byte[count1]; for (int id = 0; id < nrWorkers; ++id) { Stream stream2 = (Stream) new FileStream(LegacyDownloader.MakePartFileName(payloadName, id), FileMode.Open, FileAccess.Read); int count2; while ((count2 = stream2.Read(buffer, 0, count1)) > 0) { stream1.Write(buffer, 0, count2); } stream2.Close(); } stream1.Flush(); stream1.Close(); }
public void Download( LegacyDownloader.UpdateProgressCallback updateProgressCb, LegacyDownloader.DownloadCompletedCallback downloadedCb, LegacyDownloader.ExceptionCallback exceptionCb, LegacyDownloader.ContentTypeCallback contentTypeCb = null, LegacyDownloader.SizeDownloadedCallback sizeDownloadedCb = null, LegacyDownloader.PayloadInfoCallback pInfoCb = null) { this.mUpdateProgressCallback = updateProgressCb; this.mDownloadCompletedCallback = downloadedCb; this.mExceptionCallback = exceptionCb; this.mContentTypeCallback = contentTypeCb; this.mSizeDownloadedCallback = sizeDownloadedCb; this.mPayloadInfoCallback = pInfoCb; Logger.Info("Downloading {0} to: {1}", (object)this.mUrl, (object)this.mFileName); string mFileName = this.mFileName; try { string path = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), Path.GetFileName(this.mFileName)); string filePath; if (System.IO.File.Exists(path)) { Logger.Info("{0} already downloaded to {1}", (object)this.mUrl, (object)path); filePath = path; } else { PayloadInfo remotePayloadInfo; try { remotePayloadInfo = this.GetRemotePayloadInfo(this.mUrl); if (pInfoCb != null) { pInfoCb(remotePayloadInfo.Size); } if (remotePayloadInfo.InvalidHTTPStatusCode) { Logger.Error("Invalid http status code."); exceptionCb(new Exception(Convert.ToString(ReturnCodesUInt.DOWNLOAD_FAILED_INVALID_STATUS_CODE, (IFormatProvider)CultureInfo.InvariantCulture))); return; } string mResponseHeader = this.mResponseHeaders["Content-Type"]; if (mResponseHeader == "application/vnd.android.package-archive") { this.mFileName = Path.ChangeExtension(this.mFileName, ".apk"); } filePath = this.mFileName; if (contentTypeCb != null) { if (!contentTypeCb(mResponseHeader)) { Logger.Info("Cancelling download"); return; } } } catch (WebException ex) { if (ex.Status == WebExceptionStatus.NameResolutionFailure) { Logger.Error("The hostname could not be resolved. Url = " + this.mUrl); exceptionCb(new Exception(Convert.ToString(ReturnCodesUInt.DOWNLOAD_FAILED_HOSTNAME_NOT_RESOLVED, (IFormatProvider)CultureInfo.InvariantCulture))); return; } if (ex.Status == WebExceptionStatus.Timeout) { Logger.Error("The operation has timed out. Url = " + this.mUrl); exceptionCb(new Exception(Convert.ToString(ReturnCodesUInt.DOWNLOAD_FAILED_OPERATION_TIMEOUT, (IFormatProvider)CultureInfo.InvariantCulture))); return; } Logger.Error("A WebException has occured. Url = " + this.mUrl); exceptionCb((Exception)ex); return; } catch (Exception ex) { Logger.Error(string.Format((IFormatProvider)CultureInfo.InvariantCulture, "Unable to send to {0}", (object)this.mUrl)); throw; } if (System.IO.File.Exists(this.mFileName)) { if (LegacyDownloader.IsPayloadOk(this.mFileName, remotePayloadInfo.Size)) { Logger.Info(this.mUrl + " already downloaded"); goto label_27; } else { System.IO.File.Delete(this.mFileName); } } if (!remotePayloadInfo.SupportsRangeRequest) { this.mNrWorkers = 1; } this.mWorkers = this.MakeWorkers(this.mNrWorkers, this.mUrl, this.mFileName, remotePayloadInfo.Size); Logger.Info("Starting download of " + this.mFileName); int prevAverageTotalPercent = 0; LegacyDownloader.StartWorkers(this.mWorkers, (LegacyDownloader.ProgressCallback)(() => { int num = 0; long size = 0; foreach (KeyValuePair <Thread, LegacyDownloader.Worker> mWorker in this.mWorkers) { num += mWorker.Value.PercentComplete; size += mWorker.Value.TotalFileDownloaded; } LegacyDownloader.SizeDownloadedCallback downloadedCallback = sizeDownloadedCb; if (downloadedCallback != null) { downloadedCallback(size); } int percent = num / this.mWorkers.Count; if (percent != prevAverageTotalPercent) { updateProgressCb(percent); } prevAverageTotalPercent = percent; })); LegacyDownloader.WaitForWorkers(this.mWorkers); LegacyDownloader.MakePayload(this.mNrWorkers, this.mFileName); if (!LegacyDownloader.IsPayloadOk(this.mFileName, remotePayloadInfo.Size)) { string str = "Downloaded file not of the correct size"; Logger.Info(str); System.IO.File.Delete(this.mFileName); throw new Exception(str); } Logger.Info("File downloaded correctly"); LegacyDownloader.DeletePayloadParts(this.mNrWorkers, this.mFileName); } label_27: downloadedCb(filePath); } catch (Exception ex) { Logger.Error("Exception in Download. err: " + ex.ToString()); exceptionCb(ex); } }
public void DoWork(object data) { LegacyDownloader.Worker worker = (LegacyDownloader.Worker)data; Range range = worker?.Range; Stream stream1 = (Stream)null; HttpWebResponse res = (HttpWebResponse)null; Stream stream2 = (Stream)null; try { Logger.Info("WorkerId {0} range.From = {1}, range.To = {2}", (object)worker.Id, (object)range.From, (object)range.To); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(worker.URL); req.KeepAlive = true; if (System.IO.File.Exists(worker.PartFileName)) { stream1 = (Stream) new FileStream(worker.PartFileName, FileMode.Append, FileAccess.Write, FileShare.None); if (stream1.Length == range.Length) { worker.TotalFileDownloaded = stream1.Length; worker.PercentComplete = 100; Logger.Info("WorkerId {0} already downloaded", (object)worker.Id); return; } worker.TotalFileDownloaded = stream1.Length; worker.PercentComplete = (int)(stream1.Length * 100L / range.Length); Logger.Info("WorkerId {0} Resuming from range.From = {1}, range.To = {2}", (object)worker.Id, (object)(range.From + stream1.Length), (object)range.To); if (this.mNrWorkers > 1) { LegacyDownloader.Add64BitRange(req, range.From + stream1.Length, range.To); } } else { worker.TotalFileDownloaded = 0L; worker.PercentComplete = 0; stream1 = (Stream) new FileStream(worker.PartFileName, FileMode.Create, FileAccess.Write, FileShare.None); if (this.mNrWorkers > 1) { LegacyDownloader.Add64BitRange(req, range.From + stream1.Length, range.To); } } req.ReadWriteTimeout = 60000; res = (HttpWebResponse)req.GetResponse(); long contentLength = res.ContentLength; stream2 = res.GetResponseStream(); int count1 = 65536; byte[] buffer = new byte[count1]; long num = 0; Logger.Warning(string.Format((IFormatProvider)CultureInfo.InvariantCulture, "WorkerId {0}\n", (object)worker.Id) + LegacyDownloader.GetHTTPResponseHeaders(res)); int count2; while ((count2 = stream2.Read(buffer, 0, count1)) > 0) { if (worker.Cancelled) { throw new OperationCanceledException("Download cancelled by user."); } stream1.Write(buffer, 0, count2); num += (long)count2; worker.TotalFileDownloaded = stream1.Length; worker.PercentComplete = (int)(stream1.Length * 100L / range.Length); } if (contentLength != num) { throw new Exception(string.Format((IFormatProvider)CultureInfo.InvariantCulture, "totalContentRead({0}) != contentLength({1})", (object)num, (object)contentLength)); } } catch (Exception ex) { worker.Exception = ex; Logger.Error(ex.ToString()); } finally { stream2?.Close(); res?.Close(); if (stream1 != null) { stream1.Flush(); stream1.Close(); } } Logger.Info("WorkerId {0} Finished", (object)worker.Id); }
public void MaybeDownloadAndLaunchBTv(MainWindow parentWindow) { if (!BTVManager.IsBTVInstalled()) { if (this.sDownloading && this.sWindow != null) { BTVManager.BringToFront((CustomWindow)this.sWindow); } else { ExtensionPopupControl btvExtPopup = new ExtensionPopupControl(); btvExtPopup.LoadExtensionPopupFromFolder("BTVExtensionPopup"); System.Action action1; System.Action action2; btvExtPopup.DownloadClicked += (EventHandler)((o, e) => { BlueStacksUIUtils.CloseContainerWindow((FrameworkElement)btvExtPopup); this.sDownloading = true; this.sWindow = new CustomMessageWindow(); BlueStacksUIBinding.Bind(this.sWindow.TitleTextBlock, "STRING_BTV_DOWNLOAD", ""); BlueStacksUIBinding.Bind(this.sWindow.BodyTextBlock, "STRING_BTV_INSTALL_WAIT", ""); BlueStacksUIBinding.Bind(this.sWindow.BodyWarningTextBlock, "STRING_BTV_WARNING", ""); this.sWindow.AddButton(ButtonColors.Blue, "STRING_CANCEL", new EventHandler(this.CancelDownloadConfirmation), (string)null, false, (object)null, true); this.sWindow.BodyWarningTextBlock.Visibility = Visibility.Visible; this.sWindow.ProgressBarEnabled = true; this.sWindow.IsWindowMinizable = true; this.sWindow.IsWindowClosable = false; this.sWindow.ImageName = "BTVTopBar"; this.sWindow.ShowInTaskbar = true; this.sWindow.Owner = (Window)parentWindow; this.sWindow.IsShowGLWindow = true; this.sWindow.Show(); new Thread(closure_3 ?? (closure_3 = (ThreadStart)(() => { if (!string.IsNullOrEmpty(RegistryManager.Instance.BtvDevServer)) { BTVManager.sBTvUrl = RegistryManager.Instance.BtvDevServer; } string redirectedUrl = BTVManager.GetRedirectedUrl(BTVManager.sBTvUrl); if (redirectedUrl == null) { Logger.Error("The download url was null"); } else { string downloadPath = Path.Combine(Path.GetTempPath(), Path.GetFileName(new Uri(redirectedUrl).LocalPath)); this.sDownloader = new LegacyDownloader(3, redirectedUrl, downloadPath); this.sDownloader.Download((LegacyDownloader.UpdateProgressCallback)(percent => { // ISSUE: variable of a compiler-generated type BTVManager.\u003C\u003Ec__DisplayClass25_0 cDisplayClass250 = this; int percent1 = percent; // ISSUE: reference to a compiler-generated field this.sWindow.Dispatcher.Invoke((Delegate)(() => cDisplayClass250.\u003C\u003E4__this.sWindow.CustomProgressBar.Value = (double)percent1)); }), (LegacyDownloader.DownloadCompletedCallback)(filePath => { this.sWindow.Dispatcher.Invoke((Delegate)(action1 ?? (action1 = (System.Action)(() => { this.sWindow.CustomProgressBar.Value = 100.0; this.sWindow.Close(); })))); Logger.Info("Successfully downloaded BlueStacks TV"); this.sDownloading = false; BTVManager.ExtractBTv(downloadPath); parentWindow.Dispatcher.Invoke((Delegate)(action2 ?? (action2 = (System.Action)(() => parentWindow.mTopBar.mBtvButton.ImageName = "btv")))); }), (LegacyDownloader.ExceptionCallback)(ex => Logger.Error("Failed to download file: {0}. err: {1}", (object)downloadPath, (object)ex.Message)), (LegacyDownloader.ContentTypeCallback)null, (LegacyDownloader.SizeDownloadedCallback)null, (LegacyDownloader.PayloadInfoCallback)null); } }))) { IsBackground = true }.Start(); }); btvExtPopup.Height = parentWindow.ActualHeight * 0.8; btvExtPopup.Width = btvExtPopup.Height * 16.0 / 9.0; ContainerWindow containerWindow = new ContainerWindow(parentWindow, (System.Windows.Controls.UserControl)btvExtPopup, (double)(int)btvExtPopup.Width, (double)(int)btvExtPopup.Height, false, true, false, -1.0, (Brush)null); } } else { this.StartBlueStacksTV(); } }