/NUS Downloader/Form1.cs
C# | 3007 lines | 2072 code | 367 blank | 568 comment | 433 complexity | e917d474723625a2d213fe396b64c154 MD5 | raw file
Possible License(s): GPL-3.0
Large files files are truncated, but you can click here to view the full file
- ///////////////////////////////////////////
- // NUS Downloader: Form1.cs //
- // $Rev:: $ //
- // $Author:: $ //
- // $Date:: $ //
- ///////////////////////////////////////////
-
- ///////////////////////////////////////
- // Copyright (C) 2010
- //
- // This program is free software: you can redistribute it and/or modify
- // it under the terms of the GNU General Public License as published by
- // the Free Software Foundation, either version 3 of the License, or
- // (at your option) any later version.
- //
- // This program is distributed in the hope that it will be useful,
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- // GNU General Public License for more details.
- //
- // You should have received a copy of the GNU General Public License
- // along with this program. If not, see <http://www.gnu.org/licenses/>
- ///////////////////////////////////////
-
-
- using System;
- using System.Windows.Forms;
- using System.IO;
- using System.Net;
- using System.Security.Cryptography;
- using System.Xml;
- using System.Drawing;
- using System.Text.RegularExpressions;
- using System.ComponentModel;
- using System.Threading;
- using System.Text;
- using System.Diagnostics;
-
- namespace NUS_Downloader
- {
- partial class Form1 : Form
- {
- private readonly string CURRENT_DIR = Directory.GetCurrentDirectory();
-
- #if DEBUG
- private static string svnversion = "$Rev$";
- private static string version = String.Format("SVN r{0}", ((int.Parse(svnversion.Replace("$"+"R"+"e"+"v"+": ","").Replace(" "+"$","")))+1));
- #else
- // TODO: Always remember to change version!
- private string version = "v1.9";
- #endif
-
- // Cross-thread Windows Formsing
- private delegate void AddToolStripItemToStripCallback(
- ToolStripMenuItem menulist, ToolStripMenuItem[] additionitems);
- private delegate void WriteStatusCallback(string Update, Color writecolor);
- private delegate void BootChecksCallback();
- private delegate void SetEnableForDownloadCallback(bool enabled);
- private delegate void SetPropertyThreadSafeCallback(System.ComponentModel.Component what, object setto, string property);
- private delegate string OfficialWADNamingCallback(string whut);
-
- private string WAD_Saveas_Filename;
-
- // TODO: OOP scripting
- /*private string script_filename;
- private bool script_mode = false;
- private string[] nusentries;*/
-
- // Proxy stuff...
- private string proxy_url;
- private string proxy_usr;
- private string proxy_pwd;
-
- // Database threads
- private BackgroundWorker databaseWorker;
- private BackgroundWorker dsiDatabaseWorker;
-
- // Scripts Thread
- private BackgroundWorker scriptsWorker;
-
- // Colours for status box
- private System.Drawing.Color normalcolor = Color.FromName("Black");
- private System.Drawing.Color warningcolor = Color.FromName("DarkGoldenrod");
- private System.Drawing.Color errorcolor = Color.FromName("Crimson");
- private System.Drawing.Color infocolor = Color.FromName("RoyalBlue");
-
- // This is the standard entry to the GUI
- public Form1()
- {
- InitializeComponent();
-
- GUISetup();
-
- BootChecks();
- }
-
- // CLI Mode
- public Form1(string[] args)
- {
- InitializeComponent();
- Debug.WriteLine("CLI Parameters passed");
-
- GUISetup();
-
- if ((args.Length == 1) && (File.Exists(args[0])))
- {
- BootChecks();
-
- string script_content = File.ReadAllText(args[0]);
- FileInfo script_file = new FileInfo(args[0]);
- script_content += String.Format(";{0}", script_file.Name.Replace("." + script_file.Extension, ""));
-
- BackgroundWorker scripter = new BackgroundWorker();
- scripter.DoWork += new DoWorkEventHandler(RunScriptBg);
- scripter.RunWorkerAsync(script_content);
- }
- else if (args.Length >= 2)
- {
- RunCommandMode(args);
- Environment.Exit(0);
- //this.Close();
- }
- else
- {
- BootChecks();
- }
- }
-
- private void RunCommandMode(string[] args)
- {
- // CLI mode, inspired and taken from wiiNinja's mod.
-
- // Initialize the checkboxes and radio boxes
- packbox.Checked = false; // Create wad - default OFF
- localuse.Checked = true; // Use local content if already downloaded - default ON
- decryptbox.Checked = false;
- keepenccontents.Checked = false;
- //consoleCBox.SelectedIndex = 0; // 0 is Wii, 1 is DS
-
- // Clear 3 items in ios patches list. This feature is not supported in the command line version at this time.
- iosPatchCheckbox.Checked = false;
- iosPatchesListBox.SetItemChecked(0, false);
- iosPatchesListBox.SetItemChecked(1, false);
- iosPatchesListBox.SetItemChecked(2, false);
-
- Console.WriteLine("NUS Downloader - v{0}", version);
-
- if (args.Length < 2)
- {
- Console.WriteLine("Usage:");
- Console.WriteLine(" nusd <titleID> <titleVersion | *> [optionalArgs]");
- Console.WriteLine("\nWhere:");
- Console.WriteLine(" titleID = The ID of the title to be downloaded");
- Console.WriteLine(" titleVersion = The version of the title to be downloaded");
- Console.WriteLine(" Use \"*\" (no quotes) to get the latest version");
- Console.WriteLine(" OptionalArgs:");
- Console.WriteLine(" packwad = A wad file will be generated");
- Console.WriteLine(" localuse = Use local contents if available");
- Console.WriteLine(" decrypt = Create decrypted contents");
- Console.WriteLine(" keepencrypt = Keep encrypted contents");
- }
- else
- {
- for (int i = 0; i < args.Length; i++)
- {
- Console.WriteLine("{0}", args[i]);
- switch (i)
- {
- case 0:
- // First command line argument is ALWAYS the TitleID
- titleidbox.Text = args[i];
- break;
-
- case 1:
- // Second command line argument is ALWAYS the TitleVersion.
- // User may specify a "*" to retrieve the latest version
- if (args[i] == "*")
- titleversion.Text = "";
- else
- titleversion.Text = args[i];
- break;
-
- default:
- // Any other arguments beyond the 2nd one are considered optional
- if (args[i] == "packwad")
- packbox.Checked = true;
- else if (args[i] == "localuse")
- localuse.Checked = true;
- else if (args[i] == "decrypt")
- decryptbox.Checked = true;
- else if (args[i] == "keepencrypt")
- keepenccontents.Checked = true;
- else
- Console.WriteLine("\n>>>> Warning: Unrecognized command line argument: {0}. This option is ignored...", args[i]);
- break;
- }
- }
-
- // Do this to set the wad file name
- UpdatePackedName();
-
- // Call to get the files from server
- NUSDownloader_DoWork(null, null);
-
- Console.WriteLine("\nSuccessfully downloaded the title {0} version {1}", args[0], args[1]);
- }
- }
-
- private void GUISetup()
- {
- this.Font = new System.Drawing.Font("Tahoma", 8);
- this.MaximumSize = this.MinimumSize = this.Size; // Lock size down PATCHOW :D
- if (Type.GetType("Mono.Runtime") != null)
- {
- saveaswadbtn.Text = "Save As";
- clearButton.Text = "Clear";
- keepenccontents.Text = "Keep Enc. Contents";
- clearButton.Left -= 41;
- }
- else
- statusbox.Font = new System.Drawing.Font("Microsoft Sans Serif", 7);
- statusbox.SelectionColor = statusbox.ForeColor = normalcolor;
- if (version.StartsWith("SVN"))
- {
- WriteStatus("!!!!! THIS IS A DEBUG BUILD FROM SVN !!!!!");
- WriteStatus("Features CAN and WILL be broken in this build!");
- WriteStatus("Devs: REMEMBER TO CHANGE TO THE RELEASE CONFIGURATION AND CHANGE VERSION NUMBER BEFORE BUILDING!");
- WriteStatus("\r\n");
- }
-
- // Database BackgroundWorker
- this.databaseWorker = new BackgroundWorker();
- this.databaseWorker.DoWork += new DoWorkEventHandler(DoAllDatabaseyStuff);
- this.databaseWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(DoAllDatabaseyStuff_Completed);
- this.databaseWorker.ProgressChanged += new ProgressChangedEventHandler(DoAllDatabaseyStuff_ProgressChanged);
- this.databaseWorker.WorkerReportsProgress = true;
-
- // DSi Database BackgroundWorker
- this.dsiDatabaseWorker = new BackgroundWorker();
- this.dsiDatabaseWorker.DoWork += new DoWorkEventHandler(DSiDatabaseWork);
- this.dsiDatabaseWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(DSiDatabaseWork_Completed);
- this.dsiDatabaseWorker.ProgressChanged += new ProgressChangedEventHandler(DSiDatabaseWork_ProgressChanged);
- this.dsiDatabaseWorker.WorkerReportsProgress = true;
-
- // Scripts BGLoader
- this.scriptsWorker = new BackgroundWorker();
- this.scriptsWorker.DoWork += new DoWorkEventHandler(OrganizeScripts);
- this.scriptsWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(scriptsWorker_RunWorkerCompleted);
- }
-
- private void Form1_Load(object sender, EventArgs e)
- {
- this.Text = String.Format("NUSD - {0}", version); ;
- this.Size = this.MinimumSize;
- serverLbl.Text = "Wii";
- }
-
- private bool NUSDFileExists(string filename)
- {
- return File.Exists(Path.Combine(CURRENT_DIR, filename));
- }
-
- /// <summary>
- /// Checks certain file existances, etc.
- /// </summary>
- /// <returns></returns>
- private void BootChecks()
- {
- //Check if correct thread...
- if (this.InvokeRequired)
- {
- Debug.WriteLine("InvokeRequired...");
- BootChecksCallback bcc = new BootChecksCallback(BootChecks);
- this.Invoke(bcc);
- return;
- }
-
- /* Check for DSi common key bin file...
- if (NUSDFileExists("dsikey.bin") == true)
- {
- WriteStatus("DSi Common Key detected.");
- dsidecrypt = true;
- }*/
- /*
- // Check for database.xml
- if (NUSDFileExists("database.xml") == false)
- {
- WriteStatus("Database.xml not found. Title database not usable!");
- DatabaseEnabled(false);
- updateDatabaseToolStripMenuItem.Enabled = true;
- updateDatabaseToolStripMenuItem.Visible = true;
- updateDatabaseToolStripMenuItem.Text = "Download Database";
- }
- else
- {
- Database db = new Database();
- db.LoadDatabaseToStream(Path.Combine(CURRENT_DIR, "database.xml"));
- string version = db.GetDatabaseVersion();
- WriteStatus("Database.xml detected.");
- WriteStatus(" - Version: " + version);
- updateDatabaseToolStripMenuItem.Text = "Update Database";
- //databaseButton.Enabled = false;
- //databaseButton.Text = "DB Loading";
- databaseButton.Text = " [ ]";
- databaseButton.Image = Properties.Resources.arrow_ticker;
- // Load it up...
- this.fds.RunWorkerAsync();
- }
-
- // Check for database.xml
- if (NUSDFileExists("dsidatabase.xml") == false)
- {
- WriteStatus("DSiDatabase.xml not found. DSi database not usable!");
- DatabaseEnabled(false);
- updateDatabaseToolStripMenuItem.Enabled = true;
- updateDatabaseToolStripMenuItem.Visible = true;
- updateDatabaseToolStripMenuItem.Text = "Download Database";
- }
- else
- {
- Database db = new Database();
- db.LoadDatabaseToStream(Path.Combine(CURRENT_DIR, "database.xml"));
- string version = db.GetDatabaseVersion();
- WriteStatus("Database.xml detected.");
- WriteStatus(" - Version: " + version);
- updateDatabaseToolStripMenuItem.Text = "Update Database";
- //databaseButton.Enabled = false;
- //databaseButton.Text = "DB Loading";
- databaseButton.Text = " [ ]";
- databaseButton.Image = Properties.Resources.arrow_ticker;
- // Load it up...
- this.fds.RunWorkerAsync();
- }*/
-
- if (NUSDFileExists("database.xml") == true)
- {
- Database db = new Database();
- db.LoadDatabaseToStream(Path.Combine(CURRENT_DIR, "database.xml"));
- string version = db.GetDatabaseVersion();
- WriteStatus("Database.xml detected.");
- WriteStatus(" - Version: " + version);
- updateDatabaseToolStripMenuItem.Text = "Update Database";
- databaseButton.Text = " [ ]";
- databaseButton.Image = Properties.Resources.arrow_ticker;
- // Load it up...
- this.databaseWorker.RunWorkerAsync();
- }
-
- if (NUSDFileExists("dsidatabase.xml") == true)
- {
- Database db = new Database();
- db.LoadDatabaseToStream(Path.Combine(CURRENT_DIR, "dsidatabase.xml"));
- string version = db.GetDatabaseVersion();
- WriteStatus("DSiDatabase.xml detected.");
- WriteStatus(" - Version: " + version);
- updateDatabaseToolStripMenuItem.Text = "Update Database";
- databaseButton.Text = " [ ]";
- databaseButton.Image = Properties.Resources.arrow_ticker;
- // Load it up...
- this.dsiDatabaseWorker.RunWorkerAsync();
- }
-
- // Load scripts (local)
- RunScriptOrganizer();
-
- // Check for Proxy Settings file...
- if (NUSDFileExists("proxy.txt") == true)
- {
- WriteStatus("Proxy settings detected.");
- string[] proxy_file = File.ReadAllLines(Path.Combine(CURRENT_DIR, "proxy.txt"));
- proxy_url = proxy_file[0];
-
- // If proxy\nuser\npassword
- if (proxy_file.Length > 2)
- {
- proxy_usr = proxy_file[1];
- proxy_pwd = proxy_file[2];
- }
- else if (proxy_file.Length > 1)
- {
- proxy_usr = proxy_file[1];
- SetAllEnabled(false);
- ProxyVerifyBox.Visible = true;
- ProxyVerifyBox.Enabled = true;
- ProxyPwdBox.Enabled = true;
- SaveProxyBtn.Enabled = true;
- ProxyVerifyBox.Select();
- }
- }
- }
-
- private void DoAllDatabaseyStuff(object sender, System.ComponentModel.DoWorkEventArgs e)
- {
- BackgroundWorker worker = sender as BackgroundWorker;
- ClearDatabaseStrip();
- FillDatabaseStrip(worker);
- LoadRegionCodes();
- FillDatabaseScripts();
- ShowInnerToolTips(false);
- }
-
- private void DoAllDatabaseyStuff_Completed(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
- {
- //this.databaseButton.Enabled = true;
- this.databaseButton.Text = "Database...";
- this.databaseButton.Image = null;
- /*
- if (this.KoreaMassUpdate.HasDropDownItems || this.PALMassUpdate.HasDropDownItems || this.NTSCMassUpdate.HasDropDownItems)
- {
- this.scriptsbutton.Enabled = true;
- }*/
- }
-
- private void DoAllDatabaseyStuff_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
- {
- if (e.ProgressPercentage == 25)
- databaseButton.Text = " [. ]";
- else if (e.ProgressPercentage == 50)
- databaseButton.Text = " [.. ]";
- else if (e.ProgressPercentage == 75)
- databaseButton.Text = " [... ]";
- else if (e.ProgressPercentage == 100)
- databaseButton.Text = " [....]";
- }
-
- private void RunScriptOrganizer()
- {
- this.scriptsWorker.RunWorkerAsync();
- }
-
- private void SetAllEnabled(bool enabled)
- {
- for (int a = 0; a < this.Controls.Count; a++)
- {
- try
- {
- this.Controls[a].Enabled = enabled;
- }
- catch
- {
- // ...
- }
- }
- }
-
- /*
- /// <summary>
- /// Gets the database version.
- /// </summary>
- /// <param name="file">The database file.</param>
- /// <returns></returns>
- private string GetDatabaseVersion(string file)
- {
- // Read version of Database.xml
- XmlDocument xDoc = new XmlDocument();
- if (file.Contains("<"))
- xDoc.LoadXml(file);
- else
- {
- if (File.Exists(file))
- {
- xDoc.Load(file);
- }
- else
- {
- return "None Found";
- }
- }
- XmlNodeList DatabaseList = xDoc.GetElementsByTagName("database");
- XmlAttributeCollection Attributes = DatabaseList[0].Attributes;
- return Attributes[0].Value;
- }*/
-
- private void extrasMenuButton_Click(object sender, EventArgs e)
- {
- // Show extras menu
- extrasStrip.Text = "Showing";
- extrasStrip.Show(Extrasbtn, 2, (2+Extrasbtn.Height));
-
-
- {
- System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
- timer.Interval = 52;
- timer.Tick += new EventHandler(contextmenusTimer_Tick);
- timer.Start();
- }
- }
-
- /// <summary>
- /// Loads the title info from TMD.
- /// </summary>
- private void LoadTitleFromTMD()
- {
- // Show dialog for opening TMD file...
- OpenFileDialog opentmd = new OpenFileDialog();
- opentmd.Filter = "TMD Files|*tmd*";
- opentmd.Title = "Open TMD";
- if (opentmd.ShowDialog() != DialogResult.Cancel)
- {
- libWiiSharp.TMD tmdLocal = new libWiiSharp.TMD();
- tmdLocal.LoadFile(opentmd.FileName);
- WriteStatus(String.Format("TMD Loaded ({0} blocks)", tmdLocal.GetNandBlocks()));
-
- titleidbox.Text = tmdLocal.TitleID.ToString("X16");
- WriteStatus("Title ID: " + tmdLocal.TitleID.ToString("X16"));
-
- titleversion.Text = tmdLocal.TitleVersion.ToString();
- WriteStatus("Version: " + tmdLocal.TitleVersion);
-
- if (tmdLocal.StartupIOS.ToString("X") != "0")
- WriteStatus("Requires: IOS" + int.Parse(tmdLocal.StartupIOS.ToString("X").Substring(7, 2).ToString(), System.Globalization.NumberStyles.HexNumber));
-
- WriteStatus("Content Count: " + tmdLocal.NumOfContents);
-
- for (int a = 0; a < tmdLocal.Contents.Length; a++)
- {
- WriteStatus(String.Format(" Content {0}: {1} ({2} bytes)", a, tmdLocal.Contents[a].ContentID.ToString("X8"), tmdLocal.Contents[a].Size.ToString()));
- WriteStatus(String.Format(" - Index: {0}", tmdLocal.Contents[a].Index.ToString()));
- WriteStatus(String.Format(" - Type: {0}", tmdLocal.Contents[a].Type.ToString()));
- WriteStatus(String.Format(" - Hash: {0}...", DisplayBytes(tmdLocal.Contents[a].Hash, String.Empty).Substring(0, 8)));
- }
-
- WriteStatus("TMD information parsed!");
- }
- }
-
- /// <summary>
- /// Writes the status to the statusbox.
- /// </summary>
- /// <param name="Update">The update.</param>
- /// <param name="writecolor">The color to use for writing text into the text box.</param>
- public void WriteStatus(string Update, Color writecolor)
- {
- // Check if thread-safe
- if (statusbox.InvokeRequired)
- {
- Debug.WriteLine("InvokeRequired...");
- WriteStatusCallback wsc = new WriteStatusCallback(WriteStatus);
- this.Invoke(wsc, new object[] { Update, writecolor });
- return;
- }
- // Small function for writing text to the statusbox...
- int startlen = statusbox.TextLength;
- if (statusbox.Text == "")
- statusbox.Text = Update;
- else
- statusbox.AppendText("\r\n" + Update);
- int endlen = statusbox.TextLength;
-
- // Set the color
- statusbox.Select(startlen, endlen - startlen);
- statusbox.SelectionColor = writecolor;
-
- // Scroll to end of text box.
- statusbox.SelectionStart = statusbox.TextLength;
- statusbox.SelectionLength = 0;
- statusbox.ScrollToCaret();
-
- // Also write to console
- Console.WriteLine(Update);
- }
-
- /// <summary>
- /// Writes the status to the statusbox.
- /// </summary>
- /// <param name="Update">The update.</param>
- public void WriteStatus(string Update)
- {
- WriteStatus(Update, normalcolor);
- }
-
- /// <summary>
- /// Reads the type of the Title ID.
- /// </summary>
- /// <param name="ttlid">The TitleID.</param>
- private void ReadIDType(string ttlid)
- {
- /* Wiibrew TitleID Info...
- # 3 00000001: Essential system titles
- # 4 00010000 and 00010004 : Disc-based games
- # 5 00010001: Downloaded channels
-
- * 5.1 000010001-Cxxx : Commodore 64 Games
- * 5.2 000010001-Exxx : NeoGeo Games
- * 5.3 000010001-Fxxx : NES Games
- * 5.4 000010001-Hxxx : Channels
- * 5.5 000010001-Jxxx : SNES Games
- * 5.6 000010001-Nxxx : Nintendo 64 Games
- * 5.7 000010001-Wxxx : WiiWare
-
- # 6 00010002: System channels
- # 7 00010004: Game channels and games that use them
- # 8 00010005: Downloaded Game Content
- # 9 00010008: "Hidden" channels
- */
-
- if (ttlid.Substring(0, 8) == "00000001")
- WriteStatus("ID Type: System Title. BE CAREFUL!", warningcolor);
- else if ((ttlid.Substring(0, 8) == "00010000") || (ttlid.Substring(0, 8) == "00010004"))
- WriteStatus("ID Type: Disc-Based Game. Unlikely NUS Content!");
- else if (ttlid.Substring(0, 8) == "00010001")
- WriteStatus("ID Type: Downloaded Channel. Possible NUS Content.");
- else if (ttlid.Substring(0, 8) == "00010002")
- WriteStatus("ID Type: System Channel. BE CAREFUL!", warningcolor);
- else if (ttlid.Substring(0, 8) == "00010004")
- WriteStatus("ID Type: Game Channel. Unlikely NUS Content!");
- else if (ttlid.Substring(0, 8) == "00010005")
- WriteStatus("ID Type: Downloaded Game Content. Unlikely NUS Content!");
- else if (ttlid.Substring(0, 8) == "00010008")
- WriteStatus("ID Type: 'Hidden' Channel. Unlikely NUS Content!");
- else
- WriteStatus("ID Type: Unknown. Unlikely NUS Content!");
- }
-
- private void DownloadBtn_Click(object sender, EventArgs e)
- {
- if (titleidbox.Text == String.Empty)
- {
- // Prevent mass deletion and fail
- WriteStatus("Please enter a Title ID!", errorcolor);
- return;
- }
- else if (!(packbox.Checked) && !(decryptbox.Checked) && !(keepenccontents.Checked))
- {
- // Prevent pointless running by n00bs.
- WriteStatus("Running with your current settings will produce no output!", errorcolor);
- WriteStatus(" - To amend this, look below and check an output type.", errorcolor);
- return;
- }/*
- else if (!(script_mode))
- {
- try
- {
- if (!statusbox.Lines[0].StartsWith(" ---"))
- SetTextThreadSafe(statusbox, " --- " + titleidbox.Text + " ---");
- }
- catch // No lines present...
- {
- SetTextThreadSafe(statusbox, " --- " + titleidbox.Text + " ---");
- }
- }
- else
- WriteStatus(" --- " + titleidbox.Text + " ---");*/
-
-
- // Running Downloads in background so no form freezing
- NUSDownloader.RunWorkerAsync();
- }
-
- private void SetTextThreadSafe(System.Windows.Forms.Control what, string setto)
- {
- SetPropertyThreadSafe(what, "Name", setto);
- }
-
- private void SetPropertyThreadSafe(System.ComponentModel.Component what, object setto, string property)
- {
- if (this.InvokeRequired)
- {
- SetPropertyThreadSafeCallback sptscb = new SetPropertyThreadSafeCallback(SetPropertyThreadSafe);
- try
- {
- this.Invoke(sptscb, new object[] { what, setto, property });
- }
- catch (Exception)
- {
- // FFFFF!
- }
- return;
- }
- what.GetType().GetProperty(property).SetValue(what, setto, null);
- //what.Text = setto;
- }
-
- private void NUSDownloader_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
- {
- Control.CheckForIllegalCrossThreadCalls = false; // this function would need major rewriting to get rid of this...
-
- WriteStatus("Starting NUS Download. Please be patient!", infocolor);
- SetEnableforDownload(false);
- downloadstartbtn.Text = "Starting NUS Download!";
-
- // WebClient configuration
- WebClient nusWC = new WebClient();
- nusWC = ConfigureWithProxy(nusWC);
-
- // Create\Configure NusClient
- libWiiSharp.NusClient nusClient = new libWiiSharp.NusClient();
- nusClient.ConfigureNusClient(nusWC);
- nusClient.UseLocalFiles = localuse.Checked;
- nusClient.ContinueWithoutTicket = true;
-
- // Server
- if (serverLbl.Text == "Wii")
- nusClient.SetToWiiServer();
- else if (serverLbl.Text == "DSi")
- nusClient.SetToDSiServer();
-
- // Events
- nusClient.Debug += new EventHandler<libWiiSharp.MessageEventArgs>(nusClient_Debug);
- nusClient.Progress += new EventHandler<ProgressChangedEventArgs>(nusClient_Progress);
-
- libWiiSharp.StoreType[] storeTypes = new libWiiSharp.StoreType[3];
- if (packbox.Checked) storeTypes[0] = libWiiSharp.StoreType.WAD; else storeTypes[0] = libWiiSharp.StoreType.Empty;
- if (decryptbox.Checked) storeTypes[1] = libWiiSharp.StoreType.DecryptedContent; else storeTypes[1] = libWiiSharp.StoreType.Empty;
- if (keepenccontents.Checked) storeTypes[2] = libWiiSharp.StoreType.EncryptedContent; else storeTypes[2] = libWiiSharp.StoreType.Empty;
-
- string wadName;
- if (String.IsNullOrEmpty(WAD_Saveas_Filename))
- wadName = wadnamebox.Text;
- else
- wadName = WAD_Saveas_Filename;
-
- try
- {
- nusClient.DownloadTitle(titleidbox.Text, titleversion.Text, Path.Combine(CURRENT_DIR, "titles"), wadName, storeTypes);
- }
- catch (Exception ex)
- {
- WriteStatus("Download failed: \"" + ex.Message + " ):\"", errorcolor);
- }
-
- if (iosPatchCheckbox.Checked == true) { // Apply patches then...
- bool didpatch = false;
- int noofpatches = 0;
- string appendpatch = "";
- // Okay, it's checked.
- libWiiSharp.IosPatcher iosp = new libWiiSharp.IosPatcher();
- libWiiSharp.WAD ioswad = new libWiiSharp.WAD();
- wadName = wadName.Replace("[v]", nusClient.TitleVersion.ToString());
- if (wadName.Contains(Path.DirectorySeparatorChar.ToString()) || wadName.Contains(Path.AltDirectorySeparatorChar.ToString()))
- ioswad.LoadFile(wadName);
- else
- ioswad.LoadFile(Path.Combine(Path.Combine(Path.Combine(Path.Combine(CURRENT_DIR, "titles"), titleidbox.Text), nusClient.TitleVersion.ToString()), wadName));
- try
- {
- iosp.LoadIOS(ref ioswad);
- }
- catch (Exception)
- {
- WriteStatus("NUS Download Finished.", infocolor);
- return;
- }
- foreach (object checkItem in iosPatchesListBox.CheckedItems)
- {
- // ensure not 'indeterminate'
- if (iosPatchesListBox.GetItemCheckState(iosPatchesListBox.Items.IndexOf(checkItem)).ToString() == "Checked") {
- switch (checkItem.ToString()) {
- case "Trucha bug":
- noofpatches = iosp.PatchFakeSigning();
- if (noofpatches > 0)
- {
- WriteStatus(" - Patched in fake-signing:", infocolor);
- if (noofpatches > 1)
- appendpatch = "es";
- else
- appendpatch = "";
- WriteStatus(String.Format(" {0} patch{1} applied.", noofpatches, appendpatch));
- didpatch = true;
- }
- else
- WriteStatus(" - Could not patch fake-signing", errorcolor);
- break;
- case "ES_Identify":
- noofpatches = iosp.PatchEsIdentify();
- if (noofpatches > 0)
- {
- WriteStatus(" - Patched in ES_Identify:", infocolor);
- if (noofpatches > 1)
- appendpatch = "es";
- else
- appendpatch = "";
- WriteStatus(String.Format(" {0} patch{1} applied.", noofpatches, appendpatch));
- didpatch = true;
- }
- else
- WriteStatus(" - Could not patch ES_Identify", errorcolor);
- break;
- case "NAND permissions":
- noofpatches = iosp.PatchNandPermissions();
- if (noofpatches > 0)
- {
- WriteStatus(" - Patched in NAND permissions:", infocolor);
- if (noofpatches > 1)
- appendpatch = "es";
- else
- appendpatch = "";
- WriteStatus(String.Format(" {0} patch{1} applied.", noofpatches, appendpatch));
- didpatch = true;
- }
- else
- WriteStatus(" - Could not patch NAND permissions", errorcolor);
- break;
- }
- }
- else {
- // WriteStatus(iosPatchesListBox.GetItemCheckState(iosPatchesListBox.Items.IndexOf(checkItem)).ToString());
- }
- }
- if (didpatch)
- {
- wadName = wadName.Replace(".wad",".patched.wad");
- try
- {
- if (wadName.Contains(Path.DirectorySeparatorChar.ToString()) || wadName.Contains(Path.AltDirectorySeparatorChar.ToString()))
- ioswad.Save(wadName);
- else
- ioswad.Save(Path.Combine(Path.Combine(Path.Combine(Path.Combine(CURRENT_DIR, "titles"), titleidbox.Text), nusClient.TitleVersion.ToString()), wadName));
- WriteStatus(String.Format("Patched WAD saved as: {0}", Path.GetFileName(wadName)), infocolor);
- }
- catch (Exception ex)
- {
- WriteStatus(String.Format("Couldn't save patched WAD: \"{0}\" :(",ex.Message), errorcolor);
- }
- }
- }
-
- WriteStatus("NUS Download Finished.");
-
- }
-
- void nusClient_Progress(object sender, ProgressChangedEventArgs e)
- {
- dlprogress.Value = e.ProgressPercentage;
- }
-
- void nusClient_Debug(object sender, libWiiSharp.MessageEventArgs e)
- {
- WriteStatus(e.Message);
- }
-
- private void NUSDownloader_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
- {
- WAD_Saveas_Filename = String.Empty;
-
- SetEnableforDownload(true);
- downloadstartbtn.Text = "Start NUS Download!";
- dlprogress.Value = 0;
-
- if (IsWin7())
- dlprogress.ShowInTaskbar = false;
- }
-
- private void packbox_CheckedChanged(object sender, EventArgs e)
- {
- if (packbox.Checked == true)
- {
- wadnamebox.Enabled = true;
- saveaswadbtn.Enabled = true;
- // Change WAD name if applicable
- UpdatePackedName();
- }
- else
- {
- wadnamebox.Enabled = false;
- saveaswadbtn.Enabled = false;
- wadnamebox.Text = String.Empty;
- if (iosPatchCheckbox.Checked)
- iosPatchCheckbox.Checked = false;
- }
- }
-
- private void titleidbox_TextChanged(object sender, EventArgs e)
- {
- UpdatePackedName();
- EnablePatchIOSBox();
- }
-
- private void titleversion_TextChanged(object sender, EventArgs e)
- {
- UpdatePackedName();
- }
-
- private void EnablePatchIOSBox()
- {
- iosPatchCheckbox.Enabled = TitleIsIOS(titleidbox.Text);
- if (iosPatchCheckbox.Enabled == false)
- iosPatchCheckbox.Checked = false;
- }
-
- private bool TitleIsIOS(string titleid)
- {
- if (titleid.Length != 16)
- return false;
-
- if ((titleid == "0000000100000001") || (titleid == "0000000100000002"))
- return false;
-
- if (titleid.Substring(0, 14) == "00000001000000")
- return true;
-
- return false;
- }
-
- /// <summary>
- /// Displays the bytes.
- /// </summary>
- /// <param name="bytes">The bytes.</param>
- /// <param name="spacer">What separates the bytes</param>
- /// <returns></returns>
- public string DisplayBytes(byte[] bytes, string spacer)
- {
- string output = "";
- for (int i = 0; i < bytes.Length; ++i)
- {
- output += bytes[i].ToString("X2") + spacer;
- }
- return output;
- }
-
- private void DatabaseButton_Click(object sender, EventArgs e)
- {
- // Open Database button menu...
- databaseStrip.Text = "Showing";
- databaseStrip.Show(databaseButton, 2, (2+databaseButton.Height));
-
- //if (!e.Equals(EventArgs.Empty))
- {
- System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
- timer.Interval = 50;
- timer.Tick += new EventHandler(contextmenusTimer_Tick);
- timer.Start();
- }
- }
-
- void contextmenusTimer_Tick(object sender, EventArgs e)
- {
- if (SystemMenuList.Pressed || IOSMenuList.Pressed || VCMenuList.Pressed || WiiWareMenuList.Pressed
- || RegionCodesList.Pressed || scriptsLocalMenuEntry.Pressed || scriptsDatabaseToolStripMenuItem.Pressed
- || emulateUpdate.Pressed)
- return;
-
- if (databaseButton.ClientRectangle.Contains(databaseButton.PointToClient(MousePosition)) && ((System.Windows.Forms.Timer)sender).Interval != 50)
- {
- databaseStrip.Close();
- scriptsStrip.Close();
- extrasStrip.Close();
- DatabaseButton_Click(sender, EventArgs.Empty);
- ((System.Windows.Forms.Timer)sender).Stop();
- }
-
- if (scriptsbutton.ClientRectangle.Contains(scriptsbutton.PointToClient(MousePosition)) && ((System.Windows.Forms.Timer)sender).Interval != 51)
- {
- databaseStrip.Close();
- scriptsStrip.Close();
- extrasStrip.Close();
- scriptsbutton_Click(sender, EventArgs.Empty);
- ((System.Windows.Forms.Timer)sender).Stop();
- }
-
- if (Extrasbtn.ClientRectangle.Contains(Extrasbtn.PointToClient(MousePosition)) && ((System.Windows.Forms.Timer)sender).Interval != 52)
- {
- databaseStrip.Close();
- scriptsStrip.Close();
- extrasStrip.Close();
- extrasMenuButton_Click(sender, EventArgs.Empty);
- ((System.Windows.Forms.Timer)sender).Stop();
- }
-
- //Debug.Write(((databaseStrip.Text == "Hidden").ToString() + (extrasStrip.Text == "Hidden").ToString() + (scriptsStrip.Text == "Hidden").ToString()));
-
-
- if ((databaseStrip.Visible == false) && (extrasStrip.Visible == false) && (scriptsStrip.Visible == false))
- ((System.Windows.Forms.Timer)sender).Stop();
-
-
- }
-
- /// <summary>
- /// Clears the database strip.
- /// </summary>
- private void ClearDatabaseStrip()
- {
- Control.CheckForIllegalCrossThreadCalls = false;
- object[] thingstoclear = new object[] {
- SystemMenuList, IOSMenuList, WiiWareMenuList, VCMenuList,
-
- // Now Virtual Console
- C64MenuList, NeoGeoMenuList, NESMenuList,
- SNESMenuList, N64MenuList, TurboGrafx16MenuList,
- TurboGrafxCDMenuList, MSXMenuList, SegaMSMenuList,
- GenesisMenuList, VCArcadeMenuList,
-
- // DSi Entries
- dsiSystemToolStripMenu, dSiWareToolStripMenu
- };
-
- foreach (System.Windows.Forms.ToolStripMenuItem tsmiclear in thingstoclear)
- {
- if (tsmiclear.Name != "VCMenuList") // Don't clear the VC Menu...
- tsmiclear.DropDownItems.Clear();
- /*
- if (tsmiclear.OwnerItem != VCMenuList) // and don't disable the VC menu subparts...
- tsmiclear.Enabled = false;*/
- }
- }
-
- /// <summary>
- /// Fills the database strip with the local database.xml file.
- /// </summary>
- private void FillDatabaseStrip(BackgroundWorker worker)
- {
- // Something needs to be done to remove this i guess
- //Control.CheckForIllegalCrossThreadCalls = false;
-
- // Set fake items visible and real ones not. Only way to stop buggy enabled stuff.
- SetPropertyThreadSafe(SystemMenuList, false, "Visible");
- SetPropertyThreadSafe(IOSMenuList, false, "Visible");
- SetPropertyThreadSafe(VCMenuList, false, "Visible");
- SetPropertyThreadSafe(WiiWareMenuList, false, "Visible");
-
- SetPropertyThreadSafe(systemFakeMenuItem, true, "Visible");
- SetPropertyThreadSafe(iosFakeMenuItem, true, "Visible");
- SetPropertyThreadSafe(vcFakeMenuItem, true, "Visible");
- SetPropertyThreadSafe(wwFakeMenuItem, true, "Visible");
-
- Database databaseObj = new Database();
- databaseObj.LoadDatabaseToStream(Path.Combine(CURRENT_DIR, "database.xml"));
-
- ToolStripMenuItem[] systemItems = databaseObj.LoadSystemTitles();
- for (int a = 0; a < systemItems.Length; a++)
- {
- systemItems[a].DropDownItemClicked += new ToolStripItemClickedEventHandler(DatabaseItem_Clicked);
- for (int b = 0; b < systemItems[a].DropDownItems.Count; b++)
- {
- ToolStripMenuItem syslowerentry = (ToolStripMenuItem)systemItems[a].DropDownItems[b];
- if (syslowerentry.DropDownItems.Count > 0)
- {
- syslowerentry.DropDownItemClicked += new ToolStripItemClickedEventHandler(DatabaseItem_Clicked);
- }
- }
- //AddToolStripItemToStrip(SystemMenuList, systemItems[a]);
- //SystemMenuList.DropDownItems.Add(systemItems[a]);
- }
- Array.Sort(systemItems, delegate(ToolStripMenuItem tsmi1, ToolStripMenuItem tsmi2)
- {
- return tsmi1.Text
- .Substring(18, tsmi1.Text.Length - 19).CompareTo(tsmi2.Text.Substring(18, tsmi2.Text.Length - 19));
- });
- AddToolStripItemToStrip(SystemMenuList, systemItems);
-
- SetPropertyThreadSafe(systemFakeMenuItem, false, "Visible");
- SetPropertyThreadSafe(SystemMenuList, true, "Visible");
-
- Debug.WriteLine("Database: SysTitles added");
- worker.ReportProgress(25);
-
- ToolStripMenuItem[] iosItems = databaseObj.LoadIosTitles();
- for (int a = 0; a < iosItems.Length; a++)
- {
- iosItems[a].DropDownItemClicked += new ToolStripItemClickedEventHandler(DatabaseItem_Clicked);
- //AddToolStripItemToStrip(IOSMenuList, iosItems[a]);
- //IOSMenuList.DropDownItems.Add(iosItems[a]);
- }
- AddToolStripItemToStrip(IOSMenuList, iosItems);
-
- SetPropertyThreadSafe(iosFakeMenuItem, false, "Visible");
- SetPropertyThreadSafe(IOSMenuList, true, "Visible");
- Debug.WriteLine("Database: IosTitles added");
- worker.ReportProgress(50);
-
- ToolStripMenuItem[][] vcItems = databaseObj.LoadVirtualConsoleTitles();
- for (int a = 0; a < vcItems.Length; a++)
- {
- for (int b = 0; b < vcItems[a].Length; b++)
- {
- vcItems[a][b].DropDownItemClicked += new ToolStripItemClickedEventHandler(DatabaseItem_Clicked);
- for (int c = 0; c < vcItems[a][b].DropDownItems.Count; c++)
- {
- ToolStripMenuItem lowerentry = (ToolStripMenuItem)vcItems[a][b].DropDownItems[c];
- lowerentry.DropDownItemClicked += new ToolStripItemClickedEventHandler(DatabaseItem_Clicked);
- }
- }
- Array.Sort(vcItems[a], delegate(ToolStripMenuItem tsmi1, ToolStripMenuItem tsmi2)
- {
- return tsmi1.Text
- .Substring(18, tsmi1.Text.Length - 19).CompareTo(tsmi2.Text.Substring(18, tsmi2.Text.Length - 19));
- });
- AddToolStripItemToStrip((ToolStripMenuItem)VCMenuList.DropDownItems[a], vcItems[a]);
- }
-
- SetPropertyThreadSafe(vcFakeMenuItem, false, "Visible");
- SetPropertyThreadSafe(VCMenuList, true, "Visible");
- Debug.WriteLine("Database: VCTitles added");
- worker.ReportProgress(75);
-
- ToolStripMenuItem[] wwItems = databaseObj.LoadWiiWareTitles();
- for (int a = 0; a < wwItems.Length; a++)
- {
- wwItems[a].DropDownItemClicked += new ToolStripItemClickedEventHandler(DatabaseItem_Clicked);
- for (int b = 0; b < wwItems[a].DropDownItems.Count; b++)
- {
- ToolStripMenuItem lowerentry = (ToolStripMenuItem)wwItems[a].DropDownItems[b];
- if (lowerentry.DropDownItems.Count > 0)
- {
- lowerentry.DropDownItemClicked += new ToolStripItemClickedEventHandler(DatabaseItem_Clicked);
- }
-
- }
- //AddToolStripItemToStrip(WiiWareMenuList, wwItems[a]);
- //WiiWareMenuList.DropDownItems.Add(wwItems[a]);
- }
- Array.Sort(wwItems, delegate(ToolStripMenuItem tsmi1, ToolStripMenuItem tsmi2)
- {
- return tsmi1.Text
- .Substring(18, tsmi1.Text.Length - 19).CompareTo(tsmi2.Text.Substring(18, tsmi2.Text.Length - 19));
- });
- AddToolStripItemToStrip(WiiWareMenuList, wwItems);
-
- SetPropertyThreadSafe(wwFakeMenuItem, false, "Visible");
- SetPropertyThreadSafe(WiiWareMenuList, true, "Visible");
- Debug.WriteLine("Database: WiiWareTitles added");
- worker.ReportProgress(100);
- }
-
- /// <summary>
- /// Fills the database strip with the local database.xml file.
- /// </summary>
- private void FillDSiDatabaseStrip(BackgroundWorker worker)
- {
- // Set fake items visible and real ones not. Only way to stop buggy enabled stuff.
- SetPropertyThreadSafe(dsiSystemToolStripMenu, false, "Visible");
- SetPropertyThreadSafe(dSiWareToolStripMenu, false, "Visible");
-
- SetPropertyThreadSafe(dsiFakeSystemToolStripMenu, true, "Visible");
- SetPropertyThreadSafe(dSiWareFakeToolStripMenu, true, "Visible");
-
- Database databaseObj = new Database();
- databaseObj.LoadDatabaseToStream(Path.Combine(CURRENT_DIR, "dsidatabase.xml"));
-
- ToolStripMenuItem[] systemItems = databaseObj.LoadDSiSystemTitles();
- for (int a = 0; a < systemItems.Length; a++)
- {
- systemItems[a].DropDownItemClicked += new ToolStripItemClickedEventHandler(DatabaseItem_Clicked);
- for (int b = 0; b < s…
Large files files are truncated, but you can click here to view the full file