PageRenderTime 61ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/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
  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 < systemItems[a].DropDownItems.Count; b++)
  1002. {
  1003. ToolStripMenuItem syslowerentry = (ToolStripMenuItem)systemItems[a].DropDownItems[b];
  1004. if (syslowerentry.DropDownItems.Count > 0)
  1005. {
  1006. syslowerentry.DropDownItemClicked += new ToolStripItemClickedEventHandler(DatabaseItem_Clicked);
  1007. }
  1008. }
  1009. }
  1010. Array.Sort(systemItems, delegate(ToolStripMenuItem tsmi1, ToolStripMenuItem tsmi2)
  1011. {
  1012. return tsmi1.Text
  1013. .Substring(18, tsmi1.Text.Length - 19).CompareTo(tsmi2.Text.Substring(18, tsmi2.Text.Length - 19));
  1014. });
  1015. AddToolStripItemToStrip(dsiSystemToolStripMenu, systemItems);
  1016. SetPropertyThreadSafe(dsiFakeSystemToolStripMenu, false, "Visible");
  1017. SetPropertyThreadSafe(dsiSystemToolStripMenu, true, "Visible");
  1018. Debug.WriteLine("Database: DSiSysTitles added");
  1019. worker.ReportProgress(50);
  1020. ToolStripMenuItem[] dsiWareItems = databaseObj.LoadDsiWareTitles();
  1021. for (int a = 0; a < dsiWareItems.Length; a++)
  1022. {
  1023. dsiWareItems[a].DropDownItemClicked += new ToolStripItemClickedEventHandler(DatabaseItem_Clicked);
  1024. for (int b = 0; b < dsiWareItems[a].DropDownItems.Count; b++)
  1025. {
  1026. ToolStripMenuItem lowerentry = (ToolStripMenuItem)dsiWareItems[a].DropDownItems[b];
  1027. if (lowerentry.DropDownItems.Count > 0)
  1028. {
  1029. lowerentry.DropDownItemClicked += new ToolStripItemClickedEventHandler(DatabaseItem_Clicked);
  1030. }
  1031. }
  1032. }
  1033. Array.Sort(dsiWareItems, delegate(ToolStripMenuItem tsmi1, ToolStripMenuItem tsmi2)
  1034. {
  1035. return tsmi1.Text
  1036. .Substring(18, tsmi1.Text.Length - 19).CompareTo(tsmi2.Text.Substring(18, tsmi2.Text.Length - 19));
  1037. });
  1038. AddToolStripItemToStrip(dSiWareToolStripMenu, dsiWareItems);
  1039. SetPropertyThreadSafe(dSiWareFakeToolStripMenu, false, "Visible");
  1040. SetPropertyThreadSafe(dSiWareToolStripMenu, true, "Visible");
  1041. Debug.WriteLine("Database: DSiWareTitles added");
  1042. worker.ReportProgress(100);
  1043. }
  1044. /// <summary>
  1045. /// Adds the tool strip item to strip.
  1046. /// </summary>
  1047. /// <param name="type">The type.</param>
  1048. /// <param name="additionitem">The additionitem.</param>
  1049. /// <param name="attributes">The attributes.</param>
  1050. // private void AddToolStripItemToStrip(ToolStripMenuItem menulist, ToolStripMenuItem additionitem)
  1051. private void AddToolStripItemToStrip(ToolStripMenuItem menulist, ToolStripMenuItem[] additionitems)
  1052. {
  1053. //Control.CheckForIllegalCrossThreadCalls = false;
  1054. //Debug.WriteLine(String.Format("Adding item"));
  1055. if (this.InvokeRequired)
  1056. {
  1057. //Debug.WriteLine("InvokeRequired...");
  1058. AddToolStripItemToStripCallback atsitsc = new AddToolStripItemToStripCallback(AddToolStripItemToStrip);
  1059. this.Invoke(atsitsc, new object[] { menulist, additionitems });
  1060. return;
  1061. }
  1062. menulist.DropDownItems.AddRange(additionitems);
  1063. /*
  1064. // Do not sort IOS menu (alphabetization fail)
  1065. if (menulist.Text == IOSMenuList.Text)
  1066. {
  1067. menulist.DropDownItems.Add(additionitem);
  1068. return;
  1069. }
  1070. if (menulist.DropDownItems.Count < 1)
  1071. {
  1072. menulist.DropDownItems.Add(additionitem);
  1073. return;
  1074. }
  1075. // Sorting of items by name 18 chars in...
  1076. //try
  1077. //{
  1078. for (int a = 0; a < menulist.DropDownItems.Count; a++)
  1079. {
  1080. if (menulist.DropDownItems[a].Text
  1081. .Substring(18, menulist.DropDownItems[a].Text.Length - 19)
  1082. .CompareTo(additionitem.Text.Substring(18, additionitem.Text.Length - 19)) == 1)
  1083. {
  1084. menulist.DropDownItems.Insert((a), additionitem);
  1085. return;
  1086. }
  1087. }
  1088. //}
  1089. //catch (Exception)
  1090. //{
  1091. //Debug.WriteLine("Tryfail at : " + additionitem.Text);
  1092. //menulist.DropDownItems.Add(additionitem);
  1093. //}*/
  1094. //menulist.DropDownItems.Add(additionitem);
  1095. }
  1096. /// <summary>
  1097. /// Mods WAD names to be official.
  1098. /// </summary>
  1099. /// <param name="titlename">The titlename.</param>
  1100. public string OfficialWADNaming(string titlename)
  1101. {
  1102. if (titlename == "MIOS")
  1103. titlename = "RVL-mios-[v].wad";
  1104. else if (titlename.Contains("IOS"))
  1105. titlename = titlename + "-64-[v].wad";
  1106. else if (titlename.Contains("System Menu"))
  1107. titlename = "RVL-WiiSystemmenu-[v].wad";
  1108. else if (titlename.Contains("System Menu"))
  1109. titlename = "RVL-WiiSystemmenu-[v].wad";
  1110. else if (titlename == "BC")
  1111. titlename = "RVL-bc-[v].wad";
  1112. else if (titlename.Contains("Mii Channel"))
  1113. titlename = "RVL-NigaoeNR-[v].wad";
  1114. else if (titlename.Contains("Shopping Channel"))
  1115. titlename = "RVL-Shopping-[v].wad";
  1116. else if (titlename.Contains("Weather Channel"))
  1117. titlename = "RVL-Weather-[v].wad";
  1118. else
  1119. titlename = titlename + "-NUS-[v].wad";
  1120. if (wadnamebox.InvokeRequired)
  1121. {
  1122. OfficialWADNamingCallback ownc = new OfficialWADNamingCallback(OfficialWADNaming);
  1123. wadnamebox.Invoke(ownc, new object[] { titlename });
  1124. return titlename;
  1125. }
  1126. wadnamebox.Text = titlename;
  1127. if (titleversion.Text != "")
  1128. wadnamebox.Text = wadnamebox.Text.Replace("[v]", "v" + titleversion.Text);
  1129. return titlename;
  1130. }
  1131. /*
  1132. private void upditem_itemclicked(object sender, ToolStripItemClickedEventArgs e)
  1133. {
  1134. WriteStatus("Preparing to run download script...");
  1135. //script_mode = true;
  1136. SetTextThreadSafe(statusbox, "");
  1137. //WriteStatus("Starting script download. Please be patient!");
  1138. string[] NUS_Entries = e.ClickedItem.AccessibleDescription.Split('\n');
  1139. // TODO: Find somewhere better to put this. AND FAST!
  1140. for (int i = 0; i < NUS_Entries.Length; i++)
  1141. {
  1142. WriteStatus(NUS_Entries[i]);
  1143. }
  1144. script_filename = "\000";
  1145. nusentries = NUS_Entries;
  1146. BackgroundWorker scripter = new BackgroundWorker();
  1147. scripter.DoWork += new DoWorkEventHandler(RunScript);
  1148. scripter.RunWorkerAsync();
  1149. }*/
  1150. public void DatabaseItem_Clicked(object sender, ToolStripItemClickedEventArgs e)
  1151. {
  1152. Regex IdandTitle = new Regex(@"[0-9A-Z]*\s-\s.*");
  1153. Regex RegionEntry = new Regex(@"[0-9A-Z][0-9A-Z] \(.*\)");
  1154. Regex VersionEntry = new Regex(@"v[0-9]*.*");
  1155. object[] wiiMenuLists = new object[] {
  1156. SystemMenuList, IOSMenuList, WiiWareMenuList, VCMenuList
  1157. };
  1158. object[] dsiMenuLists = new object[] {
  1159. dsiSystemToolStripMenu, dSiWareToolStripMenu
  1160. };
  1161. // This item is a Titleid - Descname entry
  1162. if (IdandTitle.IsMatch(e.ClickedItem.Text))
  1163. {
  1164. string text = e.ClickedItem.Text.Replace(" - ", "~");
  1165. string[] values = text.Split('~');
  1166. titleidbox.Text = values[0];
  1167. statusbox.Text = String.Format(" --- {0} ---", values[1]);
  1168. titleversion.Text = String.Empty;
  1169. if ((e.ClickedItem.Image) == (Database.orange) || (e.ClickedItem.Image) == (Database.redorange))
  1170. {
  1171. WriteStatus("Note: This title has no ticket and cannot be packed/decrypted!");
  1172. packbox.Checked = false;
  1173. decryptbox.Checked = false;
  1174. }
  1175. // Check for danger item
  1176. if ((e.ClickedItem.Image) == (Database.redgreen) || (e.ClickedItem.Image) == (Database.redorange))
  1177. WriteStatus("\n" + e.ClickedItem.ToolTipText);
  1178. // Set server selection
  1179. foreach (System.Windows.Forms.ToolStripMenuItem tsmi in wiiMenuLists)
  1180. {
  1181. if (tsmi.Name == e.ClickedItem.OwnerItem.Name)
  1182. serverLbl.Text = "Wii";
  1183. }
  1184. foreach (System.Windows.Forms.ToolStripMenuItem tsmi in dsiMenuLists)
  1185. {
  1186. if (tsmi.Name == e.ClickedItem.OwnerItem.Name)
  1187. serverLbl.Text = "DSi";
  1188. }
  1189. }
  1190. // Region ClickedItem
  1191. if (RegionEntry.IsMatch(e.ClickedItem.Text))
  1192. {
  1193. string text = e.ClickedItem.OwnerItem.Text.Replace(" - ", "~");
  1194. string[] values = text.Split('~');
  1195. titleidbox.Text = values[0];
  1196. statusbox.Text = String.Format(" --- {0} ---", values[1]);
  1197. titleversion.Text = String.Empty;
  1198. // Put 'XX' into title ID
  1199. titleidbox.Text = titleidbox.Text.Replace("XX", e.ClickedItem.Text.Substring(0, 2));
  1200. if ((e.ClickedItem.OwnerItem.Image) == (Database.orange) || (e.ClickedItem.OwnerItem.Image) == (Database.redorange))
  1201. {
  1202. WriteStatus("Note: This title has no ticket and cannot be packed/decrypted!");
  1203. packbox.Checked = false;
  1204. decryptbox.Checked = false;
  1205. }
  1206. // Check for danger item
  1207. if ((e.ClickedItem.OwnerItem.Image) == (Database.redgreen) || (e.ClickedItem.OwnerItem.Image) == (Database.redorange))
  1208. WriteStatus("\n" + e.ClickedItem.OwnerItem.ToolTipText);
  1209. // Set server selection
  1210. foreach (System.Windows.Forms.ToolStripMenuItem tsmi in wiiMenuLists)
  1211. {
  1212. if (tsmi.Name == e.ClickedItem.OwnerItem.OwnerItem.Name)
  1213. serverLbl.Text = "Wii";
  1214. }
  1215. foreach (System.Windows.Forms.ToolStripMenuItem tsmi in dsiMenuLists)
  1216. {
  1217. if (tsmi.Name == e.ClickedItem.OwnerItem.OwnerItem.Name)
  1218. serverLbl.Text = "DSi";
  1219. }
  1220. }
  1221. // Version ClickedItem
  1222. if (VersionEntry.IsMatch(e.ClickedItem.Text) || e.ClickedItem.Text == "Latest Version")
  1223. {
  1224. if (RegionEntry.IsMatch(e.ClickedItem.OwnerItem.Text))
  1225. {
  1226. string text = e.ClickedItem.OwnerItem.OwnerItem.Text.Replace(" - ", "~");
  1227. string[] values = text.Split('~');
  1228. titleidbox.Text = values[0];
  1229. statusbox.Text = String.Format(" --- {0} ---", values[1]);
  1230. // Put 'XX' into title ID
  1231. titleidbox.Text = titleidbox.Text.Replace("XX", e.ClickedItem.OwnerItem.Text.Substring(0, 2));
  1232. }
  1233. else
  1234. {
  1235. string text = e.ClickedItem.OwnerItem.Text.Replace(" - ", "~");
  1236. string[] values = text.Split('~');
  1237. titleidbox.Text = values[0];
  1238. statusbox.Text = String.Format(" --- {0} ---", values[1]);
  1239. }
  1240. // Set version
  1241. if (e.ClickedItem.Text == "Latest Version")
  1242. titleversion.Text = String.Empty;
  1243. else
  1244. {
  1245. string[] version = e.ClickedItem.Text.Replace("v", "").Split(' ');
  1246. titleversion.Text = version[0];
  1247. }
  1248. if (RegionEntry.IsMatch(e.ClickedItem.OwnerItem.Text))
  1249. {
  1250. if ((e.ClickedItem.OwnerItem.OwnerItem.Image) == (Database.orange) || (e.ClickedItem.OwnerItem.OwnerItem.Image) == (Database.redorange))
  1251. {
  1252. WriteStatus("Note: This title has no ticket and cannot be packed/decrypted!");
  1253. packbox.Checked = false;
  1254. decryptbox.Checked = false;
  1255. }
  1256. // Check for danger item
  1257. if ((e.ClickedItem.OwnerItem.OwnerItem.Image) == (Database.redgreen) || (e.ClickedItem.OwnerItem.OwnerItem.Image) == (Database.redorange))
  1258. WriteStatus("\n" + e.ClickedItem.OwnerItem.OwnerItem.ToolTipText);
  1259. // Set server selection
  1260. foreach (System.Windows.Forms.ToolStripMenuItem tsmi in wiiMenuLists)
  1261. {
  1262. if (tsmi.Name == e.ClickedItem.OwnerItem.OwnerItem.OwnerItem.Name)
  1263. serverLbl.Text = "Wii";
  1264. }
  1265. foreach (System.Windows.Forms.ToolStripMenuItem tsmi in dsiMenuLists)
  1266. {
  1267. if (tsmi.Name == e.ClickedItem.OwnerItem.OwnerItem.OwnerItem.Name)
  1268. serverLbl.Text = "DSi";
  1269. }
  1270. }
  1271. else
  1272. {
  1273. if ((e.ClickedItem.OwnerItem.Image) == (Database.orange) || (e.ClickedItem.OwnerItem.Image) == (Database.redorange))
  1274. {
  1275. WriteStatus("Note: This title has no ticket and cannot be packed/decrypted!");
  1276. packbox.Checked = false;
  1277. decryptbox.Checked = false;
  1278. }
  1279. // Check for danger item
  1280. if ((e.ClickedItem.OwnerItem.Image) == (Database.redgreen) || (e.ClickedItem.OwnerItem.Image) == (Database.redorange))
  1281. WriteStatus("\n" + e.ClickedItem.OwnerItem.ToolTipText);
  1282. // Set server selection
  1283. foreach (System.Windows.Forms.ToolStripMenuItem tsmi in wiiMenuLists)
  1284. {
  1285. if (tsmi.Name == e.ClickedItem.OwnerItem.OwnerItem.Name)
  1286. serverLbl.Text = "Wii";
  1287. }
  1288. foreach (System.Windows.Forms.ToolStripMenuItem tsmi in dsiMenuLists)
  1289. {
  1290. if (tsmi.Name == e.ClickedItem.OwnerItem.OwnerItem.Name)
  1291. serverLbl.Text = "DSi";
  1292. }
  1293. }
  1294. }
  1295. }
  1296. /// <summary>
  1297. /// Gathers the region based on index
  1298. /// </summary>
  1299. /// <param name="index">The index.</param>
  1300. /// <param name="databasexml">XmlDocument with database inside</param>
  1301. /// <returns>Region desc</returns>
  1302. private string RegionFromIndex(int index, XmlDocument databasexml)
  1303. {
  1304. /* Typical Region XML
  1305. * <REGIONS>
  1306. <region index="0">41 (All/System)</region>
  1307. <region index=1>44 (German)</region>
  1308. <region index=2>45 (USA/NTSC)</region>
  1309. <region index=3>46 (French)</region>
  1310. <region index=4>4A (Japan)</region>
  1311. <region index=5>4B (Korea)</region>
  1312. <region index=6>4C (Japanese Import to Europe/Australia/PAL)</region>
  1313. <region index=7>4D (American Import to Europe/Australia/PAL)</region>
  1314. <region index=8>4E (Japanese Import to USA/NTSC)</region>
  1315. <region index=9>50 (Europe/PAL)</region>
  1316. <region index=10>51 (Korea w/ Japanese Language)</region>
  1317. <region index=11>54 (Korea w/ English Language)</region>
  1318. <region index=12>58 (Some Homebrew)</region>
  1319. </REGIONS>
  1320. */
  1321. XmlNodeList XMLRegionList = databasexml.GetElementsByTagName("REGIONS");
  1322. XmlNodeList ChildrenOfTheNode = XMLRegionList[0].ChildNodes;
  1323. // For each child node (region node)
  1324. for (int z = 0; z < ChildrenOfTheNode.Count; z++)
  1325. {
  1326. // Gather attributes (index='x')
  1327. XmlAttributeCollection XMLAttributes = ChildrenOfTheNode[z].Attributes;
  1328. // Return value of node if index matches
  1329. if (Convert.ToInt32(XMLAttributes[0].Value) == index)
  1330. return ChildrenOfTheNode[z].InnerText;
  1331. }
  1332. return "XX (Error)";
  1333. }
  1334. /// <summary>
  1335. /// Loads the region codes.
  1336. /// </summary>
  1337. private void LoadRegionCodes()
  1338. {
  1339. // TODO: make this check InvokeRequired...
  1340. if (this.InvokeRequired)
  1341. {
  1342. BootChecksCallback bcc = new BootChecksCallback(LoadRegionCodes);
  1343. this.Invoke(bcc);
  1344. return;
  1345. }
  1346. wiiRegionCodesMenu.DropDownItems.Clear();
  1347. dsiRegionCodesMenu.DropDownItems.Clear();
  1348. Database databaseObj = new Database();
  1349. databaseObj.LoadDatabaseToStream(Path.Combine(CURRENT_DIR, "database.xml"));
  1350. ToolStripMenuItem[] regionItems = databaseObj.LoadRegionCodes();
  1351. // For each child node (region node)
  1352. for (int z = 0; z < regionItems.Length; z++)
  1353. {
  1354. wiiRegionCodesMenu.DropDownItems.Add(regionItems[z].Text);
  1355. }
  1356. Database dsiDatabaseObj = new Database();
  1357. dsiDatabaseObj.LoadDatabaseToStream(Path.Combine(CURRENT_DIR, "dsidatabase.xml"));
  1358. ToolStripMenuItem[] dsiRegionItems = dsiDatabaseObj.LoadRegionCodes();
  1359. // For each child node (region node)
  1360. for (int z = 0; z < dsiRegionItems.Length; z++)
  1361. {
  1362. dsiRegionCodesMenu.DropDownItems.Add(dsiRegionItems[z].Text);
  1363. }
  1364. }
  1365. /// <summary>
  1366. /// Removes the illegal characters.
  1367. /// </summary>
  1368. /// <param name="databasestr">removes the illegal chars</param>
  1369. /// <returns>legal string</returns>
  1370. private static string RemoveIllegalCharacters(string databasestr)
  1371. {
  1372. // Database strings must contain filename-legal characters.
  1373. foreach (char illegalchar in System.IO.Path.GetInvalidFileNameChars())
  1374. {
  1375. if (databasestr.Contains(illegalchar.ToString()))
  1376. databasestr = databasestr.Replace(illegalchar, '-');
  1377. }
  1378. return databasestr;
  1379. }
  1380. private void ClearStatusbox(object sender, EventArgs e)
  1381. {
  1382. // Clear Statusbox.text
  1383. statusbox.Text = "";
  1384. }
  1385. /// <summary>
  1386. /// Makes everything disabled/enabled.
  1387. /// </summary>
  1388. /// <param name="enabled">if set to <c>true</c> [enabled].</param>
  1389. private void SetEnableforDownload(bool enabled)
  1390. {
  1391. if (this.InvokeRequired)
  1392. {
  1393. SetEnableForDownloadCallback sefdcb = new SetEnableForDownloadCallback(SetEnableforDownload);
  1394. this.Invoke(sefdcb, new object[] { enabled });
  1395. return;
  1396. }
  1397. // Disable things the user should not mess with during download...
  1398. downloadstartbtn.Enabled = enabled;
  1399. titleidbox.Enabled = enabled;
  1400. titleversion.Enabled = enabled;
  1401. Extrasbtn.Enabled = enabled;
  1402. databaseButton.Enabled = enabled;
  1403. packbox.Enabled = enabled;
  1404. localuse.Enabled = enabled;
  1405. saveaswadbtn.Enabled = enabled;
  1406. decryptbox.Enabled = enabled;
  1407. keepenccontents.Enabled = enabled;
  1408. scriptsbutton.Enabled = enabled;
  1409. serverLbl.Enabled = enabled;
  1410. iosPatchCheckbox.Enabled = enabled;
  1411. }
  1412. /// <summary>
  1413. /// Makes tooltips disappear in the database, as many contain danger tag info.
  1414. /// </summary>
  1415. /// <param name="enabled">if set to <c>true</c> [enabled].</param>
  1416. private void ShowInnerToolTips(bool enabled)
  1417. {
  1418. // Force tooltips to GTFO in sub menus...
  1419. foreach (ToolStripItem item in databaseStrip.Items)
  1420. {
  1421. try
  1422. {
  1423. ToolStripMenuItem menuitem = (ToolStripMenuItem) item;
  1424. menuitem.DropDown.ShowItemToolTips = false;
  1425. }
  1426. catch (Exception)
  1427. {
  1428. // Do nothing, some objects will not cast.
  1429. }
  1430. }
  1431. foreach (ToolStripItem item in scriptsStrip.Items)
  1432. {
  1433. try
  1434. {
  1435. ToolStripMenuItem menuitem = (ToolStripMenuItem)item;
  1436. menuitem.DropDown.ShowItemToolTips = false;
  1437. }
  1438. catch (Exception)
  1439. {
  1440. // Do nothing, some objects will not cast.
  1441. }
  1442. }
  1443. }
  1444. /// <summary>
  1445. /// Updates the name of the packed WAD in the textbox.
  1446. /// </summary>
  1447. private void UpdatePackedName()
  1448. {
  1449. // Change WAD name if applicable
  1450. string title_name = null;
  1451. if ((titleidbox.Enabled == true) && (packbox.Checked == true))
  1452. {
  1453. if (titleversion.Text != "")
  1454. {
  1455. wadnamebox.Text = titleidbox.Text + "-NUS-v" + titleversion.Text + ".wad";
  1456. }
  1457. else
  1458. {
  1459. wadnamebox.Text = titleidbox.Text + "-NUS-[v]" + titleversion.Text + ".wad";
  1460. }
  1461. if ((File.Exists("database.xml") == true) && (titleidbox.Text.Length == 16))
  1462. title_name = NameFromDatabase(titleidbox.Text);
  1463. if (title_name != null)
  1464. {
  1465. wadnamebox.Text = wadnamebox.Text.Replace(titleidbox.Text, title_name);
  1466. OfficialWADNaming(title_name);
  1467. }
  1468. }
  1469. wadnamebox.Text = RemoveIllegalCharacters(wadnamebox.Text);
  1470. }
  1471. /// <summary>
  1472. /// Determines whether OS is win7.
  1473. /// </summary>
  1474. /// <returns>
  1475. /// <c>true</c> if OS = win7; otherwise, <c>false</c>.
  1476. /// </returns>
  1477. private static bool IsWin7()
  1478. {
  1479. return (Environment.OSVersion.VersionString.Contains("6.1") == true);
  1480. }
  1481. private byte[] NewIntegertoByteArray(int theInt, int arrayLen)
  1482. {
  1483. byte[] resultArray = new byte[arrayLen];
  1484. for (int i = arrayLen - 1; i >= 0; i--)
  1485. {
  1486. resultArray[i] = (byte) ((theInt >> (8*i)) & 0xFF);
  1487. }
  1488. Array.Reverse(resultArray);
  1489. // Fix duplication, rewrite extra to 0x00;
  1490. if (arrayLen > 4)
  1491. {
  1492. for (int i = 0; i < (arrayLen - 4); i++)
  1493. {
  1494. resultArray[i] = 0x00;
  1495. }
  1496. }
  1497. return resultArray;
  1498. }
  1499. private WebClient ConfigureWithProxy(WebClient client)
  1500. {
  1501. // Proxy
  1502. if (!(String.IsNullOrEmpty(proxy_url)))
  1503. {
  1504. WebProxy customproxy = new WebProxy();
  1505. customproxy.Address = new Uri(proxy_url);
  1506. if (String.IsNullOrEmpty(proxy_usr))
  1507. customproxy.UseDefaultCredentials = true;
  1508. else
  1509. {
  1510. NetworkCredential cred = new NetworkCredential();
  1511. cred.UserName = proxy_usr;
  1512. if (!(String.IsNullOrEmpty(proxy_pwd)))
  1513. cred.Password = proxy_pwd;
  1514. customproxy.Credentials = cred;
  1515. }
  1516. client.Proxy = customproxy;
  1517. WriteStatus(" - Custom proxy settings applied!");
  1518. }
  1519. else
  1520. {
  1521. try
  1522. {
  1523. client.Proxy = WebRequest.GetSystemWebProxy();
  1524. client.UseDefaultCredentials = true;
  1525. }
  1526. catch (NotImplementedException)
  1527. {
  1528. // Linux support
  1529. WriteStatus("This operating system does not support automatic system proxy usage. Operating without a proxy...");
  1530. }
  1531. }
  1532. return client;
  1533. }
  1534. /// <summary>
  1535. /// Retrieves the new database file.
  1536. /// </summary>
  1537. /// <returns>Database as a String</returns>
  1538. private void RetrieveNewDatabase(object sender, DoWorkEventArgs e)
  1539. {
  1540. // Retrieve Wiibrew/DSiBrew database page source code
  1541. WebClient databasedl = new WebClient();
  1542. // Proxy
  1543. //databasedl = ConfigureWithProxy(databasedl);
  1544. string databaseSource =
  1545. databasedl.DownloadString(e.Argument.ToString() + "?cachesmash=" +
  1546. System.DateTime.Now.ToString());
  1547. // Strip out HTML
  1548. databaseSource = Regex.Replace(databaseSource, @"<(.|\n)*?>", "");
  1549. // Shrink to fix only the database
  1550. string startofdatabase = "&lt;database v";
  1551. string endofdatabase = "&lt;/database&gt;";
  1552. databaseSource = databaseSource.Substring(databaseSource.IndexOf(startofdatabase),
  1553. databaseSource.Length - databaseSource.IndexOf(startofdatabase));
  1554. databaseSource = databaseSource.Substring(0, databaseSource.IndexOf(endofdatabase) + endofdatabase.Length);
  1555. // Fix ", <, >, and spaces
  1556. databaseSource = databaseSource.Replace("&lt;", "<");
  1557. databaseSource = databaseSource.Replace("&gt;", ">");
  1558. databaseSource = databaseSource.Replace("&quot;", '"'.ToString());
  1559. databaseSource = databaseSource.Replace("&nbsp;", " "); // Shouldn't occur, but they happen...
  1560. // Return parsed xml database...
  1561. e.Result = databaseSource;
  1562. }
  1563. private void RetrieveNewDatabase_Completed(object sender, RunWorkerCompletedEventArgs e)
  1564. {
  1565. string database = e.Result.ToString();
  1566. string databaseFilename = "";
  1567. if (database.Contains("DSISYSTEM"))
  1568. {
  1569. databaseFilename = "dsidatabase.xml";
  1570. }
  1571. else if (database.Contains("0000000100000002"))
  1572. {
  1573. databaseFilename = "database.xml";
  1574. }
  1575. try
  1576. {
  1577. Database db = new Database();
  1578. db.LoadDatabaseToStream(Path.Combine(CURRENT_DIR, databaseFilename));
  1579. string currentversion = db.GetDatabaseVersion();
  1580. string onlineversion = Database.GetDatabaseVersion(database);
  1581. WriteStatus(String.Format(" - Database successfully parsed! ({0})", databaseFilename));
  1582. WriteStatus(" - Current Database Version: " + currentversion);
  1583. WriteStatus(" - Online Database Version: " + onlineversion);
  1584. if (currentversion == onlineversion)
  1585. {
  1586. WriteStatus(" - You have the latest database version!");
  1587. return;
  1588. }
  1589. }
  1590. catch (FileNotFoundException)
  1591. {
  1592. WriteStatus(" - Database does not yet exist.");
  1593. WriteStatus(" - Online Database Version: " + Database.GetDatabaseVersion(database));
  1594. }
  1595. bool isCreation = false;
  1596. if (File.Exists(databaseFilename))
  1597. {
  1598. WriteStatus(" - Overwriting your current database...");
  1599. WriteStatus(String.Format(" - The old database will become 'old{0}' in case the new one is faulty.", databaseFilename));
  1600. string olddatabase = File.ReadAllText(databaseFilename);
  1601. File.WriteAllText("old" + databaseFilename, olddatabase);
  1602. File.Delete(databaseFilename);
  1603. File.WriteAllText(databaseFilename, database);
  1604. }
  1605. else
  1606. {
  1607. WriteStatus(String.Format(" - {0} has been created.", databaseFilename));
  1608. File.WriteAllText(databaseFilename, database);
  1609. isCreation = true;
  1610. }
  1611. // Load it up...
  1612. this.databaseWorker.RunWorkerAsync();
  1613. if (isCreation)
  1614. {
  1615. WriteStatus("Database successfully created!");
  1616. databaseButton.Visible = true;
  1617. //databaseButton.Enabled = false;
  1618. updateDatabaseToolStripMenuItem.Text = "Download Database";
  1619. }
  1620. else
  1621. {
  1622. WriteStatus("Database successfully updated!");
  1623. }
  1624. }
  1625. private void updateDatabaseToolStripMenuItem_Click(object sender, EventArgs e)
  1626. {
  1627. statusbox.Text = "";
  1628. WriteStatus("Updating your databases from Wiibrew/DSibrew");
  1629. string[] wiibrewValues = new string[] { "http://www.wiibrew.org/wiki/NUS_Downloader/database", "http://www.dsibrew.org/wiki/NUS_Downloader/database" };
  1630. BackgroundWorker dbFetcher = new BackgroundWorker();
  1631. dbFetcher.DoWork += new DoWorkEventHandler(RetrieveNewDatabase);
  1632. dbFetcher.RunWorkerCompleted += new RunWorkerCompletedEventHandler(RetrieveNewDatabase_Completed);
  1633. dbFetcher.RunWorkerAsync(wiibrewValues[0]);
  1634. BackgroundWorker dbDsiFetcher = new BackgroundWorker();
  1635. dbDsiFetcher.DoWork += new DoWorkEventHandler(RetrieveNewDatabase);
  1636. dbDsiFetcher.RunWorkerCompleted += new RunWorkerCompletedEventHandler(RetrieveNewDatabase_Completed);
  1637. dbDsiFetcher.RunWorkerAsync(wiibrewValues[1]);
  1638. }
  1639. private void loadInfoFromTMDToolStripMenuItem_Click(object sender, EventArgs e)
  1640. {
  1641. // Extras menu -> Load TMD...
  1642. LoadTitleFromTMD();
  1643. }
  1644. /// <summary>
  1645. /// Sends the SOAP request to NUS.
  1646. /// </summary>
  1647. /// <param name="soap_xml">The Request</param>
  1648. /// <returns></returns>
  1649. public string SendSOAPRequest(string soap_xml)
  1650. {
  1651. System.Net.HttpWebRequest req =
  1652. (System.Net.HttpWebRequest)
  1653. System.Net.HttpWebRequest.Create("http://nus.shop.wii.com:80/nus/services/NetUpdateSOAP");
  1654. req.Method = "POST";
  1655. req.UserAgent = "wii libnup/1.0";
  1656. req.Headers.Add("SOAPAction", '"' + "urn:nus.wsapi.broadon.com/" + '"');
  1657. // Proxy
  1658. if (!(String.IsNullOrEmpty(proxy_url)))
  1659. {
  1660. WebProxy customproxy = new WebProxy();
  1661. customproxy.Address = new Uri(proxy_url);
  1662. if (String.IsNullOrEmpty(proxy_usr))
  1663. customproxy.UseDefaultCredentials = true;
  1664. else
  1665. {
  1666. NetworkCredential cred = new NetworkCredential();
  1667. cred.UserName = proxy_usr;
  1668. if (!(String.IsNullOrEmpty(proxy_pwd)))
  1669. cred.Password = proxy_pwd;
  1670. customproxy.Credentials = cred;
  1671. }
  1672. req.Proxy = customproxy;
  1673. WriteStatus(" - Custom proxy settings applied!");
  1674. }
  1675. else
  1676. {
  1677. req.Proxy = WebRequest.GetSystemWebProxy();
  1678. req.UseDefaultCredentials = true;
  1679. }
  1680. Stream writeStream = req.GetRequestStream();
  1681. UTF8Encoding encoding = new UTF8Encoding();
  1682. byte[] bytes = encoding.GetBytes(soap_xml);
  1683. req.ContentType = "text/xml; charset=utf-8";
  1684. //req.ContentLength = bytes.Length;
  1685. writeStream.Write(bytes, 0, bytes.Length);
  1686. writeStream.Close();
  1687. Application.DoEvents();
  1688. try
  1689. {
  1690. string result;
  1691. System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse) req.GetResponse();
  1692. using (Stream responseStream = resp.GetResponseStream())
  1693. {
  1694. using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
  1695. {
  1696. result = readStream.ReadToEnd();
  1697. }
  1698. }
  1699. req.Abort();
  1700. Application.DoEvents();
  1701. return result;
  1702. }
  1703. catch (Exception ex)
  1704. {
  1705. req.Abort();
  1706. return ex.Message.ToString();
  1707. }
  1708. }
  1709. private void emulateUpdate_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
  1710. {
  1711. // Begin Wii System Update
  1712. statusbox.Text = "";
  1713. WriteStatus("Starting Wii System Update...");
  1714. scriptsStrip.Close();
  1715. string deviceID = "4362227770";
  1716. string messageID = "13198105123219138";
  1717. string attr = "2";
  1718. string RegionID = e.ClickedItem.Text.Substring(0, 3);
  1719. if (RegionID == "JAP") // Japan fix, only region not w/ 1st 3 letters same as ID.
  1720. RegionID = "JPN";
  1721. string CountryCode = RegionID.Substring(0, 2);
  1722. /* [14:26] <Galaxy|> RegionID: USA, Country: US;
  1723. RegionID: JPN, Country: JP;
  1724. RegionID: EUR, Country: EU;
  1725. RegionID: KOR, Country: KO; */
  1726. string soap_req = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"" +
  1727. " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"" +
  1728. " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
  1729. "<soapenv:Body>\n<GetSystemUpdateRequest xmlns=\"urn:nus.wsapi.broadon.com\">\n" +
  1730. "<Version>1.0</Version>\n<MessageId>" + messageID + "</MessageId>\n<DeviceId>" + deviceID +
  1731. "</DeviceId>\n" +
  1732. "<RegionId>" + RegionID + "</RegionId>\n<CountryCode>" + CountryCode +
  1733. "</CountryCode>\n<TitleVersion>\n<TitleId>0000000100000001</TitleId>\n" +
  1734. "<Version>2</Version>\n</TitleVersion>\n<TitleVersion>\n<TitleId>0000000100000002</TitleId>\n" +
  1735. "<Version>33</Version>\n</TitleVersion>\n<TitleVersion>\n<TitleId>0000000100000009</TitleId>\n" +
  1736. "<Version>516</Version>\n</TitleVersion>\n<Attribute>" + attr +
  1737. "</Attribute>\n<AuditData></AuditData>\n" +
  1738. "</GetSystemUpdateRequest>\n</soapenv:Body>\n</soapenv:Envelope>";
  1739. WriteStatus(" - Sending SOAP Request to NUS...");
  1740. WriteStatus(" - Region: " + RegionID);
  1741. string update_xml = SendSOAPRequest(soap_req);
  1742. if (update_xml != null)
  1743. WriteStatus(" - Recieved Update Info!");
  1744. else
  1745. {
  1746. WriteStatus(" - Fail.");
  1747. return;
  1748. }
  1749. WriteStatus(" - Title information:");
  1750. string script_text = "";
  1751. XmlDocument xDoc = new XmlDocument();
  1752. xDoc.LoadXml(update_xml);
  1753. XmlNodeList TitleList = xDoc.GetElementsByTagName("TitleVersion");
  1754. for (int a = 0; a < TitleList.Count; a++)
  1755. {
  1756. XmlNodeList TitleInfo = TitleList[a].ChildNodes;
  1757. string TitleID = "";
  1758. string Version = "";
  1759. for (int b = 0; b < TitleInfo.Count; b++)
  1760. {
  1761. switch (TitleInfo[b].Name)
  1762. {
  1763. case "TitleId":
  1764. TitleID = TitleInfo[b].InnerText;
  1765. break;
  1766. case "Version":
  1767. Version = TitleInfo[b].InnerText;
  1768. break;
  1769. default:
  1770. break;
  1771. }
  1772. }
  1773. WriteStatus(String.Format(" - {0} [v{1}]", TitleID, Version));
  1774. if ((NUSDFileExists("database.xml") == true) && ((!(String.IsNullOrEmpty(NameFromDatabase(TitleID))))))
  1775. //statusbox.Text += String.Format(" [{0}]", NameFromDatabase(TitleID));
  1776. WriteStatus(String.Format(" [{0}]", NameFromDatabase(TitleID)));
  1777. script_text += String.Format("{0} {1}\n", TitleID,
  1778. DisplayBytes(NewIntegertoByteArray(Convert.ToInt32(Version), 2), ""));
  1779. }
  1780. WriteStatus(" - Outputting results to NUS script...");
  1781. if (!(Directory.Exists(Path.Combine(CURRENT_DIR, "scripts"))))
  1782. {
  1783. Directory.CreateDirectory(Path.Combine(CURRENT_DIR, "scripts"));
  1784. WriteStatus(" - Created 'scripts\' directory.");
  1785. }
  1786. string time = RemoveIllegalCharacters(DateTime.Now.ToShortTimeString());
  1787. File.WriteAllText(
  1788. String.Format(Path.Combine(CURRENT_DIR, Path.Combine("scripts","{0}_Update_{1}_{2}_{3} at {4}.nus")), RegionID,
  1789. DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Year, time), script_text);
  1790. WriteStatus(" - Script written!");
  1791. scriptsLocalMenuEntry.Enabled = false;
  1792. this.scriptsWorker.RunWorkerAsync();
  1793. WriteStatus(" - Run this script if you feel like downloading the update!");
  1794. // TODO: run the script...
  1795. }
  1796. /// <summary>
  1797. /// Looks for a title's name by TitleID in Database.
  1798. /// </summary>
  1799. /// <param name="titleid">The titleid.</param>
  1800. /// <returns>Existing name; else null</returns>
  1801. private string NameFromDatabase(string titleid)
  1802. {
  1803. // DANGER: BAD h4x HERE!!
  1804. // Fix MIOS/BC naming
  1805. if (titleid == "0000000100000101")
  1806. return "MIOS";
  1807. else if (titleid == "0000000100000100")
  1808. return "BC";
  1809. XmlDocument xDoc = new XmlDocument();
  1810. xDoc.Load("database.xml");
  1811. // Variables
  1812. string[] XMLNodeTypes = new string[4] {"SYS", "IOS", "VC", "WW"};
  1813. // Loop through XMLNodeTypes
  1814. for (int i = 0; i < XMLNodeTypes.Length; i++) // FOR THE FOUR TYPES OF NODES
  1815. {
  1816. XmlNodeList XMLSpecificNodeTypeList = xDoc.GetElementsByTagName(XMLNodeTypes[i]);
  1817. for (int x = 0; x < XMLSpecificNodeTypeList.Count; x++) // FOR EACH ITEM IN THE LIST OF A NODE TYPE
  1818. {
  1819. bool found_it = false;
  1820. // Lol.
  1821. XmlNodeList ChildrenOfTheNode = XMLSpecificNodeTypeList[x].ChildNodes;
  1822. for (int z = 0; z < ChildrenOfTheNode.Count; z++) // FOR EACH CHILD NODE
  1823. {
  1824. switch (ChildrenOfTheNode[z].Name)
  1825. {
  1826. case "titleID":
  1827. if (ChildrenOfTheNode[z].InnerText == titleid)
  1828. found_it = true;
  1829. else if ((ChildrenOfTheNode[z].InnerText.Substring(0, 14) + "XX") ==
  1830. (titleid.Substring(0, 14) + "XX") &&
  1831. (titleid.Substring(0, 14) != "00000001000000"))
  1832. found_it = true;
  1833. else
  1834. found_it = false;
  1835. break;
  1836. default:
  1837. break;
  1838. }
  1839. }
  1840. if (found_it)
  1841. {
  1842. for (int z = 0; z < ChildrenOfTheNode.Count; z++) // FOR EACH CHILD NODE
  1843. {
  1844. switch (ChildrenOfTheNode[z].Name)
  1845. {
  1846. case "name":
  1847. return ChildrenOfTheNode[z].InnerText;
  1848. default:
  1849. break;
  1850. }
  1851. }
  1852. }
  1853. }
  1854. }
  1855. return null;
  1856. }
  1857. private void packbox_EnabledChanged(object sender, EventArgs e)
  1858. {
  1859. saveaswadbtn.Enabled = packbox.Enabled;
  1860. //deletecontentsbox.Enabled = packbox.Enabled;
  1861. }
  1862. private void SaveProxyBtn_Click(object sender, EventArgs e)
  1863. {
  1864. if ((String.IsNullOrEmpty(ProxyURL.Text)) && (String.IsNullOrEmpty(ProxyUser.Text)) &&
  1865. ((File.Exists(Path.Combine(CURRENT_DIR, "proxy.txt")))))
  1866. {
  1867. File.Delete(Path.Combine(CURRENT_DIR, "proxy.txt"));
  1868. proxyBox.Visible = false;
  1869. proxy_usr = "";
  1870. proxy_url = "";
  1871. proxy_pwd = "";
  1872. WriteStatus("Proxy settings deleted!");
  1873. return;
  1874. }
  1875. else if ((String.IsNullOrEmpty(ProxyURL.Text)) && (String.IsNullOrEmpty(ProxyUser.Text)) &&
  1876. ((!(File.Exists(Path.Combine(CURRENT_DIR, "proxy.txt"))))))
  1877. {
  1878. proxyBox.Visible = false;
  1879. WriteStatus("No proxy settings saved!");
  1880. return;
  1881. }
  1882. string proxy_file = "";
  1883. if (!(String.IsNullOrEmpty(ProxyURL.Text)))
  1884. {
  1885. proxy_file += ProxyURL.Text + "\n";
  1886. proxy_url = ProxyURL.Text;
  1887. }
  1888. if (!(String.IsNullOrEmpty(ProxyUser.Text)))
  1889. {
  1890. proxy_file += ProxyUser.Text;
  1891. proxy_usr = ProxyUser.Text;
  1892. }
  1893. if (!(String.IsNullOrEmpty(proxy_file)))
  1894. {
  1895. File.WriteAllText(Path.Combine(CURRENT_DIR, "proxy.txt"), proxy_file);
  1896. WriteStatus("Proxy settings saved!");
  1897. }
  1898. proxyBox.Visible = false;
  1899. SetAllEnabled(false);
  1900. ProxyVerifyBox.Visible = true;
  1901. ProxyVerifyBox.Enabled = true;
  1902. ProxyPwdBox.Enabled = true;
  1903. SaveProxyBtn.Enabled = true;
  1904. ProxyVerifyBox.Select();
  1905. }
  1906. private void proxySettingsToolStripMenuItem_Click(object sender, EventArgs e)
  1907. {
  1908. // Check for Proxy Settings file...
  1909. if (File.Exists(Path.Combine(CURRENT_DIR, "proxy.txt")) == true)
  1910. {
  1911. string[] proxy_file = File.ReadAllLines(Path.Combine(CURRENT_DIR, "proxy.txt"));
  1912. ProxyURL.Text = proxy_file[0];
  1913. if (proxy_file.Length > 1)
  1914. {
  1915. ProxyUser.Text = proxy_file[1];
  1916. }
  1917. }
  1918. proxyBox.Visible = true;
  1919. }
  1920. private void SaveProxyPwdButton_Click(object sender, EventArgs e)
  1921. {
  1922. proxy_pwd = ProxyPwdBox.Text;
  1923. ProxyVerifyBox.Visible = false;
  1924. SetAllEnabled(true);
  1925. }
  1926. private void ProxyPwdBox_KeyPress(object sender, KeyPressEventArgs e)
  1927. {
  1928. if (e.KeyChar == Convert.ToChar(Keys.Enter))
  1929. SaveProxyPwdButton_Click("LOLWUT", EventArgs.Empty);
  1930. }
  1931. private void ProxyAssistBtn_Click(object sender, EventArgs e)
  1932. {
  1933. MessageBox.Show("If you are behind a proxy, set these settings to get through to NUS." +
  1934. " If you have an alternate port for accessing your proxy, add ':' followed by the port.");
  1935. }
  1936. private void loadNUSScriptToolStripMenuItem_Click(object sender, EventArgs e)
  1937. {
  1938. // Open a NUS script.
  1939. OpenFileDialog ofd = new OpenFileDialog();
  1940. ofd.Multiselect = false;
  1941. ofd.Filter = "NUS Scripts|*.nus|All Files|*.*";
  1942. if (Directory.Exists(Path.Combine(CURRENT_DIR, "scripts")))
  1943. ofd.InitialDirectory = Path.Combine(CURRENT_DIR, "scripts");
  1944. ofd.Title = "Load a NUS/Wiimpersonator script.";
  1945. if (ofd.ShowDialog() != DialogResult.Cancel)
  1946. {
  1947. string script_content = File.ReadAllText(ofd.FileName);
  1948. FileInfo script_file = new FileInfo(ofd.FileName);
  1949. script_content += String.Format(";{0}", script_file.Name.Replace("." + script_file.Extension, ""));
  1950. BackgroundWorker scripter = new BackgroundWorker();
  1951. scripter.DoWork += new DoWorkEventHandler(RunScriptBg);
  1952. scripter.RunWorkerAsync(script_content);
  1953. }
  1954. }
  1955. /// <summary>
  1956. /// Runs a NUS script (BG).
  1957. /// </summary>
  1958. /// <param name="sender">The sender.</param>
  1959. /// <param name="e">The <see cref="System.ComponentModel.DoWorkEventArgs"/> instance containing the event data.</param>
  1960. private void RunScriptBg(object sender, System.ComponentModel.DoWorkEventArgs e)
  1961. {
  1962. char ArgsSplitChar = ';';
  1963. string[] scriptArgs = e.Argument.ToString().Split(ArgsSplitChar);
  1964. if (scriptArgs.Length < 2)
  1965. RunScript(scriptArgs[0], "random");
  1966. else
  1967. {
  1968. RunScript(scriptArgs[0], RemoveIllegalCharacters(scriptArgs[1]));
  1969. }
  1970. /*
  1971. script_mode = true;
  1972. SetTextThreadSafe(statusbox, "");
  1973. WriteStatus("Starting script download. Please be patient!");
  1974. if (!File.Exists(Path.Combine(CURRENT_DIR, "output_" + Path.GetFileNameWithoutExtension(script_filename))))
  1975. Directory.CreateDirectory(Path.Combine(CURRENT_DIR, "output_" + Path.GetFileNameWithoutExtension(script_filename)));
  1976. string[] NUS_Entries;
  1977. if (script_filename != "\000")
  1978. {
  1979. NUS_Entries = File.ReadAllLines(script_filename);
  1980. }
  1981. else
  1982. {
  1983. NUS_Entries = nusentries;
  1984. }
  1985. WriteStatus(String.Format(" - Script loaded ({0} Titles)", NUS_Entries.Length));
  1986. for (int a = 0; a < NUS_Entries.Length; a++)
  1987. {
  1988. // Download the title
  1989. WriteStatus(String.Format("===== Running Download ({0}/{1}) =====", a + 1, NUS_Entries.Length));
  1990. string[] title_info = NUS_Entries[a].Split(' ');
  1991. // don't let the delete issue reappear...
  1992. if (string.IsNullOrEmpty(title_info[0]))
  1993. break;
  1994. // WebClient configuration
  1995. WebClient nusWC = new WebClient();
  1996. nusWC = ConfigureWithProxy(nusWC);
  1997. nusWC.Headers.Add("User-Agent", "wii libnup/1.0"); // Set UserAgent to Wii value
  1998. // Create\Configure NusClient
  1999. libWiiSharp.NusClient nusClient = new libWiiSharp.NusClient();
  2000. nusClient.ConfigureNusClient(nusWC);
  2001. nusClient.UseLocalFiles = localuse.Checked;
  2002. nusClient.ContinueWithoutTicket = true;
  2003. nusClient.Debug += new EventHandler<libWiiSharp.MessageEventArgs>(nusClient_Debug);
  2004. libWiiSharp.StoreType[] storeTypes = new libWiiSharp.StoreType[1];
  2005. // There's no harm in outputting everything i suppose
  2006. storeTypes[0] = libWiiSharp.StoreType.All;
  2007. int title_version = int.Parse(title_info[1], System.Globalization.NumberStyles.HexNumber);
  2008. string wadName = NameFromDatabase(title_info[0]);
  2009. if (wadName != null)
  2010. wadName = OfficialWADNaming(wadName);
  2011. else
  2012. wadName = title_info[0] + "-NUS-v" + title_version + ".wad";
  2013. nusClient.DownloadTitle(title_info[0], title_version.ToString(), Path.Combine(CURRENT_DIR, ("output_" + Path.GetFileNameWithoutExtension(script_filename))), wadName, storeTypes);
  2014. /*
  2015. SetTextThreadSafe(titleidbox, title_info[0]);
  2016. SetTextThreadSafe(titleversion,
  2017. Convert.ToString(256*
  2018. (byte.Parse(title_info[1].Substring(0, 2),
  2019. System.Globalization.NumberStyles.HexNumber))));
  2020. SetTextThreadSafe(titleversion,
  2021. Convert.ToString(Convert.ToInt32(titleversion.Text) +
  2022. byte.Parse(title_info[1].Substring(2, 2),
  2023. System.Globalization.NumberStyles.HexNumber)));
  2024. button3_Click("Scripter", EventArgs.Empty);
  2025. Thread.Sleep(1000);
  2026. while (NUSDownloader.IsBusy)
  2027. {
  2028. Thread.Sleep(1000);
  2029. }
  2030. }
  2031. script_mode = false;
  2032. WriteStatus("Script completed!");*/
  2033. }
  2034. private void scriptsbutton_Click(object sender, EventArgs e)
  2035. {
  2036. // Show scripts menu
  2037. scriptsStrip.Text = "Showing";
  2038. scriptsStrip.Show(scriptsbutton, 2, (2+scriptsbutton.Height));
  2039. //if (!e.Equals(EventArgs.Empty))
  2040. {
  2041. System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
  2042. timer.Interval = 51;
  2043. timer.Tick += new EventHandler(contextmenusTimer_Tick);
  2044. timer.Start();
  2045. }
  2046. }
  2047. private void DatabaseEnabled(bool enabled)
  2048. {
  2049. for (int a = 0; a < databaseStrip.Items.Count; a++)
  2050. {
  2051. databaseStrip.Items[a].Enabled = enabled;
  2052. databaseStrip.Items[a].Visible = enabled;
  2053. }
  2054. for (int b = 0; b < VCMenuList.DropDownItems.Count; b++)
  2055. {
  2056. VCMenuList.DropDownItems[b].Enabled = true;
  2057. VCMenuList.DropDownItems[b].Visible = true;
  2058. }
  2059. }
  2060. void scriptsWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  2061. {
  2062. scriptsLocalMenuEntry.Enabled = true;
  2063. }
  2064. void OrganizeScripts(object sender, DoWorkEventArgs e)
  2065. {
  2066. //throw new NotImplementedException();
  2067. if (Directory.Exists(Path.Combine(CURRENT_DIR, "scripts")) == false)
  2068. {
  2069. WriteStatus("Scripts directory not found...");
  2070. WriteStatus("- Creating it.");
  2071. Directory.CreateDirectory(Path.Combine(CURRENT_DIR, "scripts"));
  2072. }
  2073. // Clear any entries from previous runthrough
  2074. if (scriptsLocalMenuEntry.DropDownItems.Count > 0)
  2075. {
  2076. // TODO: i suppose this is bad amiright
  2077. Control.CheckForIllegalCrossThreadCalls = false;
  2078. scriptsLocalMenuEntry.DropDownItems.Clear();
  2079. }
  2080. // Add directories w/ scripts in \scripts\
  2081. foreach (string directory in Directory.GetDirectories(Path.Combine(CURRENT_DIR, "scripts"), "*", SearchOption.TopDirectoryOnly))
  2082. {
  2083. if (Directory.GetFiles(directory, "*.nus", SearchOption.TopDirectoryOnly).Length > 0)
  2084. {
  2085. DirectoryInfo dinfo = new DirectoryInfo(directory);
  2086. ToolStripMenuItem folder_item = new ToolStripMenuItem();
  2087. folder_item.Text = dinfo.Name + Path.DirectorySeparatorChar;
  2088. folder_item.Image = Properties.Resources.folder_table;
  2089. foreach (string nusscript in Directory.GetFiles(directory, "*.nus", SearchOption.TopDirectoryOnly))
  2090. {
  2091. FileInfo finfo = new FileInfo(nusscript);
  2092. ToolStripMenuItem nus_script_item = new ToolStripMenuItem();
  2093. nus_script_item.Text = finfo.Name;
  2094. nus_script_item.Image = Properties.Resources.script_start;
  2095. folder_item.DropDownItems.Add(nus_script_item);
  2096. nus_script_item.Click += new EventHandler(nus_script_item_Click);
  2097. }
  2098. scriptsLocalMenuEntry.DropDownItems.Add(folder_item);
  2099. }
  2100. }
  2101. // Add scripts in \scripts\
  2102. foreach (string nusscript in Directory.GetFiles(Path.Combine(CURRENT_DIR, "scripts"), "*.nus", SearchOption.TopDirectoryOnly))
  2103. {
  2104. FileInfo finfo = new FileInfo(nusscript);
  2105. ToolStripMenuItem nus_script_item = new ToolStripMenuItem();
  2106. nus_script_item.Text = finfo.Name;
  2107. nus_script_item.Image = Properties.Resources.script_start;
  2108. scriptsLocalMenuEntry.DropDownItems.Add(nus_script_item);
  2109. nus_script_item.Click += new EventHandler(nus_script_item_Click);
  2110. }
  2111. }
  2112. private void aboutNUSDToolStripMenuItem_Click(object sender, EventArgs e)
  2113. {
  2114. // Display About Text...
  2115. statusbox.Text = "";
  2116. WriteStatus("NUS Downloader (NUSD)");
  2117. WriteStatus("You are running version: " + version);
  2118. if (version.StartsWith("SVN"))
  2119. WriteStatus("SVN BUILD: DO NOT REPORT BROKEN FEATURES!");
  2120. WriteStatus("This application created by WB3000");
  2121. WriteStatus("Various contributions by lukegb");
  2122. WriteStatus(String.Empty);
  2123. if (NUSDFileExists("key.bin") == true)
  2124. WriteStatus("Wii Decryption: Local (key.bin)");
  2125. if (NUSDFileExists("kkey.bin") == true)
  2126. WriteStatus("Wii Korea Decryption: Local (kkey.bin)");
  2127. if (NUSDFileExists("dsikey.bin") == true)
  2128. WriteStatus("DSi Decryption: Local (dsikey.bin)");
  2129. if (NUSDFileExists("database.xml") == false)
  2130. WriteStatus("Database (Wii): Need (database.xml)");
  2131. else
  2132. WriteStatus("Database (Wii): OK");
  2133. if (NUSDFileExists("dsidatabase.xml") == false)
  2134. WriteStatus("Database (DSi): Need (dsidatabase.xml)");
  2135. else
  2136. WriteStatus("Database (DSi): OK");
  2137. if (IsWin7())
  2138. WriteStatus("Windows 7 Features: Enabled");
  2139. WriteStatus("");
  2140. WriteStatus("Special thanks to:");
  2141. WriteStatus(" * Crediar for his wadmaker tool + source, and for the advice!");
  2142. WriteStatus(" * Leathl for libWiiSharp.");
  2143. WriteStatus(" * SquidMan/Galaxy/comex/Xuzz/#WiiDev for advice.");
  2144. WriteStatus(" * Pasta for impressive database contributions.");
  2145. WriteStatus(" * Napo7 for testing proxy settings.");
  2146. WriteStatus(" * Wyatt O'Day for the Windows7ProgressBar Control.");
  2147. WriteStatus(" * Famfamfam for the Silk Icon Set.");
  2148. WriteStatus(" * Anyone who has helped beta test!");
  2149. }
  2150. private void checkBox1_CheckedChanged(object sender, EventArgs e)
  2151. {
  2152. SaveProxyPwdPermanentBtn.Enabled = checkBox1.Checked;
  2153. }
  2154. private void SaveProxyPwdPermanentBtn_Click(object sender, EventArgs e)
  2155. {
  2156. proxy_pwd = ProxyPwdBox.Text;
  2157. string proxy_file = File.ReadAllText(Path.Combine(CURRENT_DIR, "proxy.txt"));
  2158. proxy_file += String.Format("\n{0}", proxy_pwd);
  2159. File.WriteAllText(Path.Combine(CURRENT_DIR, "proxy.txt"), proxy_file);
  2160. ProxyVerifyBox.Visible = false;
  2161. SetAllEnabled(true);
  2162. WriteStatus("To delete all traces of proxy settings, delete the proxy.txt file!");
  2163. }
  2164. private void clearButton_MouseEnter(object sender, EventArgs e)
  2165. {
  2166. // expand clear button
  2167. /*button3.Left = 194;
  2168. button3.Size = new System.Drawing.Size(68, 21);*/
  2169. clearButton.Text = "Clear";
  2170. //button3.ImageAlign = ContentAlignment.MiddleLeft;
  2171. }
  2172. private void clearButton_MouseLeave(object sender, EventArgs e)
  2173. {
  2174. // shrink clear button
  2175. /*button3.Left = 239;
  2176. button3.Size = new System.Drawing.Size(23, 21);*/
  2177. if (Type.GetType ("Mono.Runtime") == null)
  2178. clearButton.Text = String.Empty;
  2179. //button3.ImageAlign = ContentAlignment.MiddleCenter;
  2180. }
  2181. private void saveaswadbtn_MouseEnter(object sender, EventArgs e)
  2182. {
  2183. /*saveaswadbtn.Left = 190;
  2184. saveaswadbtn.Size = new Size(72, 22);*/
  2185. saveaswadbtn.Text = "Save As";
  2186. /*saveaswadbtn.ImageAlign = ContentAlignment.MiddleLeft;*/
  2187. }
  2188. private void saveaswadbtn_MouseLeave(object sender, EventArgs e)
  2189. {
  2190. /*saveaswadbtn.Left = 230;
  2191. saveaswadbtn.Size = new Size(32, 22);*/
  2192. if (Type.GetType("Mono.Runtime") == null)
  2193. saveaswadbtn.Text = String.Empty;
  2194. //saveaswadbtn.ImageAlign = ContentAlignment.MiddleCenter;
  2195. }
  2196. void nus_script_item_Click(object sender, EventArgs e)
  2197. {
  2198. ToolStripMenuItem tsmi = (ToolStripMenuItem)sender;
  2199. string folderpath = "";
  2200. if (!tsmi.OwnerItem.Equals(this.scriptsLocalMenuEntry))
  2201. {
  2202. folderpath = Path.Combine(tsmi.OwnerItem.Text, folderpath);
  2203. }
  2204. folderpath = Path.Combine(this.CURRENT_DIR, Path.Combine("scripts", Path.Combine(folderpath, tsmi.Text)));
  2205. string script_content = File.ReadAllText(folderpath);
  2206. script_content += String.Format(";{0}", tsmi.Text.Replace(".nus", ""));
  2207. BackgroundWorker scripter = new BackgroundWorker();
  2208. scripter.DoWork += new DoWorkEventHandler(RunScriptBg);
  2209. scripter.RunWorkerAsync(script_content);
  2210. }
  2211. private void saveaswadbtn_Click(object sender, EventArgs e)
  2212. {
  2213. SaveFileDialog wad_saveas = new SaveFileDialog();
  2214. wad_saveas.Title = "Save WAD File...";
  2215. wad_saveas.Filter = "WAD Files|*.wad|All Files|*.*";
  2216. wad_saveas.AddExtension = true;
  2217. DialogResult dres = wad_saveas.ShowDialog();
  2218. if (dres != DialogResult.Cancel)
  2219. WAD_Saveas_Filename = wad_saveas.FileName;
  2220. }
  2221. private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  2222. {
  2223. // This prevents errors when exiting before the database is parsed.
  2224. // This is also probably not the best way to accomplish this...
  2225. Environment.Exit(0);
  2226. }
  2227. private void iosPatchCheckbox_CheckedChanged(object sender, EventArgs e)
  2228. {
  2229. if (iosPatchCheckbox.Checked == true)
  2230. {
  2231. //packbox.Enabled = false;
  2232. packbox.Checked = true;
  2233. SetAllEnabled(false);
  2234. iosPatchGroupBox.Visible = true;
  2235. iosPatchGroupBox.Enabled = true;
  2236. iosPatchesListBox.Enabled = true;
  2237. iosPatchGroupBoxOKbtn.Enabled = true;
  2238. }
  2239. }
  2240. private void iosPatchGroupBoxOKbtn_Click(object sender, EventArgs e)
  2241. {
  2242. SetAllEnabled(true);
  2243. iosPatchGroupBox.Visible = false;
  2244. if (iosPatchesListBox.CheckedIndices.Count == 0)
  2245. // Uncheck the checkbox to indicate no patches
  2246. iosPatchCheckbox.Checked = false;
  2247. }
  2248. private void FillDatabaseScripts()
  2249. {
  2250. SetPropertyThreadSafe(scriptsDatabaseToolStripMenuItem, false, "Visible");
  2251. Database databaseObj = new Database();
  2252. databaseObj.LoadDatabaseToStream(Path.Combine(CURRENT_DIR, "database.xml"));
  2253. ToolStripMenuItem[] scriptItems = databaseObj.LoadScripts();
  2254. for (int a = 0; a < scriptItems.Length; a++)
  2255. {
  2256. scriptItems[a].Click += new EventHandler(ScriptItem_Clicked);
  2257. //AddToolStripItemToStrip(scriptsDatabaseToolStripMenuItem, scriptItems[a]);
  2258. //SystemMenuList.DropDownItems.Add(systemItems[a]);
  2259. }
  2260. AddToolStripItemToStrip(scriptsDatabaseToolStripMenuItem, scriptItems);
  2261. SetPropertyThreadSafe(scriptsDatabaseToolStripMenuItem, true, "Enabled");
  2262. SetPropertyThreadSafe(scriptsDatabaseToolStripMenuItem, true, "Visible");
  2263. }
  2264. public void ScriptItem_Clicked(object sender, EventArgs e)
  2265. {
  2266. // Scripts from database are stored in tooltips...
  2267. ToolStripMenuItem tsmi = (ToolStripMenuItem)sender;
  2268. string script_content = tsmi.ToolTipText;
  2269. script_content += String.Format(";{0}", tsmi.Text);
  2270. BackgroundWorker scripter = new BackgroundWorker();
  2271. scripter.DoWork += new DoWorkEventHandler(RunScriptBg);
  2272. scripter.RunWorkerAsync(script_content);
  2273. }
  2274. void ReorganizePreviousFolderStructure(object sender, DoWorkEventArgs e)
  2275. {
  2276. // 0000000000000000v000\* become titles\0000000000000000\v000\*
  2277. Regex TitleDirectoryRegex = new Regex(@"[a-zA-Z0-9]{16}v?([0-9]*)?");
  2278. if (Directory.Exists(Path.Combine(CURRENT_DIR, "titles")) == false)
  2279. Directory.CreateDirectory(Path.Combine(CURRENT_DIR, "titles"));
  2280. string[] directories = Directory.GetDirectories(CURRENT_DIR, "*", SearchOption.TopDirectoryOnly);
  2281. Debug.WriteLine("Dirs: " + directories.Length);
  2282. foreach (string directory in directories)
  2283. {
  2284. Debug.WriteLine("ff: " + directory);
  2285. DirectoryInfo dinfo = new DirectoryInfo(directory);
  2286. // name is XXXXXXXXXXXXXXXXvYYYY
  2287. if (TitleDirectoryRegex.IsMatch(dinfo.Name.ToString()) && dinfo.Name.Contains("v"))
  2288. {
  2289. string[] title_info = dinfo.Name.Split('v');
  2290. string titleid_dir = Path.Combine(Path.Combine(CURRENT_DIR, "titles"), title_info[0]);
  2291. string newfull_dir = Path.Combine(titleid_dir, String.Format("{0}", title_info[1]));
  2292. if (Directory.Exists(titleid_dir) == false)
  2293. Directory.CreateDirectory(titleid_dir);
  2294. if (Directory.Exists(newfull_dir) == false)
  2295. Directory.CreateDirectory(newfull_dir);
  2296. string[] files = Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly);
  2297. foreach (string file in files)
  2298. {
  2299. FileInfo titlefile = new FileInfo(file);
  2300. if (File.Exists(Path.Combine(newfull_dir, titlefile.Name)) == false)
  2301. titlefile.MoveTo(Path.Combine(newfull_dir, titlefile.Name));
  2302. }
  2303. if (dinfo.GetFiles().Length <= 0 && dinfo.GetDirectories().Length <= 0)
  2304. Directory.Delete(directory);
  2305. }
  2306. else if (TitleDirectoryRegex.IsMatch(dinfo.Name.ToString()))
  2307. {
  2308. string titleid_dir = Path.Combine(Path.Combine(CURRENT_DIR, "titles"), dinfo.Name.ToString());
  2309. libWiiSharp.TMD tmdfile = new libWiiSharp.TMD();
  2310. int count = 0;
  2311. string[] tmdfiles = Directory.GetFiles(directory, "*tmd*", SearchOption.TopDirectoryOnly);
  2312. if (tmdfiles.Length > 1)
  2313. continue; //Too many TMD files ?
  2314. foreach (string file in tmdfiles)
  2315. {
  2316. if (file.Contains("tmd"))
  2317. {
  2318. tmdfile.LoadFile(file);
  2319. count++;
  2320. }
  2321. }
  2322. if (count == 0)
  2323. continue;
  2324. string version = tmdfile.TitleVersion.ToString();
  2325. string newfull_dir = Path.Combine(titleid_dir, String.Format("{0}", version));
  2326. if (Directory.Exists(titleid_dir) == false)
  2327. Directory.CreateDirectory(titleid_dir);
  2328. if (Directory.Exists(newfull_dir) == false)
  2329. Directory.CreateDirectory(newfull_dir);
  2330. string[] files = Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly);
  2331. foreach (string file in files)
  2332. {
  2333. FileInfo titlefile = new FileInfo(file);
  2334. if (File.Exists(Path.Combine(newfull_dir, titlefile.Name)) == false)
  2335. titlefile.MoveTo(Path.Combine(newfull_dir, titlefile.Name));
  2336. }
  2337. if (dinfo.GetFiles().Length <= 0 && dinfo.GetDirectories().Length <= 0)
  2338. Directory.Delete(directory);
  2339. }
  2340. }
  2341. }
  2342. void ReorganizePreviousFolderStructure_Completed(object sender, RunWorkerCompletedEventArgs e)
  2343. {
  2344. WriteStatus(" - Operation complete!");
  2345. }
  2346. private void RunScript(string scriptstr, string scriptname)
  2347. {
  2348. // Form and folder stuffs
  2349. SetTextThreadSafe(statusbox, "");
  2350. WriteStatus("Starting script download. Please be patient!");
  2351. string scriptdir;
  2352. if (scriptname == "random")
  2353. scriptdir = Path.Combine(Path.Combine(CURRENT_DIR, "scripts"), RandomString(7) + "_output");
  2354. else
  2355. scriptdir = Path.Combine(Path.Combine(CURRENT_DIR, "scripts"), scriptname + "_output");
  2356. if (!File.Exists(scriptdir))
  2357. Directory.CreateDirectory(scriptdir);
  2358. // Parse entries
  2359. string[] NUS_Entries = scriptstr.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
  2360. WriteStatus(String.Format(" - Script loaded ({0} Titles)", NUS_Entries.Length));
  2361. WriteStatus(" - Output: " + scriptdir.Replace(CURRENT_DIR, ""));
  2362. for (int a = 0; a < NUS_Entries.Length; a++)
  2363. {
  2364. // Download the title
  2365. WriteStatus(String.Format("===== Running Download ({0}/{1}) =====", a + 1, NUS_Entries.Length));
  2366. string[] title_info = NUS_Entries[a].Split(' ');
  2367. // don't let the delete issue reappear...
  2368. if (string.IsNullOrEmpty(title_info[0]))
  2369. continue;
  2370. // WebClient configuration
  2371. WebClient nusWC = new WebClient();
  2372. nusWC = ConfigureWithProxy(nusWC);
  2373. nusWC.Headers.Add("User-Agent", "wii libnup/1.0"); // Set UserAgent to Wii value
  2374. // Create\Configure NusClient
  2375. libWiiSharp.NusClient nusClient = new libWiiSharp.NusClient();
  2376. nusClient.ConfigureNusClient(nusWC);
  2377. nusClient.UseLocalFiles = localuse.Checked;
  2378. nusClient.ContinueWithoutTicket = true;
  2379. nusClient.Debug += new EventHandler<libWiiSharp.MessageEventArgs>(nusClient_Debug);
  2380. libWiiSharp.StoreType[] storeTypes = new libWiiSharp.StoreType[1];
  2381. // There's no harm in outputting everything i suppose
  2382. storeTypes[0] = libWiiSharp.StoreType.All;
  2383. int title_version = int.Parse(title_info[1], System.Globalization.NumberStyles.HexNumber);
  2384. string wadName = NameFromDatabase(title_info[0]);
  2385. if (wadName != null)
  2386. wadName = OfficialWADNaming(wadName);
  2387. else
  2388. wadName = title_info[0] + "-NUS-v" + title_version + ".wad";
  2389. nusClient.DownloadTitle(title_info[0], title_version.ToString(), scriptdir, wadName, storeTypes);
  2390. }
  2391. WriteStatus("Script completed!");
  2392. }
  2393. // Random string function for temp foldernames in RunScript.
  2394. // Probably going to be removed TODO
  2395. private readonly Random _rng = new Random();
  2396. private const string _chars = "abcdefghijklmnopqrstuvwxyz";
  2397. private string RandomString(int size)
  2398. {
  2399. char[] buffer = new char[size];
  2400. for (int i = 0; i < size; i++)
  2401. {
  2402. buffer[i] = _chars[_rng.Next(_chars.Length)];
  2403. }
  2404. return new string(buffer);
  2405. }
  2406. void Form1_MouseWheel(object sender, System.Windows.Forms.MouseEventArgs e)
  2407. {
  2408. //Debug.WriteLine("Delta: " + e.Delta.ToString());
  2409. if (SystemMenuList.DropDown.DisplayRectangle.Contains(e.Location) ||
  2410. SystemMenuList.DropDown.Bounds.Contains(e.Location) ||
  2411. WiiWareMenuList.DropDown.DisplayRectangle.Contains(e.Location) ||
  2412. WiiWareMenuList.DropDown.Bounds.Contains(e.Location) ||
  2413. VCMenuList.DropDown.DisplayRectangle.Contains(e.Location) ||
  2414. VCMenuList.DropDown.Bounds.Contains(e.Location) ||
  2415. IOSMenuList.DropDown.DisplayRectangle.Contains(e.Location) ||
  2416. IOSMenuList.DropDown.Bounds.Contains(e.Location))
  2417. {
  2418. if (e.Delta > 0)
  2419. {
  2420. System.Windows.Forms.SendKeys.Send("{UP}");
  2421. System.Windows.Forms.SendKeys.Send("{UP}");
  2422. System.Windows.Forms.SendKeys.Send("{UP}");
  2423. System.Windows.Forms.SendKeys.Send("{UP}");
  2424. System.Windows.Forms.SendKeys.Send("{UP}");
  2425. }
  2426. else
  2427. {
  2428. System.Windows.Forms.SendKeys.Send("{DOWN}");
  2429. System.Windows.Forms.SendKeys.Send("{DOWN}");
  2430. System.Windows.Forms.SendKeys.Send("{DOWN}");
  2431. System.Windows.Forms.SendKeys.Send("{DOWN}");
  2432. System.Windows.Forms.SendKeys.Send("{DOWN}");
  2433. }
  2434. }
  2435. }
  2436. private void openNUSDDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
  2437. {
  2438. // Opens the directory NUSD is working in... (CURREND_DIR)
  2439. Process.Start(CURRENT_DIR);
  2440. }
  2441. private void mainPageToolStripMenuItem_Click(object sender, EventArgs e)
  2442. {
  2443. Process.Start("http://www.wiibrew.org/wiki/NUS_Downloader");
  2444. }
  2445. private void databasePageToolStripMenuItem_Click(object sender, EventArgs e)
  2446. {
  2447. Process.Start("http://www.wiibrew.org/wiki/NUS_Downloader/database");
  2448. }
  2449. private void extrasStrip_Opening(object sender, CancelEventArgs e)
  2450. {
  2451. // Show additional features based on held keys...
  2452. #if DEBUG
  2453. moreExtrasToolStripMenuItem.Visible = true;
  2454. #else
  2455. moreExtrasToolStripMenuItem.Visible = Control.ModifierKeys == Keys.Control; // If Ctrl Pressed.
  2456. #endif
  2457. }
  2458. private void runFolderFixToolStripMenuItem_Click(object sender, EventArgs e)
  2459. {
  2460. // Run folderfix to make \titles\
  2461. // Organizing folders from past NUSD releases...
  2462. BackgroundWorker folder_fixer = new BackgroundWorker();
  2463. folder_fixer.DoWork += new DoWorkEventHandler(ReorganizePreviousFolderStructure);
  2464. folder_fixer.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ReorganizePreviousFolderStructure_Completed);
  2465. Debug.WriteLine("folderfix active");
  2466. WriteStatus("Organizing your old folder structure...");
  2467. folder_fixer.RunWorkerAsync();
  2468. }
  2469. private void removeNUSDFilesFoldersToolStripMenuItem_Click(object sender, EventArgs e)
  2470. {
  2471. // Extras thing, remove all of NUSD files...
  2472. if (MessageBox.Show("This will delete all the files\folders you have downloaded from NUS! Are you sure you want to do this?", "Wait a second!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != System.Windows.Forms.DialogResult.Yes)
  2473. return;
  2474. if (Directory.Exists(Path.Combine(CURRENT_DIR, "titles")))
  2475. Directory.Delete(Path.Combine(CURRENT_DIR, "titles"), true);
  2476. if (Directory.Exists(Path.Combine(CURRENT_DIR, "scripts")))
  2477. Directory.Delete(Path.Combine(CURRENT_DIR, "scripts"), true);
  2478. if (File.Exists(Path.Combine(CURRENT_DIR, "database.xml")))
  2479. File.Delete(Path.Combine(CURRENT_DIR, "database.xml"));
  2480. if (File.Exists(Path.Combine(CURRENT_DIR, "dsidatabase.xml")))
  2481. File.Delete(Path.Combine(CURRENT_DIR, "dsidatabase.xml"));
  2482. if (File.Exists(Path.Combine(CURRENT_DIR, "olddatabase.xml")))
  2483. File.Delete(Path.Combine(CURRENT_DIR, "olddatabase.xml"));
  2484. if (File.Exists(Path.Combine(CURRENT_DIR, "proxy.txt")))
  2485. File.Delete(Path.Combine(CURRENT_DIR, "proxy.txt"));
  2486. if (File.Exists(Path.Combine(CURRENT_DIR, "key.bin")))
  2487. File.Delete(Path.Combine(CURRENT_DIR, "key.bin"));
  2488. if (File.Exists(Path.Combine(CURRENT_DIR, "kkey.bin")))
  2489. File.Delete(Path.Combine(CURRENT_DIR, "kkey.bin"));
  2490. if (File.Exists(Path.Combine(CURRENT_DIR, "dsikey.bin")))
  2491. File.Delete(Path.Combine(CURRENT_DIR, "dsikey.bin"));
  2492. }
  2493. private void anyStrip_Closed(object sender, ToolStripDropDownClosedEventArgs e)
  2494. {
  2495. ((ContextMenuStrip)sender).Text = "Hidden";
  2496. //Debug.Write(((ContextMenuStrip)sender).Name);
  2497. }
  2498. private void localTicketInventoryToolStripMenuItem_Click(object sender, EventArgs e)
  2499. {
  2500. // Alters icons if tickets exist locally...
  2501. WriteStatus("Adding ticket information to database entries...");
  2502. ToolStripMenuItem[] Lists = new ToolStripMenuItem[6] { SystemMenuList, IOSMenuList, VCMenuList, WiiWareMenuList, dsiSystemToolStripMenu, dSiWareToolStripMenu };
  2503. for (int l = 0; l < Lists.Length; l++)
  2504. {
  2505. for (int a = 0; a < Lists[l].DropDownItems.Count; a++)
  2506. {
  2507. if (Lists[l].DropDownItems[a].Text.Length < 16)
  2508. continue;
  2509. string itemTitleId = Lists[l].DropDownItems[a].Text.Substring(0, 16);
  2510. string itemDir = Path.Combine(Path.Combine(CURRENT_DIR, "titles"), itemTitleId);
  2511. if (Directory.Exists(itemDir) == false)
  2512. continue;
  2513. string[] files = Directory.GetFiles(itemDir, "cetk", SearchOption.AllDirectories);
  2514. if (files.Length > 0)
  2515. {
  2516. if (Lists[l].DropDownItems[a].Image == Database.green)
  2517. Lists[l].DropDownItems[a].Image = Database.green_blue;
  2518. if (Lists[l].DropDownItems[a].Image == Database.orange)
  2519. Lists[l].DropDownItems[a].Image = Database.orange_blue;
  2520. if (Lists[l].DropDownItems[a].Image == Database.redorange)
  2521. Lists[l].DropDownItems[a].Image = Database.redorange_blue;
  2522. if (Lists[l].DropDownItems[a].Image == Database.redgreen)
  2523. Lists[l].DropDownItems[a].Image = Database.redgreen_blue;
  2524. }
  2525. }
  2526. }
  2527. WriteStatus(" - Operation completed!");
  2528. }
  2529. private void donateToolStripMenuItem_Click(object sender, EventArgs e)
  2530. {
  2531. //TODO: Organize how this will work...
  2532. Process.Start("http://wb3000.atspace.name/donations.html");
  2533. }
  2534. private void DSiDatabaseWork(object sender, System.ComponentModel.DoWorkEventArgs e)
  2535. {
  2536. while (databaseWorker.IsBusy)
  2537. {
  2538. Thread.Sleep(1000);
  2539. }
  2540. BackgroundWorker worker = sender as BackgroundWorker;
  2541. FillDSiDatabaseStrip(worker);
  2542. LoadRegionCodes();
  2543. //FillDatabaseScripts();
  2544. ShowInnerToolTips(false);
  2545. }
  2546. private void DSiDatabaseWork_Completed(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
  2547. {
  2548. this.databaseButton.Text = "Database...";
  2549. this.databaseButton.Image = null;
  2550. }
  2551. private void DSiDatabaseWork_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
  2552. {
  2553. if (e.ProgressPercentage == 50)
  2554. databaseButton.Text = " [. ]";
  2555. else if (e.ProgressPercentage == 100)
  2556. databaseButton.Text = " [..]";
  2557. }
  2558. private void wiiRegionCodesMenu_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
  2559. {
  2560. if (titleidbox.Text.Length == 16)
  2561. titleidbox.Text = titleidbox.Text.Substring(0, 14) + e.ClickedItem.Text.Substring(0, 2);
  2562. }
  2563. private void dsiRegionCodesMenu_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
  2564. {
  2565. if (titleidbox.Text.Length == 16)
  2566. titleidbox.Text = titleidbox.Text.Substring(0, 14) + e.ClickedItem.Text.Substring(0, 2);
  2567. }
  2568. private void serverLbl_MouseEnter(object sender, EventArgs e)
  2569. {
  2570. serverLbl.Font = new Font(serverLbl.Font, FontStyle.Underline);
  2571. }
  2572. private void serverLbl_MouseLeave(object sender, EventArgs e)
  2573. {
  2574. serverLbl.Font = new Font(serverLbl.Font, FontStyle.Regular);
  2575. }
  2576. private void serverLbl_TextChanged(object sender, EventArgs e)
  2577. {
  2578. if (serverLbl.Text == "Wii")
  2579. {
  2580. // Can pack WADs / Decrypt
  2581. packbox.Enabled = true;
  2582. }
  2583. if (serverLbl.Text == "DSi")
  2584. {
  2585. // Cannot Pack WADs
  2586. packbox.Checked = false;
  2587. packbox.Enabled = false;
  2588. wadnamebox.Enabled = false;
  2589. wadnamebox.Text = "";
  2590. }
  2591. }
  2592. private void serverLbl_Click(object sender, EventArgs e)
  2593. {
  2594. // Switch what server is displayed in the label, when clicked.
  2595. string[] serverLblServers = new string[2] { "Wii", "DSi" };
  2596. for (int a = 0; a < serverLblServers.Length; a++)
  2597. {
  2598. if (serverLbl.Text == serverLblServers[a])
  2599. {
  2600. if (serverLblServers.Length == (a + 1))
  2601. serverLbl.Text = serverLblServers[0];
  2602. else
  2603. serverLbl.Text = serverLblServers[a+1];
  2604. break;
  2605. }
  2606. }
  2607. }
  2608. }
  2609. }