PageRenderTime 67ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 1ms

/NUS Downloader/Form1.cs

https://github.com/edude03/nusformac
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

  1. ///////////////////////////////////////////
  2. // NUS Downloader: Form1.cs //
  3. // $Rev:: $ //
  4. // $Author:: $ //
  5. // $Date:: $ //
  6. ///////////////////////////////////////////
  7. ///////////////////////////////////////
  8. // Copyright (C) 2010
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>
  22. ///////////////////////////////////////
  23. using System;
  24. using System.Windows.Forms;
  25. using System.IO;
  26. using System.Net;
  27. using System.Security.Cryptography;
  28. using System.Xml;
  29. using System.Drawing;
  30. using System.Text.RegularExpressions;
  31. using System.ComponentModel;
  32. using System.Threading;
  33. using System.Text;
  34. using System.Diagnostics;
  35. namespace NUS_Downloader
  36. {
  37. partial class Form1 : Form
  38. {
  39. private readonly string CURRENT_DIR = Directory.GetCurrentDirectory();
  40. #if DEBUG
  41. private static string svnversion = "$Rev$";
  42. private static string version = String.Format("SVN r{0}", ((int.Parse(svnversion.Replace("$"+"R"+"e"+"v"+": ","").Replace(" "+"$","")))+1));
  43. #else
  44. // TODO: Always remember to change version!
  45. private string version = "v1.9";
  46. #endif
  47. // Cross-thread Windows Formsing
  48. private delegate void AddToolStripItemToStripCallback(
  49. ToolStripMenuItem menulist, ToolStripMenuItem[] additionitems);
  50. private delegate void WriteStatusCallback(string Update, Color writecolor);
  51. private delegate void BootChecksCallback();
  52. private delegate void SetEnableForDownloadCallback(bool enabled);
  53. private delegate void SetPropertyThreadSafeCallback(System.ComponentModel.Component what, object setto, string property);
  54. private delegate string OfficialWADNamingCallback(string whut);
  55. private string WAD_Saveas_Filename;
  56. // TODO: OOP scripting
  57. /*private string script_filename;
  58. private bool script_mode = false;
  59. private string[] nusentries;*/
  60. // Proxy stuff...
  61. private string proxy_url;
  62. private string proxy_usr;
  63. private string proxy_pwd;
  64. // Database threads
  65. private BackgroundWorker databaseWorker;
  66. private BackgroundWorker dsiDatabaseWorker;
  67. // Scripts Thread
  68. private BackgroundWorker scriptsWorker;
  69. // Colours for status box
  70. private System.Drawing.Color normalcolor = Color.FromName("Black");
  71. private System.Drawing.Color warningcolor = Color.FromName("DarkGoldenrod");
  72. private System.Drawing.Color errorcolor = Color.FromName("Crimson");
  73. private System.Drawing.Color infocolor = Color.FromName("RoyalBlue");
  74. // This is the standard entry to the GUI
  75. public Form1()
  76. {
  77. InitializeComponent();
  78. GUISetup();
  79. BootChecks();
  80. }
  81. // CLI Mode
  82. public Form1(string[] args)
  83. {
  84. InitializeComponent();
  85. Debug.WriteLine("CLI Parameters passed");
  86. GUISetup();
  87. if ((args.Length == 1) && (File.Exists(args[0])))
  88. {
  89. BootChecks();
  90. string script_content = File.ReadAllText(args[0]);
  91. FileInfo script_file = new FileInfo(args[0]);
  92. script_content += String.Format(";{0}", script_file.Name.Replace("." + script_file.Extension, ""));
  93. BackgroundWorker scripter = new BackgroundWorker();
  94. scripter.DoWork += new DoWorkEventHandler(RunScriptBg);
  95. scripter.RunWorkerAsync(script_content);
  96. }
  97. else if (args.Length >= 2)
  98. {
  99. RunCommandMode(args);
  100. Environment.Exit(0);
  101. //this.Close();
  102. }
  103. else
  104. {
  105. BootChecks();
  106. }
  107. }
  108. private void RunCommandMode(string[] args)
  109. {
  110. // CLI mode, inspired and taken from wiiNinja's mod.
  111. // Initialize the checkboxes and radio boxes
  112. packbox.Checked = false; // Create wad - default OFF
  113. localuse.Checked = true; // Use local content if already downloaded - default ON
  114. decryptbox.Checked = false;
  115. keepenccontents.Checked = false;
  116. //consoleCBox.SelectedIndex = 0; // 0 is Wii, 1 is DS
  117. // Clear 3 items in ios patches list. This feature is not supported in the command line version at this time.
  118. iosPatchCheckbox.Checked = false;
  119. iosPatchesListBox.SetItemChecked(0, false);
  120. iosPatchesListBox.SetItemChecked(1, false);
  121. iosPatchesListBox.SetItemChecked(2, false);
  122. Console.WriteLine("NUS Downloader - v{0}", version);
  123. if (args.Length < 2)
  124. {
  125. Console.WriteLine("Usage:");
  126. Console.WriteLine(" nusd <titleID> <titleVersion | *> [optionalArgs]");
  127. Console.WriteLine("\nWhere:");
  128. Console.WriteLine(" titleID = The ID of the title to be downloaded");
  129. Console.WriteLine(" titleVersion = The version of the title to be downloaded");
  130. Console.WriteLine(" Use \"*\" (no quotes) to get the latest version");
  131. Console.WriteLine(" OptionalArgs:");
  132. Console.WriteLine(" packwad = A wad file will be generated");
  133. Console.WriteLine(" localuse = Use local contents if available");
  134. Console.WriteLine(" decrypt = Create decrypted contents");
  135. Console.WriteLine(" keepencrypt = Keep encrypted contents");
  136. }
  137. else
  138. {
  139. for (int i = 0; i < args.Length; i++)
  140. {
  141. Console.WriteLine("{0}", args[i]);
  142. switch (i)
  143. {
  144. case 0:
  145. // First command line argument is ALWAYS the TitleID
  146. titleidbox.Text = args[i];
  147. break;
  148. case 1:
  149. // Second command line argument is ALWAYS the TitleVersion.
  150. // User may specify a "*" to retrieve the latest version
  151. if (args[i] == "*")
  152. titleversion.Text = "";
  153. else
  154. titleversion.Text = args[i];
  155. break;
  156. default:
  157. // Any other arguments beyond the 2nd one are considered optional
  158. if (args[i] == "packwad")
  159. packbox.Checked = true;
  160. else if (args[i] == "localuse")
  161. localuse.Checked = true;
  162. else if (args[i] == "decrypt")
  163. decryptbox.Checked = true;
  164. else if (args[i] == "keepencrypt")
  165. keepenccontents.Checked = true;
  166. else
  167. Console.WriteLine("\n>>>> Warning: Unrecognized command line argument: {0}. This option is ignored...", args[i]);
  168. break;
  169. }
  170. }
  171. // Do this to set the wad file name
  172. UpdatePackedName();
  173. // Call to get the files from server
  174. NUSDownloader_DoWork(null, null);
  175. Console.WriteLine("\nSuccessfully downloaded the title {0} version {1}", args[0], args[1]);
  176. }
  177. }
  178. private void GUISetup()
  179. {
  180. this.Font = new System.Drawing.Font("Tahoma", 8);
  181. this.MaximumSize = this.MinimumSize = this.Size; // Lock size down PATCHOW :D
  182. if (Type.GetType("Mono.Runtime") != null)
  183. {
  184. saveaswadbtn.Text = "Save As";
  185. clearButton.Text = "Clear";
  186. keepenccontents.Text = "Keep Enc. Contents";
  187. clearButton.Left -= 41;
  188. }
  189. else
  190. statusbox.Font = new System.Drawing.Font("Microsoft Sans Serif", 7);
  191. statusbox.SelectionColor = statusbox.ForeColor = normalcolor;
  192. if (version.StartsWith("SVN"))
  193. {
  194. WriteStatus("!!!!! THIS IS A DEBUG BUILD FROM SVN !!!!!");
  195. WriteStatus("Features CAN and WILL be broken in this build!");
  196. WriteStatus("Devs: REMEMBER TO CHANGE TO THE RELEASE CONFIGURATION AND CHANGE VERSION NUMBER BEFORE BUILDING!");
  197. WriteStatus("\r\n");
  198. }
  199. // Database BackgroundWorker
  200. this.databaseWorker = new BackgroundWorker();
  201. this.databaseWorker.DoWork += new DoWorkEventHandler(DoAllDatabaseyStuff);
  202. this.databaseWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(DoAllDatabaseyStuff_Completed);
  203. this.databaseWorker.ProgressChanged += new ProgressChangedEventHandler(DoAllDatabaseyStuff_ProgressChanged);
  204. this.databaseWorker.WorkerReportsProgress = true;
  205. // DSi Database BackgroundWorker
  206. this.dsiDatabaseWorker = new BackgroundWorker();
  207. this.dsiDatabaseWorker.DoWork += new DoWorkEventHandler(DSiDatabaseWork);
  208. this.dsiDatabaseWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(DSiDatabaseWork_Completed);
  209. this.dsiDatabaseWorker.ProgressChanged += new ProgressChangedEventHandler(DSiDatabaseWork_ProgressChanged);
  210. this.dsiDatabaseWorker.WorkerReportsProgress = true;
  211. // Scripts BGLoader
  212. this.scriptsWorker = new BackgroundWorker();
  213. this.scriptsWorker.DoWork += new DoWorkEventHandler(OrganizeScripts);
  214. this.scriptsWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(scriptsWorker_RunWorkerCompleted);
  215. }
  216. private void Form1_Load(object sender, EventArgs e)
  217. {
  218. this.Text = String.Format("NUSD - {0}", version); ;
  219. this.Size = this.MinimumSize;
  220. serverLbl.Text = "Wii";
  221. }
  222. private bool NUSDFileExists(string filename)
  223. {
  224. return File.Exists(Path.Combine(CURRENT_DIR, filename));
  225. }
  226. /// <summary>
  227. /// Checks certain file existances, etc.
  228. /// </summary>
  229. /// <returns></returns>
  230. private void BootChecks()
  231. {
  232. //Check if correct thread...
  233. if (this.InvokeRequired)
  234. {
  235. Debug.WriteLine("InvokeRequired...");
  236. BootChecksCallback bcc = new BootChecksCallback(BootChecks);
  237. this.Invoke(bcc);
  238. return;
  239. }
  240. /* Check for DSi common key bin file...
  241. if (NUSDFileExists("dsikey.bin") == true)
  242. {
  243. WriteStatus("DSi Common Key detected.");
  244. dsidecrypt = true;
  245. }*/
  246. /*
  247. // Check for database.xml
  248. if (NUSDFileExists("database.xml") == false)
  249. {
  250. WriteStatus("Database.xml not found. Title database not usable!");
  251. DatabaseEnabled(false);
  252. updateDatabaseToolStripMenuItem.Enabled = true;
  253. updateDatabaseToolStripMenuItem.Visible = true;
  254. updateDatabaseToolStripMenuItem.Text = "Download Database";
  255. }
  256. else
  257. {
  258. Database db = new Database();
  259. db.LoadDatabaseToStream(Path.Combine(CURRENT_DIR, "database.xml"));
  260. string version = db.GetDatabaseVersion();
  261. WriteStatus("Database.xml detected.");
  262. WriteStatus(" - Version: " + version);
  263. updateDatabaseToolStripMenuItem.Text = "Update Database";
  264. //databaseButton.Enabled = false;
  265. //databaseButton.Text = "DB Loading";
  266. databaseButton.Text = " [ ]";
  267. databaseButton.Image = Properties.Resources.arrow_ticker;
  268. // Load it up...
  269. this.fds.RunWorkerAsync();
  270. }
  271. // Check for database.xml
  272. if (NUSDFileExists("dsidatabase.xml") == false)
  273. {
  274. WriteStatus("DSiDatabase.xml not found. DSi database not usable!");
  275. DatabaseEnabled(false);
  276. updateDatabaseToolStripMenuItem.Enabled = true;
  277. updateDatabaseToolStripMenuItem.Visible = true;
  278. updateDatabaseToolStripMenuItem.Text = "Download Database";
  279. }
  280. else
  281. {
  282. Database db = new Database();
  283. db.LoadDatabaseToStream(Path.Combine(CURRENT_DIR, "database.xml"));
  284. string version = db.GetDatabaseVersion();
  285. WriteStatus("Database.xml detected.");
  286. WriteStatus(" - Version: " + version);
  287. updateDatabaseToolStripMenuItem.Text = "Update Database";
  288. //databaseButton.Enabled = false;
  289. //databaseButton.Text = "DB Loading";
  290. databaseButton.Text = " [ ]";
  291. databaseButton.Image = Properties.Resources.arrow_ticker;
  292. // Load it up...
  293. this.fds.RunWorkerAsync();
  294. }*/
  295. if (NUSDFileExists("database.xml") == true)
  296. {
  297. Database db = new Database();
  298. db.LoadDatabaseToStream(Path.Combine(CURRENT_DIR, "database.xml"));
  299. string version = db.GetDatabaseVersion();
  300. WriteStatus("Database.xml detected.");
  301. WriteStatus(" - Version: " + version);
  302. updateDatabaseToolStripMenuItem.Text = "Update Database";
  303. databaseButton.Text = " [ ]";
  304. databaseButton.Image = Properties.Resources.arrow_ticker;
  305. // Load it up...
  306. this.databaseWorker.RunWorkerAsync();
  307. }
  308. if (NUSDFileExists("dsidatabase.xml") == true)
  309. {
  310. Database db = new Database();
  311. db.LoadDatabaseToStream(Path.Combine(CURRENT_DIR, "dsidatabase.xml"));
  312. string version = db.GetDatabaseVersion();
  313. WriteStatus("DSiDatabase.xml detected.");
  314. WriteStatus(" - Version: " + version);
  315. updateDatabaseToolStripMenuItem.Text = "Update Database";
  316. databaseButton.Text = " [ ]";
  317. databaseButton.Image = Properties.Resources.arrow_ticker;
  318. // Load it up...
  319. this.dsiDatabaseWorker.RunWorkerAsync();
  320. }
  321. // Load scripts (local)
  322. RunScriptOrganizer();
  323. // Check for Proxy Settings file...
  324. if (NUSDFileExists("proxy.txt") == true)
  325. {
  326. WriteStatus("Proxy settings detected.");
  327. string[] proxy_file = File.ReadAllLines(Path.Combine(CURRENT_DIR, "proxy.txt"));
  328. proxy_url = proxy_file[0];
  329. // If proxy\nuser\npassword
  330. if (proxy_file.Length > 2)
  331. {
  332. proxy_usr = proxy_file[1];
  333. proxy_pwd = proxy_file[2];
  334. }
  335. else if (proxy_file.Length > 1)
  336. {
  337. proxy_usr = proxy_file[1];
  338. SetAllEnabled(false);
  339. ProxyVerifyBox.Visible = true;
  340. ProxyVerifyBox.Enabled = true;
  341. ProxyPwdBox.Enabled = true;
  342. SaveProxyBtn.Enabled = true;
  343. ProxyVerifyBox.Select();
  344. }
  345. }
  346. }
  347. private void DoAllDatabaseyStuff(object sender, System.ComponentModel.DoWorkEventArgs e)
  348. {
  349. BackgroundWorker worker = sender as BackgroundWorker;
  350. ClearDatabaseStrip();
  351. FillDatabaseStrip(worker);
  352. LoadRegionCodes();
  353. FillDatabaseScripts();
  354. ShowInnerToolTips(false);
  355. }
  356. private void DoAllDatabaseyStuff_Completed(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
  357. {
  358. //this.databaseButton.Enabled = true;
  359. this.databaseButton.Text = "Database...";
  360. this.databaseButton.Image = null;
  361. /*
  362. if (this.KoreaMassUpdate.HasDropDownItems || this.PALMassUpdate.HasDropDownItems || this.NTSCMassUpdate.HasDropDownItems)
  363. {
  364. this.scriptsbutton.Enabled = true;
  365. }*/
  366. }
  367. private void DoAllDatabaseyStuff_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
  368. {
  369. if (e.ProgressPercentage == 25)
  370. databaseButton.Text = " [. ]";
  371. else if (e.ProgressPercentage == 50)
  372. databaseButton.Text = " [.. ]";
  373. else if (e.ProgressPercentage == 75)
  374. databaseButton.Text = " [... ]";
  375. else if (e.ProgressPercentage == 100)
  376. databaseButton.Text = " [....]";
  377. }
  378. private void RunScriptOrganizer()
  379. {
  380. this.scriptsWorker.RunWorkerAsync();
  381. }
  382. private void SetAllEnabled(bool enabled)
  383. {
  384. for (int a = 0; a < this.Controls.Count; a++)
  385. {
  386. try
  387. {
  388. this.Controls[a].Enabled = enabled;
  389. }
  390. catch
  391. {
  392. // ...
  393. }
  394. }
  395. }
  396. /*
  397. /// <summary>
  398. /// Gets the database version.
  399. /// </summary>
  400. /// <param name="file">The database file.</param>
  401. /// <returns></returns>
  402. private string GetDatabaseVersion(string file)
  403. {
  404. // Read version of Database.xml
  405. XmlDocument xDoc = new XmlDocument();
  406. if (file.Contains("<"))
  407. xDoc.LoadXml(file);
  408. else
  409. {
  410. if (File.Exists(file))
  411. {
  412. xDoc.Load(file);
  413. }
  414. else
  415. {
  416. return "None Found";
  417. }
  418. }
  419. XmlNodeList DatabaseList = xDoc.GetElementsByTagName("database");
  420. XmlAttributeCollection Attributes = DatabaseList[0].Attributes;
  421. return Attributes[0].Value;
  422. }*/
  423. private void extrasMenuButton_Click(object sender, EventArgs e)
  424. {
  425. // Show extras menu
  426. extrasStrip.Text = "Showing";
  427. extrasStrip.Show(Extrasbtn, 2, (2+Extrasbtn.Height));
  428. {
  429. System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
  430. timer.Interval = 52;
  431. timer.Tick += new EventHandler(contextmenusTimer_Tick);
  432. timer.Start();
  433. }
  434. }
  435. /// <summary>
  436. /// Loads the title info from TMD.
  437. /// </summary>
  438. private void LoadTitleFromTMD()
  439. {
  440. // Show dialog for opening TMD file...
  441. OpenFileDialog opentmd = new OpenFileDialog();
  442. opentmd.Filter = "TMD Files|*tmd*";
  443. opentmd.Title = "Open TMD";
  444. if (opentmd.ShowDialog() != DialogResult.Cancel)
  445. {
  446. libWiiSharp.TMD tmdLocal = new libWiiSharp.TMD();
  447. tmdLocal.LoadFile(opentmd.FileName);
  448. WriteStatus(String.Format("TMD Loaded ({0} blocks)", tmdLocal.GetNandBlocks()));
  449. titleidbox.Text = tmdLocal.TitleID.ToString("X16");
  450. WriteStatus("Title ID: " + tmdLocal.TitleID.ToString("X16"));
  451. titleversion.Text = tmdLocal.TitleVersion.ToString();
  452. WriteStatus("Version: " + tmdLocal.TitleVersion);
  453. if (tmdLocal.StartupIOS.ToString("X") != "0")
  454. WriteStatus("Requires: IOS" + int.Parse(tmdLocal.StartupIOS.ToString("X").Substring(7, 2).ToString(), System.Globalization.NumberStyles.HexNumber));
  455. WriteStatus("Content Count: " + tmdLocal.NumOfContents);
  456. for (int a = 0; a < tmdLocal.Contents.Length; a++)
  457. {
  458. WriteStatus(String.Format(" Content {0}: {1} ({2} bytes)", a, tmdLocal.Contents[a].ContentID.ToString("X8"), tmdLocal.Contents[a].Size.ToString()));
  459. WriteStatus(String.Format(" - Index: {0}", tmdLocal.Contents[a].Index.ToString()));
  460. WriteStatus(String.Format(" - Type: {0}", tmdLocal.Contents[a].Type.ToString()));
  461. WriteStatus(String.Format(" - Hash: {0}...", DisplayBytes(tmdLocal.Contents[a].Hash, String.Empty).Substring(0, 8)));
  462. }
  463. WriteStatus("TMD information parsed!");
  464. }
  465. }
  466. /// <summary>
  467. /// Writes the status to the statusbox.
  468. /// </summary>
  469. /// <param name="Update">The update.</param>
  470. /// <param name="writecolor">The color to use for writing text into the text box.</param>
  471. public void WriteStatus(string Update, Color writecolor)
  472. {
  473. // Check if thread-safe
  474. if (statusbox.InvokeRequired)
  475. {
  476. Debug.WriteLine("InvokeRequired...");
  477. WriteStatusCallback wsc = new WriteStatusCallback(WriteStatus);
  478. this.Invoke(wsc, new object[] { Update, writecolor });
  479. return;
  480. }
  481. // Small function for writing text to the statusbox...
  482. int startlen = statusbox.TextLength;
  483. if (statusbox.Text == "")
  484. statusbox.Text = Update;
  485. else
  486. statusbox.AppendText("\r\n" + Update);
  487. int endlen = statusbox.TextLength;
  488. // Set the color
  489. statusbox.Select(startlen, endlen - startlen);
  490. statusbox.SelectionColor = writecolor;
  491. // Scroll to end of text box.
  492. statusbox.SelectionStart = statusbox.TextLength;
  493. statusbox.SelectionLength = 0;
  494. statusbox.ScrollToCaret();
  495. // Also write to console
  496. Console.WriteLine(Update);
  497. }
  498. /// <summary>
  499. /// Writes the status to the statusbox.
  500. /// </summary>
  501. /// <param name="Update">The update.</param>
  502. public void WriteStatus(string Update)
  503. {
  504. WriteStatus(Update, normalcolor);
  505. }
  506. /// <summary>
  507. /// Reads the type of the Title ID.
  508. /// </summary>
  509. /// <param name="ttlid">The TitleID.</param>
  510. private void ReadIDType(string ttlid)
  511. {
  512. /* Wiibrew TitleID Info...
  513. # 3 00000001: Essential system titles
  514. # 4 00010000 and 00010004 : Disc-based games
  515. # 5 00010001: Downloaded channels
  516. * 5.1 000010001-Cxxx : Commodore 64 Games
  517. * 5.2 000010001-Exxx : NeoGeo Games
  518. * 5.3 000010001-Fxxx : NES Games
  519. * 5.4 000010001-Hxxx : Channels
  520. * 5.5 000010001-Jxxx : SNES Games
  521. * 5.6 000010001-Nxxx : Nintendo 64 Games
  522. * 5.7 000010001-Wxxx : WiiWare
  523. # 6 00010002: System channels
  524. # 7 00010004: Game channels and games that use them
  525. # 8 00010005: Downloaded Game Content
  526. # 9 00010008: "Hidden" channels
  527. */
  528. if (ttlid.Substring(0, 8) == "00000001")
  529. WriteStatus("ID Type: System Title. BE CAREFUL!", warningcolor);
  530. else if ((ttlid.Substring(0, 8) == "00010000") || (ttlid.Substring(0, 8) == "00010004"))
  531. WriteStatus("ID Type: Disc-Based Game. Unlikely NUS Content!");
  532. else if (ttlid.Substring(0, 8) == "00010001")
  533. WriteStatus("ID Type: Downloaded Channel. Possible NUS Content.");
  534. else if (ttlid.Substring(0, 8) == "00010002")
  535. WriteStatus("ID Type: System Channel. BE CAREFUL!", warningcolor);
  536. else if (ttlid.Substring(0, 8) == "00010004")
  537. WriteStatus("ID Type: Game Channel. Unlikely NUS Content!");
  538. else if (ttlid.Substring(0, 8) == "00010005")
  539. WriteStatus("ID Type: Downloaded Game Content. Unlikely NUS Content!");
  540. else if (ttlid.Substring(0, 8) == "00010008")
  541. WriteStatus("ID Type: 'Hidden' Channel. Unlikely NUS Content!");
  542. else
  543. WriteStatus("ID Type: Unknown. Unlikely NUS Content!");
  544. }
  545. private void DownloadBtn_Click(object sender, EventArgs e)
  546. {
  547. if (titleidbox.Text == String.Empty)
  548. {
  549. // Prevent mass deletion and fail
  550. WriteStatus("Please enter a Title ID!", errorcolor);
  551. return;
  552. }
  553. else if (!(packbox.Checked) && !(decryptbox.Checked) && !(keepenccontents.Checked))
  554. {
  555. // Prevent pointless running by n00bs.
  556. WriteStatus("Running with your current settings will produce no output!", errorcolor);
  557. WriteStatus(" - To amend this, look below and check an output type.", errorcolor);
  558. return;
  559. }/*
  560. else if (!(script_mode))
  561. {
  562. try
  563. {
  564. if (!statusbox.Lines[0].StartsWith(" ---"))
  565. SetTextThreadSafe(statusbox, " --- " + titleidbox.Text + " ---");
  566. }
  567. catch // No lines present...
  568. {
  569. SetTextThreadSafe(statusbox, " --- " + titleidbox.Text + " ---");
  570. }
  571. }
  572. else
  573. WriteStatus(" --- " + titleidbox.Text + " ---");*/
  574. // Running Downloads in background so no form freezing
  575. NUSDownloader.RunWorkerAsync();
  576. }
  577. private void SetTextThreadSafe(System.Windows.Forms.Control what, string setto)
  578. {
  579. SetPropertyThreadSafe(what, "Name", setto);
  580. }
  581. private void SetPropertyThreadSafe(System.ComponentModel.Component what, object setto, string property)
  582. {
  583. if (this.InvokeRequired)
  584. {
  585. SetPropertyThreadSafeCallback sptscb = new SetPropertyThreadSafeCallback(SetPropertyThreadSafe);
  586. try
  587. {
  588. this.Invoke(sptscb, new object[] { what, setto, property });
  589. }
  590. catch (Exception)
  591. {
  592. // FFFFF!
  593. }
  594. return;
  595. }
  596. what.GetType().GetProperty(property).SetValue(what, setto, null);
  597. //what.Text = setto;
  598. }
  599. private void NUSDownloader_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
  600. {
  601. Control.CheckForIllegalCrossThreadCalls = false; // this function would need major rewriting to get rid of this...
  602. WriteStatus("Starting NUS Download. Please be patient!", infocolor);
  603. SetEnableforDownload(false);
  604. downloadstartbtn.Text = "Starting NUS Download!";
  605. // WebClient configuration
  606. WebClient nusWC = new WebClient();
  607. nusWC = ConfigureWithProxy(nusWC);
  608. // Create\Configure NusClient
  609. libWiiSharp.NusClient nusClient = new libWiiSharp.NusClient();
  610. nusClient.ConfigureNusClient(nusWC);
  611. nusClient.UseLocalFiles = localuse.Checked;
  612. nusClient.ContinueWithoutTicket = true;
  613. // Server
  614. if (serverLbl.Text == "Wii")
  615. nusClient.SetToWiiServer();
  616. else if (serverLbl.Text == "DSi")
  617. nusClient.SetToDSiServer();
  618. // Events
  619. nusClient.Debug += new EventHandler<libWiiSharp.MessageEventArgs>(nusClient_Debug);
  620. nusClient.Progress += new EventHandler<ProgressChangedEventArgs>(nusClient_Progress);
  621. libWiiSharp.StoreType[] storeTypes = new libWiiSharp.StoreType[3];
  622. if (packbox.Checked) storeTypes[0] = libWiiSharp.StoreType.WAD; else storeTypes[0] = libWiiSharp.StoreType.Empty;
  623. if (decryptbox.Checked) storeTypes[1] = libWiiSharp.StoreType.DecryptedContent; else storeTypes[1] = libWiiSharp.StoreType.Empty;
  624. if (keepenccontents.Checked) storeTypes[2] = libWiiSharp.StoreType.EncryptedContent; else storeTypes[2] = libWiiSharp.StoreType.Empty;
  625. string wadName;
  626. if (String.IsNullOrEmpty(WAD_Saveas_Filename))
  627. wadName = wadnamebox.Text;
  628. else
  629. wadName = WAD_Saveas_Filename;
  630. try
  631. {
  632. nusClient.DownloadTitle(titleidbox.Text, titleversion.Text, Path.Combine(CURRENT_DIR, "titles"), wadName, storeTypes);
  633. }
  634. catch (Exception ex)
  635. {
  636. WriteStatus("Download failed: \"" + ex.Message + " ):\"", errorcolor);
  637. }
  638. if (iosPatchCheckbox.Checked == true) { // Apply patches then...
  639. bool didpatch = false;
  640. int noofpatches = 0;
  641. string appendpatch = "";
  642. // Okay, it's checked.
  643. libWiiSharp.IosPatcher iosp = new libWiiSharp.IosPatcher();
  644. libWiiSharp.WAD ioswad = new libWiiSharp.WAD();
  645. wadName = wadName.Replace("[v]", nusClient.TitleVersion.ToString());
  646. if (wadName.Contains(Path.DirectorySeparatorChar.ToString()) || wadName.Contains(Path.AltDirectorySeparatorChar.ToString()))
  647. ioswad.LoadFile(wadName);
  648. else
  649. ioswad.LoadFile(Path.Combine(Path.Combine(Path.Combine(Path.Combine(CURRENT_DIR, "titles"), titleidbox.Text), nusClient.TitleVersion.ToString()), wadName));
  650. try
  651. {
  652. iosp.LoadIOS(ref ioswad);
  653. }
  654. catch (Exception)
  655. {
  656. WriteStatus("NUS Download Finished.", infocolor);
  657. return;
  658. }
  659. foreach (object checkItem in iosPatchesListBox.CheckedItems)
  660. {
  661. // ensure not 'indeterminate'
  662. if (iosPatchesListBox.GetItemCheckState(iosPatchesListBox.Items.IndexOf(checkItem)).ToString() == "Checked") {
  663. switch (checkItem.ToString()) {
  664. case "Trucha bug":
  665. noofpatches = iosp.PatchFakeSigning();
  666. if (noofpatches > 0)
  667. {
  668. WriteStatus(" - Patched in fake-signing:", infocolor);
  669. if (noofpatches > 1)
  670. appendpatch = "es";
  671. else
  672. appendpatch = "";
  673. WriteStatus(String.Format(" {0} patch{1} applied.", noofpatches, appendpatch));
  674. didpatch = true;
  675. }
  676. else
  677. WriteStatus(" - Could not patch fake-signing", errorcolor);
  678. break;
  679. case "ES_Identify":
  680. noofpatches = iosp.PatchEsIdentify();
  681. if (noofpatches > 0)
  682. {
  683. WriteStatus(" - Patched in ES_Identify:", infocolor);
  684. if (noofpatches > 1)
  685. appendpatch = "es";
  686. else
  687. appendpatch = "";
  688. WriteStatus(String.Format(" {0} patch{1} applied.", noofpatches, appendpatch));
  689. didpatch = true;
  690. }
  691. else
  692. WriteStatus(" - Could not patch ES_Identify", errorcolor);
  693. break;
  694. case "NAND permissions":
  695. noofpatches = iosp.PatchNandPermissions();
  696. if (noofpatches > 0)
  697. {
  698. WriteStatus(" - Patched in NAND permissions:", infocolor);
  699. if (noofpatches > 1)
  700. appendpatch = "es";
  701. else
  702. appendpatch = "";
  703. WriteStatus(String.Format(" {0} patch{1} applied.", noofpatches, appendpatch));
  704. didpatch = true;
  705. }
  706. else
  707. WriteStatus(" - Could not patch NAND permissions", errorcolor);
  708. break;
  709. }
  710. }
  711. else {
  712. // WriteStatus(iosPatchesListBox.GetItemCheckState(iosPatchesListBox.Items.IndexOf(checkItem)).ToString());
  713. }
  714. }
  715. if (didpatch)
  716. {
  717. wadName = wadName.Replace(".wad",".patched.wad");
  718. try
  719. {
  720. if (wadName.Contains(Path.DirectorySeparatorChar.ToString()) || wadName.Contains(Path.AltDirectorySeparatorChar.ToString()))
  721. ioswad.Save(wadName);
  722. else
  723. ioswad.Save(Path.Combine(Path.Combine(Path.Combine(Path.Combine(CURRENT_DIR, "titles"), titleidbox.Text), nusClient.TitleVersion.ToString()), wadName));
  724. WriteStatus(String.Format("Patched WAD saved as: {0}", Path.GetFileName(wadName)), infocolor);
  725. }
  726. catch (Exception ex)
  727. {
  728. WriteStatus(String.Format("Couldn't save patched WAD: \"{0}\" :(",ex.Message), errorcolor);
  729. }
  730. }
  731. }
  732. WriteStatus("NUS Download Finished.");
  733. }
  734. void nusClient_Progress(object sender, ProgressChangedEventArgs e)
  735. {
  736. dlprogress.Value = e.ProgressPercentage;
  737. }
  738. void nusClient_Debug(object sender, libWiiSharp.MessageEventArgs e)
  739. {
  740. WriteStatus(e.Message);
  741. }
  742. private void NUSDownloader_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  743. {
  744. WAD_Saveas_Filename = String.Empty;
  745. SetEnableforDownload(true);
  746. downloadstartbtn.Text = "Start NUS Download!";
  747. dlprogress.Value = 0;
  748. if (IsWin7())
  749. dlprogress.ShowInTaskbar = false;
  750. }
  751. private void packbox_CheckedChanged(object sender, EventArgs e)
  752. {
  753. if (packbox.Checked == true)
  754. {
  755. wadnamebox.Enabled = true;
  756. saveaswadbtn.Enabled = true;
  757. // Change WAD name if applicable
  758. UpdatePackedName();
  759. }
  760. else
  761. {
  762. wadnamebox.Enabled = false;
  763. saveaswadbtn.Enabled = false;
  764. wadnamebox.Text = String.Empty;
  765. if (iosPatchCheckbox.Checked)
  766. iosPatchCheckbox.Checked = false;
  767. }
  768. }
  769. private void titleidbox_TextChanged(object sender, EventArgs e)
  770. {
  771. UpdatePackedName();
  772. EnablePatchIOSBox();
  773. }
  774. private void titleversion_TextChanged(object sender, EventArgs e)
  775. {
  776. UpdatePackedName();
  777. }
  778. private void EnablePatchIOSBox()
  779. {
  780. iosPatchCheckbox.Enabled = TitleIsIOS(titleidbox.Text);
  781. if (iosPatchCheckbox.Enabled == false)
  782. iosPatchCheckbox.Checked = false;
  783. }
  784. private bool TitleIsIOS(string titleid)
  785. {
  786. if (titleid.Length != 16)
  787. return false;
  788. if ((titleid == "0000000100000001") || (titleid == "0000000100000002"))
  789. return false;
  790. if (titleid.Substring(0, 14) == "00000001000000")
  791. return true;
  792. return false;
  793. }
  794. /// <summary>
  795. /// Displays the bytes.
  796. /// </summary>
  797. /// <param name="bytes">The bytes.</param>
  798. /// <param name="spacer">What separates the bytes</param>
  799. /// <returns></returns>
  800. public string DisplayBytes(byte[] bytes, string spacer)
  801. {
  802. string output = "";
  803. for (int i = 0; i < bytes.Length; ++i)
  804. {
  805. output += bytes[i].ToString("X2") + spacer;
  806. }
  807. return output;
  808. }
  809. private void DatabaseButton_Click(object sender, EventArgs e)
  810. {
  811. // Open Database button menu...
  812. databaseStrip.Text = "Showing";
  813. databaseStrip.Show(databaseButton, 2, (2+databaseButton.Height));
  814. //if (!e.Equals(EventArgs.Empty))
  815. {
  816. System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
  817. timer.Interval = 50;
  818. timer.Tick += new EventHandler(contextmenusTimer_Tick);
  819. timer.Start();
  820. }
  821. }
  822. void contextmenusTimer_Tick(object sender, EventArgs e)
  823. {
  824. if (SystemMenuList.Pressed || IOSMenuList.Pressed || VCMenuList.Pressed || WiiWareMenuList.Pressed
  825. || RegionCodesList.Pressed || scriptsLocalMenuEntry.Pressed || scriptsDatabaseToolStripMenuItem.Pressed
  826. || emulateUpdate.Pressed)
  827. return;
  828. if (databaseButton.ClientRectangle.Contains(databaseButton.PointToClient(MousePosition)) && ((System.Windows.Forms.Timer)sender).Interval != 50)
  829. {
  830. databaseStrip.Close();
  831. scriptsStrip.Close();
  832. extrasStrip.Close();
  833. DatabaseButton_Click(sender, EventArgs.Empty);
  834. ((System.Windows.Forms.Timer)sender).Stop();
  835. }
  836. if (scriptsbutton.ClientRectangle.Contains(scriptsbutton.PointToClient(MousePosition)) && ((System.Windows.Forms.Timer)sender).Interval != 51)
  837. {
  838. databaseStrip.Close();
  839. scriptsStrip.Close();
  840. extrasStrip.Close();
  841. scriptsbutton_Click(sender, EventArgs.Empty);
  842. ((System.Windows.Forms.Timer)sender).Stop();
  843. }
  844. if (Extrasbtn.ClientRectangle.Contains(Extrasbtn.PointToClient(MousePosition)) && ((System.Windows.Forms.Timer)sender).Interval != 52)
  845. {
  846. databaseStrip.Close();
  847. scriptsStrip.Close();
  848. extrasStrip.Close();
  849. extrasMenuButton_Click(sender, EventArgs.Empty);
  850. ((System.Windows.Forms.Timer)sender).Stop();
  851. }
  852. //Debug.Write(((databaseStrip.Text == "Hidden").ToString() + (extrasStrip.Text == "Hidden").ToString() + (scriptsStrip.Text == "Hidden").ToString()));
  853. if ((databaseStrip.Visible == false) && (extrasStrip.Visible == false) && (scriptsStrip.Visible == false))
  854. ((System.Windows.Forms.Timer)sender).Stop();
  855. }
  856. /// <summary>
  857. /// Clears the database strip.
  858. /// </summary>
  859. private void ClearDatabaseStrip()
  860. {
  861. Control.CheckForIllegalCrossThreadCalls = false;
  862. object[] thingstoclear = new object[] {
  863. SystemMenuList, IOSMenuList, WiiWareMenuList, VCMenuList,
  864. // Now Virtual Console
  865. C64MenuList, NeoGeoMenuList, NESMenuList,
  866. SNESMenuList, N64MenuList, TurboGrafx16MenuList,
  867. TurboGrafxCDMenuList, MSXMenuList, SegaMSMenuList,
  868. GenesisMenuList, VCArcadeMenuList,
  869. // DSi Entries
  870. dsiSystemToolStripMenu, dSiWareToolStripMenu
  871. };
  872. foreach (System.Windows.Forms.ToolStripMenuItem tsmiclear in thingstoclear)
  873. {
  874. if (tsmiclear.Name != "VCMenuList") // Don't clear the VC Menu...
  875. tsmiclear.DropDownItems.Clear();
  876. /*
  877. if (tsmiclear.OwnerItem != VCMenuList) // and don't disable the VC menu subparts...
  878. tsmiclear.Enabled = false;*/
  879. }
  880. }
  881. /// <summary>
  882. /// Fills the database strip with the local database.xml file.
  883. /// </summary>
  884. private void FillDatabaseStrip(BackgroundWorker worker)
  885. {
  886. // Something needs to be done to remove this i guess
  887. //Control.CheckForIllegalCrossThreadCalls = false;
  888. // Set fake items visible and real ones not. Only way to stop buggy enabled stuff.
  889. SetPropertyThreadSafe(SystemMenuList, false, "Visible");
  890. SetPropertyThreadSafe(IOSMenuList, false, "Visible");
  891. SetPropertyThreadSafe(VCMenuList, false, "Visible");
  892. SetPropertyThreadSafe(WiiWareMenuList, false, "Visible");
  893. SetPropertyThreadSafe(systemFakeMenuItem, true, "Visible");
  894. SetPropertyThreadSafe(iosFakeMenuItem, true, "Visible");
  895. SetPropertyThreadSafe(vcFakeMenuItem, true, "Visible");
  896. SetPropertyThreadSafe(wwFakeMenuItem, true, "Visible");
  897. Database databaseObj = new Database();
  898. databaseObj.LoadDatabaseToStream(Path.Combine(CURRENT_DIR, "database.xml"));
  899. ToolStripMenuItem[] systemItems = databaseObj.LoadSystemTitles();
  900. for (int a = 0; a < systemItems.Length; a++)
  901. {
  902. systemItems[a].DropDownItemClicked += new ToolStripItemClickedEventHandler(DatabaseItem_Clicked);
  903. for (int b = 0; b < systemItems[a].DropDownItems.Count; b++)
  904. {
  905. ToolStripMenuItem syslowerentry = (ToolStripMenuItem)systemItems[a].DropDownItems[b];
  906. if (syslowerentry.DropDownItems.Count > 0)
  907. {
  908. syslowerentry.DropDownItemClicked += new ToolStripItemClickedEventHandler(DatabaseItem_Clicked);
  909. }
  910. }
  911. //AddToolStripItemToStrip(SystemMenuList, systemItems[a]);
  912. //SystemMenuList.DropDownItems.Add(systemItems[a]);
  913. }
  914. Array.Sort(systemItems, delegate(ToolStripMenuItem tsmi1, ToolStripMenuItem tsmi2)
  915. {
  916. return tsmi1.Text
  917. .Substring(18, tsmi1.Text.Length - 19).CompareTo(tsmi2.Text.Substring(18, tsmi2.Text.Length - 19));
  918. });
  919. AddToolStripItemToStrip(SystemMenuList, systemItems);
  920. SetPropertyThreadSafe(systemFakeMenuItem, false, "Visible");
  921. SetPropertyThreadSafe(SystemMenuList, true, "Visible");
  922. Debug.WriteLine("Database: SysTitles added");
  923. worker.ReportProgress(25);
  924. ToolStripMenuItem[] iosItems = databaseObj.LoadIosTitles();
  925. for (int a = 0; a < iosItems.Length; a++)
  926. {
  927. iosItems[a].DropDownItemClicked += new ToolStripItemClickedEventHandler(DatabaseItem_Clicked);
  928. //AddToolStripItemToStrip(IOSMenuList, iosItems[a]);
  929. //IOSMenuList.DropDownItems.Add(iosItems[a]);
  930. }
  931. AddToolStripItemToStrip(IOSMenuList, iosItems);
  932. SetPropertyThreadSafe(iosFakeMenuItem, false, "Visible");
  933. SetPropertyThreadSafe(IOSMenuList, true, "Visible");
  934. Debug.WriteLine("Database: IosTitles added");
  935. worker.ReportProgress(50);
  936. ToolStripMenuItem[][] vcItems = databaseObj.LoadVirtualConsoleTitles();
  937. for (int a = 0; a < vcItems.Length; a++)
  938. {
  939. for (int b = 0; b < vcItems[a].Length; b++)
  940. {
  941. vcItems[a][b].DropDownItemClicked += new ToolStripItemClickedEventHandler(DatabaseItem_Clicked);
  942. for (int c = 0; c < vcItems[a][b].DropDownItems.Count; c++)
  943. {
  944. ToolStripMenuItem lowerentry = (ToolStripMenuItem)vcItems[a][b].DropDownItems[c];
  945. lowerentry.DropDownItemClicked += new ToolStripItemClickedEventHandler(DatabaseItem_Clicked);
  946. }
  947. }
  948. Array.Sort(vcItems[a], delegate(ToolStripMenuItem tsmi1, ToolStripMenuItem tsmi2)
  949. {
  950. return tsmi1.Text
  951. .Substring(18, tsmi1.Text.Length - 19).CompareTo(tsmi2.Text.Substring(18, tsmi2.Text.Length - 19));
  952. });
  953. AddToolStripItemToStrip((ToolStripMenuItem)VCMenuList.DropDownItems[a], vcItems[a]);
  954. }
  955. SetPropertyThreadSafe(vcFakeMenuItem, false, "Visible");
  956. SetPropertyThreadSafe(VCMenuList, true, "Visible");
  957. Debug.WriteLine("Database: VCTitles added");
  958. worker.ReportProgress(75);
  959. ToolStripMenuItem[] wwItems = databaseObj.LoadWiiWareTitles();
  960. for (int a = 0; a < wwItems.Length; a++)
  961. {
  962. wwItems[a].DropDownItemClicked += new ToolStripItemClickedEventHandler(DatabaseItem_Clicked);
  963. for (int b = 0; b < wwItems[a].DropDownItems.Count; b++)
  964. {
  965. ToolStripMenuItem lowerentry = (ToolStripMenuItem)wwItems[a].DropDownItems[b];
  966. if (lowerentry.DropDownItems.Count > 0)
  967. {
  968. lowerentry.DropDownItemClicked += new ToolStripItemClickedEventHandler(DatabaseItem_Clicked);
  969. }
  970. }
  971. //AddToolStripItemToStrip(WiiWareMenuList, wwItems[a]);
  972. //WiiWareMenuList.DropDownItems.Add(wwItems[a]);
  973. }
  974. Array.Sort(wwItems, delegate(ToolStripMenuItem tsmi1, ToolStripMenuItem tsmi2)
  975. {
  976. return tsmi1.Text
  977. .Substring(18, tsmi1.Text.Length - 19).CompareTo(tsmi2.Text.Substring(18, tsmi2.Text.Length - 19));
  978. });
  979. AddToolStripItemToStrip(WiiWareMenuList, wwItems);
  980. SetPropertyThreadSafe(wwFakeMenuItem, false, "Visible");
  981. SetPropertyThreadSafe(WiiWareMenuList, true, "Visible");
  982. Debug.WriteLine("Database: WiiWareTitles added");
  983. worker.ReportProgress(100);
  984. }
  985. /// <summary>
  986. /// Fills the database strip with the local database.xml file.
  987. /// </summary>
  988. private void FillDSiDatabaseStrip(BackgroundWorker worker)
  989. {
  990. // Set fake items visible and real ones not. Only way to stop buggy enabled stuff.
  991. SetPropertyThreadSafe(dsiSystemToolStripMenu, false, "Visible");
  992. SetPropertyThreadSafe(dSiWareToolStripMenu, false, "Visible");
  993. SetPropertyThreadSafe(dsiFakeSystemToolStripMenu, true, "Visible");
  994. SetPropertyThreadSafe(dSiWareFakeToolStripMenu, true, "Visible");
  995. Database databaseObj = new Database();
  996. databaseObj.LoadDatabaseToStream(Path.Combine(CURRENT_DIR, "dsidatabase.xml"));
  997. ToolStripMenuItem[] systemItems = databaseObj.LoadDSiSystemTitles();
  998. for (int a = 0; a < systemItems.Length; a++)
  999. {
  1000. systemItems[a].DropDownItemClicked += new ToolStripItemClickedEventHandler(DatabaseItem_Clicked);
  1001. for (int b = 0; b < s

Large files files are truncated, but you can click here to view the full file