private async static Task FetchMegaFile(string inSaveLocation, DownloadProgressCallback delProgress) { string megaUrl = await FetchMegaUrl(); if (File.Exists(inSaveLocation)) { File.Delete(inSaveLocation); } // Because the MegaApiClient just Task.Run()s (rather than actually parking until the native events are over) // I might want to use the single-threaded API all wrapped in a single Task.Run(). Probably negligible gains // though (only save ~number of commands - 1 threadpool requests) and it could be annoying if I want to handle // user input for ex: "Do you want to retry?" MegaApiClient client = new MegaApiClient(); try { await client.LoginAnonymousAsync(); INodeInfo node = await client.GetNodeFromLinkAsync(new Uri(megaUrl)); await client.DownloadFileAsync(new Uri(megaUrl), inSaveLocation, new ProgressReporter(delProgress, node.Size)); } catch (Exception ex) { // Check to see if we can split up the errors any further. throw new CannotConnectToMegaException("", ex);; } finally { await client.LogoutAsync(); } }
/// <summary> /// Handles a mod add via URL. /// Validates the URL, gets ModInfos, downloads mod archive, adds it to the ModSelection and installs the mod if selected. /// </summary> /// <param name="url">The URL to the mod.</param> /// <param name="modName">The name for the mod.</param> /// <param name="install">Flag to determine if the mod should be installed after adding.</param> /// <param name="downloadProgressCallback">Callback function for download progress.</param> /// <returns>The root node of the added mod, or null.</returns> public ModNode HandleAdd(string url, string modName, bool install, DownloadProgressCallback downloadProgressCallback = null) { url = ReduceToPlainUrl(url); ModInfo modInfo = GetModInfo(url); if (modInfo == null) { return(null); } if (!string.IsNullOrEmpty(modName)) { modInfo.Name = modName; } ModNode newMod = null; if (DownloadMod(ref modInfo, downloadProgressCallback)) { newMod = ModSelectionController.HandleModAddViaModInfo(modInfo, install); } return(newMod); }
public async static Task DownloadAndInstall(DownloadProgressCallback delDownloadProgress, UnzipStartCallback delUnzipStart) { // Fetch the current version. // NOTE: YandereDev says that he always updates version.txt *after* the new build upload is complete. // As such, we should be able to rely upon version.txt as a cache buster. // If he goofs, he can just re-increment version.txt. string versionOnSite = await FetchHttpText(GameVersionHttp); await FetchMegaFile(inSaveLocation : GameZipSaveLocation, delProgress : delDownloadProgress); if (System.IO.Directory.Exists(GameDirectoryPath)) { // C# struggles to delete folders if, for example, there's an active Windows Explorer looking into them. bool successful = DeleteAsMuchAsPossible(GameDirectoryPath); } delUnzipStart(); await UnpackZipFile(inFile : GameZipSaveLocation, inUnpackLocation : GameDirectoryPath); using (System.IO.StreamWriter gameVersionFile = System.IO.File.CreateText(GameVersionFilePath)) { gameVersionFile.WriteLine(versionOnSite); } if (System.IO.File.Exists(GameZipSaveLocation)) { System.IO.File.Delete(GameZipSaveLocation); } }
/// <summary> /// Default constructor. /// </summary> /// <param name="uploadProgressCallback">Upload progress call back delegate.</param> /// <param name="downloadProgressCallback">Download progress call back delegate.</param> /// <param name="uploadCompleteCallback">Upload complete call back delegate.</param> /// <param name="downloadCompleteCallback">Download complete call back delegate.</param> /// <param name="onCommandError">On error delegate event handler.</param> /// <param name="onAsyncThreadError">On async thread error delegate event handler.</param> /// <param name="credentials">The user credentials.</param> /// <param name="connection">The server connection data.</param> /// <param name="filePath">The file path transfer data.</param> /// <param name="internalFilePath">The internal file path transfer data.</param> /// <param name="operation">The current operation.</param> /// <param name="secureConnection">Is the connection secure.</param> /// <param name="timeout">The time out for the operation.</param> public FileTransferDataChannel( UploadProgressCallback uploadProgressCallback, DownloadProgressCallback downloadProgressCallback, UploadCompleteCallback uploadCompleteCallback, DownloadCompleteCallback downloadCompleteCallback, ClientCommandHandler onCommandError, ClientThreadErrorHandler onAsyncThreadError, NetworkCredential credentials, FileTransferConnection connection, FileTransferPath filePath, FileTransferPath internalFilePath, Operation operation, bool secureConnection, int timeout) { _connection = new FileTransferConnection(); _connection.Host = connection.Host; _connection.Port = connection.Port; _connection.ValidateCertificate = false; _connection.UseDataChannel = false; _secureConnection = secureConnection; _credentials = credentials; _filePath = filePath; _operation = operation; _timeout = timeout; _internalFilePath = internalFilePath; _onCommandError = onCommandError; _onAsyncThreadError = onAsyncThreadError; _uploadProgressCallback = uploadProgressCallback; _downloadProgressCallback = downloadProgressCallback; _uploadCompleteCallback = uploadCompleteCallback; _downloadCompleteCallback = downloadCompleteCallback; }
public void Download(DownloadProgressCallback downloadProgressCallback = default, UnzipProgressCallback unzipProgressCallback = default) { if (Interlocked.CompareExchange(ref _syncPoint, 1, 0) != 0) { throw new InvalidOperationException("A download or cleanup operation is already in progress."); } var webRequest = (HttpWebRequest)WebRequest.Create(DownloadUrl); try { using (var response = (HttpWebResponse)webRequest.GetResponse()) using (var responseStream = response.GetResponseStream() ?? throw new DiskCleanupException($"Error downloading CCleaner from {DownloadUrl}.")) using (var fileStream = _zip.OpenWrite()) { var downloaded = 0L; var buffer = new byte[8192]; int read; while ((read = responseStream.Read(buffer, 0, buffer.Length)) > 0) { fileStream.Write(buffer, 0, read); downloaded += read; downloadProgressCallback?.Invoke(response.ContentLength, downloaded); } } UnzipFile(_zip, Path.Combine(_zip.Directory.FullName, "CCleanerPortable"), unzipProgressCallback); } finally { Interlocked.Decrement(ref _syncPoint); } }
/// <summary> /// Downloads a file. /// Filename will be taken from WebResponse.ResponseUri.AbsolutePath /// </summary> /// <param name="downloadURL">Url to the file to download.</param> /// <param name="downloadPath">Path to save the file to without filename!</param> /// <param name="downloadProgressCallback">Callback function which will receive download progress information.</param> /// <returns>The full path to the downloaded file (path and filename).</returns> public static string DownloadFile2(string downloadURL, string downloadPath, DownloadProgressCallback downloadProgressCallback = null) { string fullpath = string.Empty; using (WebClient wcDownload = new WebClient()) { Stream strResponse = null; Stream strLocal = null; try { // Create a request to the file we are downloading HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(downloadURL); // Set default authentication for retrieving the file webRequest.Credentials = CredentialCache.DefaultCredentials; // Retrieve the response from the server HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse(); // Ask the server for the file size and store it long fileSize = webResponse.ContentLength; string filename = Path.GetFileName(webResponse.ResponseUri.AbsolutePath); fullpath = Path.Combine(downloadPath, filename); fullpath = GetNewFilenameWhenDestinationExists(fullpath); // Open the URL for download strResponse = wcDownload.OpenRead(downloadURL); // Create a new file stream where we will be saving the data (local drive) strLocal = new FileStream(fullpath, FileMode.Create, FileAccess.Write, FileShare.None); // It will store the current number of bytes we retrieved from the server int bytesSize = 0; // A buffer for storing and writing the data retrieved from the server byte[] downBuffer = new byte[2048]; // Loop through the buffer until the buffer is empty while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0) { // Write the data from the buffer to the local hard drive strLocal.Write(downBuffer, 0, bytesSize); // Invoke the method that propagates the progress. if (downloadProgressCallback != null) { downloadProgressCallback(strLocal.Length, fileSize); } } } catch (Exception ex) { Messenger.AddError(string.Format("Error while downloading \"{0}\"!", downloadURL), ex); fullpath = string.Empty; } finally { // When the above code has ended, close the streams strResponse.Close(); strLocal.Close(); } return(fullpath); } }
/// <summary> /// Handles a mod add via URL. /// Validates the URL, gets ModInfos, downloads mod archive, adds it to the ModSelection and installs the mod if selected. /// </summary> /// <param name="url">The URL to the mod.</param> /// <param name="modName">The name for the mod.</param> /// <param name="install">Flag to determine if the mod should be installed after adding.</param> /// <param name="downloadProgressCallback">Callback function for download progress.</param> /// <returns>The root node of the added mod, or null.</returns> public ModNode HandleAdd(string url, string modName, bool install, DownloadProgressCallback downloadProgressCallback = null) { ISiteHandler curseForge = SiteHandlerManager.GetSiteHandlerByName("CurseForge"); ModNode modNode = curseForge.HandleAdd(GetDownloadURL(url), modName, install, downloadProgressCallback); ////modNode.VersionControllerName = Name; return modNode; }
/// <summary> /// Handles a mod add via URL. /// Validates the URL, gets ModInfos, downloads mod archive, adds it to the ModSelection and installs the mod if selected. /// </summary> /// <param name="url">The URL to the mod.</param> /// <param name="modName">The name for the mod.</param> /// <param name="install">Flag to determine if the mod should be installed after adding.</param> /// <param name="downloadProgressCallback">Callback function for download progress.</param> /// <returns>The root node of the added mod, or null.</returns> public ModNode HandleAdd(string url, string modName, bool install, DownloadProgressCallback downloadProgressCallback = null) { ISiteHandler curseForge = SiteHandlerManager.GetSiteHandlerByName("CurseForge"); ModNode modNode = curseForge.HandleAdd(GetDownloadURL(url), modName, install, downloadProgressCallback); ////modNode.VersionControllerName = Name; return(modNode); }
/// <summary> /// Downloads the mod. /// </summary> /// <param name="modInfo">The infos of the mod. Must have at least ModURL and LocalPath</param> /// <param name="downloadProgressCallback">Callback function for download progress.</param> /// <returns>True if the mod was downloaded.</returns> public bool DownloadMod(ref ModInfo modInfo, DownloadProgressCallback downloadProgressCallback = null) { if (modInfo == null) { return(false); } string downloadURL = GetDownloadURL(modInfo.ModURL); modInfo.LocalPath = Www.DownloadFile2(downloadURL, OptionsController.DownloadPath, downloadProgressCallback); return(!string.IsNullOrEmpty(modInfo.LocalPath) && File.Exists(modInfo.LocalPath)); }
/// <summary> /// Downloads the mod. /// </summary> /// <param name="modInfo">The infos of the mod. Must have at least ModURL and LocalPath</param> /// <param name="downloadProgressCallback">Callback function for download progress.</param> /// <returns>True if the mod was downloaded.</returns> public bool DownloadMod(ref ModInfo modInfo, DownloadProgressCallback downloadProgressCallback = null) { Messenger.AddError("No download support for KSP Forum mods, update check only!"); MessageBox.Show("No download support for KSP Forum mods, update check only!", Messages.MSG_TITLE_ATTENTION); return(false); ////if (modInfo == null) //// return false; ////string downloadUrl = GetDownloadUrl(modInfo); ////modInfo.LocalPath = Path.Combine(OptionsController.DownloadPath, GetDownloadName(downloadUrl)); ////Www.DownloadFile(downloadUrl, modInfo.LocalPath, downloadProgressHandler); ////return File.Exists(modInfo.LocalPath); }
/// <summary> /// Downloads the mod. /// </summary> /// <param name="modInfo">The infos of the mod. Must have at least ModURL and LocalPath</param> /// <param name="downloadProgressCallback">Callback function for download progress.</param> /// <returns>True if the mod was downloaded.</returns> public bool DownloadMod(ref ModInfo modInfo, DownloadProgressCallback downloadProgressCallback = null) { if (modInfo == null) { return(false); } string downloadUrl = GetDownloadPath(GetPathToDownloads(modInfo.ModURL)); modInfo.LocalPath = Path.Combine(OptionsController.DownloadPath, downloadUrl.Split("/").Last()); Www.DownloadFile(downloadUrl, modInfo.LocalPath, downloadProgressCallback); return(File.Exists(modInfo.LocalPath)); }
/// <summary> /// Handles a mod add via URL. /// Validates the URL, gets ModInfos, downloads mod archive, adds it to the ModSelection and installs the mod if selected. /// </summary> /// <param name="url">The URL to the mod.</param> /// <param name="modName">The name for the mod.</param> /// <param name="install">Flag to determine if the mod should be installed after adding.</param> /// <param name="downloadProgressCallback">Callback function for download progress.</param> /// <returns>The root node of the added mod, or null.</returns> public ModNode HandleAdd(string url, string modName, bool install, DownloadProgressCallback downloadProgressCallback = null) { ModInfo modInfo = GetModInfo(url); if (modInfo == null) return null; if (!string.IsNullOrEmpty(modName)) modInfo.Name = modName; ModNode newMod = null; if (DownloadMod(ref modInfo, downloadProgressCallback)) newMod = ModSelectionController.HandleModAddViaModInfo(modInfo, install); return newMod; }
/// <summary> /// Downloads the mod. /// </summary> /// <param name="modInfo">The infos of the mod. Must have at least ModURL and LocalPath</param> /// <param name="downloadProgressCallback">Callback function for download progress.</param> /// <returns>True if the mod was downloaded.</returns> public bool DownloadMod(ref ModInfo modInfo, DownloadProgressCallback downloadProgressCallback = null) { if (modInfo == null) { return(false); } string downloadUrl = GetDownloadURL(modInfo); ////string siteContent = www.Load(GetFilesURL(modInfo.ModURL)); ////string filename = GetFileName(siteContent); modInfo.LocalPath = Path.Combine(OptionsController.DownloadPath, GetDownloadName(modInfo)); Www.DownloadFile(downloadUrl, modInfo.LocalPath, downloadProgressCallback); return(File.Exists(modInfo.LocalPath)); }
/// <summary> /// Downloads the mod. /// </summary> /// <param name="modInfo">The infos of the mod. Must have at least ModURL and LocalPath</param> /// <param name="downloadProgressCallback">Callback function for download progress.</param> /// <returns>True if the mod was downloaded.</returns> public bool DownloadMod(ref ModInfo modInfo, DownloadProgressCallback downloadProgressCallback = null) { if (modInfo == null) { return(false); } HtmlWeb web = new HtmlWeb(); HtmlDocument htmlDoc = web.Load(modInfo.ModURL); htmlDoc.OptionFixNestedTags = true; // get filename from hover text HtmlNode fileNode = htmlDoc.DocumentNode.SelectSingleNode("//*[@id='content']/section[2]/div[4]/div[2]/ul/li[1]/div[2]/p/a"); HtmlNode fileNode2 = htmlDoc.DocumentNode.SelectSingleNode("//*[@id='content']/section[2]/div[4]/div[2]/ul/li/div[2]/p/a/span"); string downloadURL = GetDownloadURL(modInfo.ModURL); if (fileNode == null || (fileNode.InnerHtml.Contains("...") && fileNode2 == null)) { modInfo.LocalPath = Www.DownloadFile2(downloadURL, OptionsController.DownloadPath, downloadProgressCallback); return(!string.IsNullOrEmpty(modInfo.LocalPath) && File.Exists(modInfo.LocalPath)); } string filename = string.Empty; if (fileNode.InnerHtml.Contains("...")) { filename = fileNode2.Attributes["title"].Value; // Long filename was truncated } else { filename = fileNode.InnerHtml; } modInfo.LocalPath = Path.Combine(OptionsController.DownloadPath, filename); Www.DownloadFile(downloadURL, modInfo.LocalPath, downloadProgressCallback); return(File.Exists(modInfo.LocalPath)); }
/// <summary> /// Downloads the mod. /// </summary> /// <param name="modInfo">The infos of the mod. Must have at least ModURL and LocalPath</param> /// <param name="downloadProgressCallback">Callback function for download progress.</param> /// <returns>True if the mod was downloaded.</returns> public bool DownloadMod(ref ModInfo modInfo, DownloadProgressCallback downloadProgressCallback = null) { if (modInfo == null) { return(false); } var downloadInfos = GetDownloadInfo(modInfo); DownloadInfo selected = null; if (downloadInfos.Count > 1) { // create new selection form if more than one download option found var dlg = new frmSelectDownload(downloadInfos); if (dlg.ShowDialog() == DialogResult.OK) { selected = dlg.SelectedLink; } } else if (downloadInfos.Count == 1) { selected = downloadInfos.First(); } else { string msg = string.Format(Messages.MSG_NO_BINARY_DOWNLOAD_FOUND_AT_0, modInfo.SiteHandlerName); MessageBox.Show(msg, Messages.MSG_TITLE_ERROR); Messenger.AddDebug(msg); return(false); } if (selected != null) { string downloadUrl = selected.DownloadURL; modInfo.LocalPath = Path.Combine(OptionsController.DownloadPath, selected.Filename); Www.DownloadFile(downloadUrl, modInfo.LocalPath, downloadProgressCallback); } return(File.Exists(modInfo.LocalPath)); }
/// <summary> /// Downloads a file. /// </summary> /// <param name="downloadURL">Url to the file to download.</param> /// <param name="downloadPath">Path to save the file to.</param> public static void DownloadFile(string downloadURL, string downloadPath, DownloadProgressCallback downloadProgressCallback = null) { using (WebClient webClient = new WebClient()) { webClient.Credentials = CredentialCache.DefaultCredentials; webClient.DownloadProgressChanged += (sender, args) => { if (downloadProgressCallback != null) { downloadProgressCallback(args.BytesReceived, args.TotalBytesToReceive); } }; bool wait = true; webClient.DownloadFileCompleted += (sender, args) => { wait = false; }; // User DownloadFileAsync cause DownloadFile doesn't fire the DownloadProgressChanged event. webClient.DownloadFileAsync(new Uri(downloadURL), downloadPath); while (wait) /* Wait till download is finished. */ } { } }
/// <summary> /// Downloads a file. /// </summary> /// <param name="downloadURL">Url to the file to download.</param> /// <param name="downloadPath">Path to save the file to.</param> public static void DownloadFile(string downloadURL, string downloadPath, DownloadProgressCallback downloadProgressCallback = null) { using (WebClient webClient = new WebClient()) { webClient.Credentials = CredentialCache.DefaultCredentials; webClient.DownloadProgressChanged += (sender, args) => { if (downloadProgressCallback != null) downloadProgressCallback(args.BytesReceived, args.TotalBytesToReceive); }; bool wait = true; webClient.DownloadFileCompleted += (sender, args) => { wait = false; }; // User DownloadFileAsync cause DownloadFile doesn't fire the DownloadProgressChanged event. webClient.DownloadFileAsync(new Uri(downloadURL), downloadPath); while (wait) { // Wait till download is finished. } } }
public ProgressReporter(DownloadProgressCallback inCallback, double inTotalFileBytes) { callback = inCallback; totalFileBytes = inTotalFileBytes; }
/// <summary> /// Downloads the mod. /// </summary> /// <param name="modInfo">The infos of the mod. Must have at least ModURL and LocalPath</param> /// <param name="downloadProgressCallback">Callback function for download progress.</param> /// <returns>True if the mod was downloaded.</returns> public bool DownloadMod(ref ModInfo modInfo, DownloadProgressCallback downloadProgressCallback = null) { ISiteHandler curseForge = SiteHandlerManager.GetSiteHandlerByName("CurseForge"); return curseForge.DownloadMod(ref modInfo, downloadProgressCallback); }
/// <summary> /// Downloads the mod. /// </summary> /// <param name="modInfo">The infos of the mod. Must have at least ModURL and LocalPath</param> /// <param name="downloadProgressCallback">Callback function for download progress.</param> /// <returns>True if the mod was downloaded.</returns> public bool DownloadMod(ref ModInfo modInfo, DownloadProgressCallback downloadProgressCallback = null) { Messenger.AddError("No download support for KSP Forum mods, update check only!"); MessageBox.Show("No download support for KSP Forum mods, update check only!", Messages.MSG_TITLE_ATTENTION); return false; ////if (modInfo == null) //// return false; ////string downloadUrl = GetDownloadUrl(modInfo); ////modInfo.LocalPath = Path.Combine(OptionsController.DownloadPath, GetDownloadName(downloadUrl)); ////Www.DownloadFile(downloadUrl, modInfo.LocalPath, downloadProgressHandler); ////return File.Exists(modInfo.LocalPath); }
/// <summary> /// Downloads the mod. /// </summary> /// <param name="modInfo">The infos of the mod. Must have at least ModURL and LocalPath</param> /// <param name="downloadProgressCallback">Callback function for download progress.</param> /// <returns>True if the mod was downloaded.</returns> public bool DownloadMod(ref ModInfo modInfo, DownloadProgressCallback downloadProgressCallback = null) { if (modInfo == null) return false; var downloadInfos = GetDownloadInfo(modInfo); DownloadInfo selected = null; // If any of the nodes came back as a prerelease, notify the user that there are pre-release nodes foreach (var d in downloadInfos) { if (!d.Name.Contains("Pre-release")) continue; var dlg = MessageBox.Show("This download contains a pre-release version. This version might not be stable.", Messages.MSG_TITLE_ATTENTION, MessageBoxButtons.OK); break; } if (downloadInfos.Count > 1) { // create new selection form if more than one download option found var dlg = new frmSelectDownload(downloadInfos); if (dlg.ShowDialog() == DialogResult.OK) { selected = dlg.SelectedLink; } } else if (downloadInfos.Count == 1) { selected = downloadInfos.First(); } else { string msg = string.Format(Messages.MSG_NO_BINARY_DOWNLOAD_FOUND_AT_0, modInfo.SiteHandlerName); MessageBox.Show(msg, Messages.MSG_TITLE_ERROR); Messenger.AddDebug(msg); return false; } if (selected != null) { string downloadUrl = selected.DownloadURL; modInfo.LocalPath = Path.Combine(OptionsController.DownloadPath, selected.Filename); Www.DownloadFile(downloadUrl, modInfo.LocalPath, downloadProgressCallback); } return File.Exists(modInfo.LocalPath); }
/// <summary> /// Downloads the mod. /// </summary> /// <param name="modInfo">The infos of the mod. Must have at least ModURL and LocalPath</param> /// <param name="downloadProgressCallback">Callback function for download progress.</param> /// <returns>True if the mod was downloaded.</returns> public bool DownloadMod(ref ModInfo modInfo, DownloadProgressCallback downloadProgressCallback = null) { if (modInfo == null) return false; string downloadUrl = GetDownloadPath(GetPathToDownloads(modInfo.ModURL)); modInfo.LocalPath = Path.Combine(OptionsController.DownloadPath, downloadUrl.Split("/").Last()); Www.DownloadFile(downloadUrl, modInfo.LocalPath, downloadProgressCallback); return File.Exists(modInfo.LocalPath); }
/// <summary> /// Downloads the mod. /// </summary> /// <param name="modInfo">The infos of the mod. Must have at least ModURL and LocalPath</param> /// <param name="downloadProgressCallback">Callback function for download progress.</param> /// <returns>True if the mod was downloaded.</returns> public bool DownloadMod(ref ModInfo modInfo, DownloadProgressCallback downloadProgressCallback = null) { ISiteHandler curseForge = SiteHandlerManager.GetSiteHandlerByName("CurseForge"); return(curseForge.DownloadMod(ref modInfo, downloadProgressCallback)); }
/// <summary> /// Downloads the mod. /// </summary> /// <param name="modInfo">The infos of the mod. Must have at least ModURL and LocalPath</param> /// <param name="downloadProgressCallback">Callback function for download progress.</param> /// <returns>True if the mod was downloaded.</returns> public bool DownloadMod(ref ModInfo modInfo, DownloadProgressCallback downloadProgressCallback = null) { if (modInfo == null) return false; string downloadUrl = GetDownloadURL(modInfo); ////string siteContent = www.Load(GetFilesURL(modInfo.ModURL)); ////string filename = GetFileName(siteContent); modInfo.LocalPath = Path.Combine(OptionsController.DownloadPath, GetDownloadName(modInfo)); Www.DownloadFile(downloadUrl, modInfo.LocalPath, downloadProgressCallback); return File.Exists(modInfo.LocalPath); }
/// <summary> /// Handles a mod add via URL. /// Validates the URL, gets ModInfos, downloads mod archive, adds it to the ModSelection and installs the mod if selected. /// </summary> /// <param name="url">The URL to the mod.</param> /// <param name="modName">The name for the mod.</param> /// <param name="install">Flag to determine if the mod should be installed after adding.</param> /// <param name="downloadProgressCallback">Callback function for download progress.</param> /// <returns>The root node of the added mod, or null.</returns> public ModNode HandleAdd(string url, string modName, bool install, DownloadProgressCallback downloadProgressCallback = null) { Messenger.AddError(KERBALSTUFF_URL_ERROR); return(null); }
public IAsyncResult BeginDownload(DownloadProgressCallback downloadProgressCallback, UnzipProgressCallback unzipProgressCallback, AsyncCallback callback, object state) { _downloadDelegate = Download; return(_downloadDelegate.BeginInvoke(downloadProgressCallback, unzipProgressCallback, callback, state)); }
/// <summary> /// Downloads a file. /// Filename will be taken from WebResponse.ResponseUri.AbsolutePath /// </summary> /// <param name="downloadURL">Url to the file to download.</param> /// <param name="downloadPath">Path to save the file to without filename!</param> /// <param name="downloadProgressCallback">Callback function which will receive download progress information.</param> /// <returns>The full path to the downloaded file (path and filename).</returns> public static string DownloadFile2(string downloadURL, string downloadPath, DownloadProgressCallback downloadProgressCallback = null) { string fullpath = string.Empty; using (WebClient wcDownload = new WebClient()) { Stream strResponse = null; Stream strLocal = null; try { // Create a request to the file we are downloading HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(downloadURL); // Set default authentication for retrieving the file webRequest.Credentials = CredentialCache.DefaultCredentials; // Retrieve the response from the server HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse(); // Ask the server for the file size and store it long fileSize = webResponse.ContentLength; string filename = Path.GetFileName(webResponse.ResponseUri.AbsolutePath); fullpath = Path.Combine(downloadPath, filename); fullpath = GetNewFilenameWhenDestinationExists(fullpath); // Open the URL for download strResponse = wcDownload.OpenRead(downloadURL); // Create a new file stream where we will be saving the data (local drive) strLocal = new FileStream(fullpath, FileMode.Create, FileAccess.Write, FileShare.None); // It will store the current number of bytes we retrieved from the server int bytesSize = 0; // A buffer for storing and writing the data retrieved from the server byte[] downBuffer = new byte[2048]; // Loop through the buffer until the buffer is empty while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0) { // Write the data from the buffer to the local hard drive strLocal.Write(downBuffer, 0, bytesSize); // Invoke the method that propagates the progress. if (downloadProgressCallback != null) downloadProgressCallback(strLocal.Length, fileSize); } } catch (Exception ex) { Messenger.AddError(string.Format("Error while downloading \"{0}\"!", downloadURL), ex); fullpath = string.Empty; } finally { // When the above code has ended, close the streams strResponse.Close(); strLocal.Close(); } return fullpath; } }
public static extern void KSetDownloadProgressCallback(IntPtr Handel, uint userParam, DownloadProgressCallback Download_Progress_Callback);
public static void DownloadFile(long videoId, string path, bool overwrite = false, DownloadProgressCallback progressCallback = null) { if (File.Exists(path) && !overwrite) { throw new Exception("Output file already exists."); } string baseUrl = $"{"https"}://api.twitch.tv/v5/videos/{videoId}/comments"; string nextCursor = null; int segmentCount = 0; JObject firstComment = null; JObject lastComment = null; using (var writer = new JsonTextWriter(new StreamWriter(path, false, new UTF8Encoding(true)))) { writer.WriteStartArray(); do { string url = nextCursor == null ? $"{baseUrl}?content_offset_seconds=0" : $"{baseUrl}?cursor={nextCursor}"; JObject response = JObject.Parse(DownloadUrlAsString(url, withRequest: AddTwitchApiHeaders)); foreach (JObject comment in (JArray)response["comments"]) { comment.WriteTo(writer); firstComment = firstComment ?? comment; lastComment = comment; } nextCursor = (string)response["_next"]; segmentCount++; progressCallback?.Invoke(segmentCount, TryGetContentOffset(lastComment)); }while (nextCursor != null); writer.WriteEndArray(); } if (firstComment != null) { try { var firstMessage = new RechatMessage(firstComment); var lastMessage = new RechatMessage(lastComment); File.SetCreationTimeUtc(path, firstMessage.CreatedAt - firstMessage.ContentOffset); File.SetLastWriteTimeUtc(path, lastMessage.CreatedAt); } catch (Exception ex) { throw new WarningException("Unable to set file created/modified time.", ex); } } }
/// <summary> /// Downloads the mod. /// </summary> /// <param name="modInfo">The infos of the mod. Must have at least ModURL and LocalPath</param> /// <param name="downloadProgressCallback">Callback function for download progress.</param> /// <returns>True if the mod was downloaded.</returns> public bool DownloadMod(ref ModInfo modInfo, DownloadProgressCallback downloadProgressCallback = null) { if (modInfo == null) return false; HtmlWeb web = new HtmlWeb(); HtmlDocument htmlDoc = web.Load(modInfo.ModURL); htmlDoc.OptionFixNestedTags = true; // get filename from hover text HtmlNode fileNode = htmlDoc.DocumentNode.SelectSingleNode("//*[@id='content']/section[2]/div[4]/div[2]/ul/li[1]/div[2]/p/a"); HtmlNode fileNode2 = htmlDoc.DocumentNode.SelectSingleNode("//*[@id='content']/section[2]/div[4]/div[2]/ul/li/div[2]/p/a/span"); string downloadURL = GetDownloadURL(modInfo.ModURL); if (fileNode == null || (fileNode.InnerHtml.Contains("...") && fileNode2 == null)) { modInfo.LocalPath = Www.DownloadFile2(downloadURL, OptionsController.DownloadPath, downloadProgressCallback); return !string.IsNullOrEmpty(modInfo.LocalPath) && File.Exists(modInfo.LocalPath); } string filename = string.Empty; if (fileNode.InnerHtml.Contains("...")) filename = fileNode2.Attributes["title"].Value; // Long filename was truncated else filename = fileNode.InnerHtml; modInfo.LocalPath = Path.Combine(OptionsController.DownloadPath, filename); Www.DownloadFile(downloadURL, modInfo.LocalPath, downloadProgressCallback); return File.Exists(modInfo.LocalPath); }
/// <summary> /// Downloads the mod. /// </summary> /// <param name="modInfo">The infos of the mod. Must have at least ModURL and LocalPath</param> /// <param name="downloadProgressCallback">Callback function for download progress.</param> /// <returns>True if the mod was downloaded.</returns> public bool DownloadMod(ref ModInfo modInfo, DownloadProgressCallback downloadProgressCallback = null) { Messenger.AddError(KERBALSTUFF_URL_ERROR); return(false); }