-
Notifications
You must be signed in to change notification settings - Fork 7
/
Form1.cs
903 lines (800 loc) · 39.8 KB
/
Form1.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net.Http;
using System.Net;
using System.Runtime.CompilerServices;
using MetroFramework;
using Microsoft.Win32;
using System.Net.Sockets;
using System.Threading;
using System.Data.SQLite;
using System.Security.Cryptography;
using System.Data.SqlClient;
using PS4_Tools.LibOrbis;
using PS4_Tools.Util;
using System.Drawing.Imaging;
using System.Net.NetworkInformation;
using Microsoft.Win32;
using IWshRuntimeLibrary;
/*Copyright Darksoftware (c) 2019-2022*/
/* LICENSED UNDER GPLv3 */
namespace Store_CDN_Server
{
public partial class Form1 : System.Windows.Forms.Form
{
private TcpListener myListener;
SQLiteConnection sql_con;
string serverRoot = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
private Ini.IniFile ini;
string drive;
bool isautostart = false;
Thread th, th2, th3, th4;
public Form1()
{
InitializeComponent();
ini = new Ini.IniFile(serverRoot + @"\settings.ini");
groupControl1.AllowDrop = true;
metroTextBox1.Text = Properties.Settings.Default.IP;
sql_con = new SQLiteConnection("Data Source=" + serverRoot + @"/store.db;");
Console.WriteLine("INI: " + serverRoot + @"\settings.ini" + " ROOT: " + serverRoot);
}
private string apptype_info(PS4_Tools.PKG.SceneRelated.PKGType type, string filename)
{
switch (type)
{
case PS4_Tools.PKG.SceneRelated.PKGType.Game:
return "Game";
case PS4_Tools.PKG.SceneRelated.PKGType.App:
return "App";
case PS4_Tools.PKG.SceneRelated.PKGType.Patch:
return "Patch";
case PS4_Tools.PKG.SceneRelated.PKGType.Addon_Theme: // workaround for PS4 Tools
{
if (filename.Contains("theme") || filename.Contains("Theme"))
return "Theme";
else
return "DLC";
}
}
return "Unknown";
}
private void Form1_Load(object sender, EventArgs e)
{
if (!System.IO.File.Exists(serverRoot + "/store.db"))
{
SQLiteConnection.CreateFile(serverRoot + "/store.db");
SQLiteConnection.CreateFile(serverRoot + "/store_readonly.db");
sql_con.Open();
string create_db = "CREATE TABLE homebrews ( pid int UNSIGNED NOT NULL,id varchar(255), name varchar(255), desc varchar(255), image varchar(255), package varchar(255), version varchar(255) ,picpath varchar(255) ,desc_1 varchar(255) ,desc_2 varchar(255) ,ReviewStars varchar(255) ,Size varchar(255) ,Author varchar(255) ,apptype varchar(255) ,pv varchar(255) ,main_icon_path varchar(255) ,main_menu_pic varchar(255) ,releaseddate date DEFAULT NULL,number_downloads int NOT NULL);";
SQLiteCommand command = new SQLiteCommand(create_db, sql_con);
command.ExecuteNonQuery();
}
else
{
if (!System.IO.File.Exists(serverRoot + "/store_readonly.db"))
System.IO.File.Copy(serverRoot + "/store.db", serverRoot + "/store_readonly.db", true);
sql_con.Open();
}
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
//Console.WriteLine(ni.Name);
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
//Console.WriteLine(ip.Address.ToString());
metroTextBox1.Items.Add(ip.Address.ToString());
}
}
}
}
try
{
metroTextBox1.Text = ini.IniReadValue("network", "ps4ip");
pkgText.Text = ini.IniReadValue("network", "pkgPath");
}
catch (Exception) { }
RegistryKey rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (rk != null)
{
try
{
string value = (String)rk.GetValue("Store CDN Server");
if (!string.IsNullOrEmpty(value))
isautostart = true;
else
Console.WriteLine("Reg key not installed...");
}
catch
{
Console.WriteLine("Reg key not installed...");
}
}
button1.Text = isautostart ? "Disable" : "Enable";
button1.ForeColor = isautostart ? Color.Red : Color.Green;
if (isautostart)
button3_Click(sender, e);
}
public static System.Drawing.Bitmap BytesToBitmap(byte[] ImgBytes)
{
System.Drawing.Bitmap result = null;
if (ImgBytes != null)
{
MemoryStream stream = new MemoryStream(ImgBytes);
result = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromStream(stream);
}
return result;
}
public int count_rows()
{
string query = "SELECT COUNT(*) FROM homebrews";
List<string> liteEntries = new List<string>();
var cmd = new SQLiteCommand(query, sql_con);
object result = cmd.ExecuteScalar();
int nTables = Convert.ToInt32(result);
return nTables;
}
private string calcsize(string file)
{
string[] sizes = { "B", "KB", "MB", "GB", "TB" };
double len = new FileInfo(file).Length;
int order = 0;
while (len >= 1024 && order < sizes.Length - 1)
{
order++;
len = len / 1024;
}
// Adjust the format string to your preferences. For example "{0:0.#}{1}" would
// show a single decimal place, and no space.
return String.Format("{0:0.##} {1}", len, sizes[order]);
}
public static void SavePic(Image img, string Filename)
{
try
{
new Bitmap(img, 512, 512).Save(Filename);
}
catch (Exception) { } //No Image
}
public void SendToBrowser(String sData, ref Socket mySocket)
{
SendToBrowser(Encoding.ASCII.GetBytes(sData), ref mySocket);
}
public void SendToBrowser(Byte[] bSendData, ref Socket mySocket, long startRange = 0)
{
try
{
if (mySocket.Connected)
{
// Adjust this to send in chunks and respect the range header if present
long dataToSend = bSendData.Length - startRange;
int bytesSent = 0;
while (dataToSend > 0)
{
// Send in chunks of up to 5MB
int chunkSize = (int)Math.Min(dataToSend, 5 * 1024 * 1024);
bytesSent += mySocket.Send(bSendData, (int)startRange + bytesSent, chunkSize, 0);
dataToSend -= chunkSize;
}
}
else
{
Console.WriteLine("Connection Dropped....");
}
}
catch (SocketException e)
{
Console.WriteLine("Error Occurred : {0} ", e);
}
}
public string md5_file(string file)
{
using (var md5 = MD5.Create())
{
FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
var hashResult = md5.ComputeHash(fs);
fs.Close();
return BitConverter.ToString(hashResult).Replace("-", "").ToLowerInvariant();
}
}
public void SendHeader(string sHttpVersion, string sMIMEHeader, long iTotBytes, string sStatusCode, ref Socket mySocket, string contentRange = "")
{
StringBuilder sBuffer = new StringBuilder();
sBuffer.Append(sHttpVersion + sStatusCode + "\r\n");
sBuffer.Append("Server: CustomCDNServer\r\n");
sBuffer.Append("Content-Type: " + sMIMEHeader + "\r\n");
// Include Content-Range header if provided (for partial content responses)
if (!string.IsNullOrEmpty(contentRange))
{
sBuffer.Append(contentRange);
}
sBuffer.Append("Accept-Ranges: bytes\r\n");
sBuffer.Append("Content-Length: " + iTotBytes + "\r\n");
// Keep the connection alive (if your logic supports it)
sBuffer.Append("Connection: keep-alive\r\n\r\n");
Byte[] bSendData = Encoding.ASCII.GetBytes(sBuffer.ToString());
SendToBrowser(bSendData, ref mySocket);
}
bool is_running = false;
int x = 0;
private void SetText(string text)
{
if (lblProgress.Location.X-90 > x)
x = lblProgress.Location.X - 90;
Invoke(new Action(() => { lblProgress.Text = text; lblProgress.Location = new Point(x, lblProgress.Location.Y); }));
}
public void StartListen()
{
int iStartPos = 0;
String sRequest;
String sDirName;
String sRequestedFile;
String sErrorMessage;
String sPhysicalFilePath = "";
String sMimeType = "application/octet-stream";
Socket mySocket = null;
while (is_running)
{
try
{
if (!myListener.Pending())
{
Thread.Sleep(500); // choose a number (in milliseconds) that makes sense
continue; // skip to next iteration of loop
}
}
catch
{
is_running = false;
return;
}
bool is_head = false;
//Accept a new connection
mySocket = myListener.AcceptSocket();
Console.WriteLine("Socket Type " + mySocket.SocketType);
if (mySocket.Connected)
{
Console.WriteLine("\nClient Connected!!\n==================\nCLient IP {0}\n", mySocket.RemoteEndPoint);
//make a byte array and receive data from the client
Byte[] bReceive = new Byte[1024];
int i = mySocket.Receive(bReceive, bReceive.Length, 0);
//Convert Byte to String
string sBuffer = Encoding.ASCII.GetString(bReceive);
iStartPos = sBuffer.IndexOf("Range:");
string range_header = "";
if (iStartPos != -1)
{
// Find the end of the line to accurately capture the Range header value
int iEndPos = sBuffer.IndexOf("\r\n", iStartPos);
if (iEndPos > iStartPos)
{
range_header = sBuffer.Substring(iStartPos, iEndPos - iStartPos);
// Optionally, trim the "Range:" part if you only want the value
range_header = range_header.Replace("Range: ", ""); // This leaves just the range value, e.g., "bytes=0-65535"
}
}
//At present we will only deal with GET type
if (sBuffer.Substring(0, 3) != "GET")
{
Console.WriteLine("Only Get Method is supported..");
// mySocket.Close();
// continue;
}
if (sBuffer.Substring(0, 4) == "HEAD")
{
Console.WriteLine("Head set..");
is_head = true;
}
//print out the http request header
Console.WriteLine(sBuffer);
// Look for HTTP request
iStartPos = sBuffer.IndexOf("HTTP", 1);
// Get the HTTP text and version e.g. it will return "HTTP/1.1"
string sHttpVersion = sBuffer.Substring(iStartPos, 8);
// Extract the Requested Type and Requested file/directory
sRequest = sBuffer.Substring(0, iStartPos - 1);
//Replace backslash with Forward Slash, if Any
//If file name is not supplied add forward slash to indicate
//that it is a directory and then we will look for the
//default file name..
//
//get the range http header for sbuffer
if ((sRequest.IndexOf(".") < 1) && (!sRequest.EndsWith("/")))
{
sRequest = sRequest + "/";
}
//Extract the requested file name
iStartPos = sRequest.LastIndexOf("/") + 1;
sRequestedFile = sRequest.Substring(iStartPos);
//Extract The directory Name
int re = (is_head) ? 4 : 3;
sDirName = sRequest.Substring(sRequest.IndexOf("/"), sRequest.LastIndexOf("/") - re);
Console.WriteLine("Directory Requested : " + sDirName);
//If the physical directory does not exists then
// dispaly the error message
Console.WriteLine("dir: " + sDirName);
if (sRequestedFile.Contains("api.php?page="))
{
string file_numb = sRequestedFile.Remove(0, 13);
Console.WriteLine("page" + file_numb + ".json");
if (System.IO.File.Exists("page" + file_numb + ".json"))
{
string con = System.IO.File.ReadAllText("page" + file_numb + ".json");
//Send to HTTP Page and set header
SendHeader(sHttpVersion, "application/json", con.Length, " 200 OK", ref mySocket);
SendToBrowser(con, ref mySocket);
}
else
{
sErrorMessage = "<H2>404 Error! File Does Not Exists...</H2>";
SendHeader(sHttpVersion, "text/html", sErrorMessage.Length, " 404 Not Found", ref mySocket);
SendToBrowser(sErrorMessage, ref mySocket);
}
mySocket.Close();
continue;
}
//download.php?tid
if (sRequestedFile.Contains("download.php?tid"))
{
string json = "{\"number_of_downloads\":\"" + 0 /* LATER MAY ACTUAL DO SMTH */ + "\"}";
SendHeader(sHttpVersion, "application/json", json.Length, " 200 OK", ref mySocket);
SendToBrowser(json, ref mySocket);
SetText("Last Served File: " + sRequestedFile);
mySocket.Close();
continue;
}
if (sRequestedFile.Contains("api.php?db_check_hash"))
{
string json = "{\"hash\":\"" + md5_file("./store_readonly.db") + "\"}";
SendHeader(sHttpVersion, "application/json", json.Length, " 200 OK", ref mySocket);
SendToBrowser(json, ref mySocket);
SetText("Last Served File: " + sRequestedFile);
mySocket.Close();
continue;
}
if (sRequestedFile.Length == 0)
{
// Get the default filename
// sRequestedFile = GetTheDefaultFileName(sLocalDir);
if (sRequestedFile == "")
{
Console.WriteLine("file: " + sRequestedFile);
sErrorMessage = "<H2>Error!! No Default File Name Specified</H2>";
SendHeader(sHttpVersion, "", sErrorMessage.Length, " 404 Not Found", ref mySocket);
SendToBrowser(sErrorMessage, ref mySocket);
mySocket.Close();
continue;
}
}
if (sRequestedFile.Contains(".html") || sRequestedFile.Contains(".js") || sRequestedFile.Contains(".bin") || sDirName == "/update/" || sRequestedFile == "store.db" || sDirName.Contains("storedata"))
{
if (sRequestedFile == "store.db") //redirect open db to readonly db
sRequestedFile = "store_readonly.db";
sPhysicalFilePath = serverRoot + sDirName + sRequestedFile;
//MessageBox.Show(sPhysicalFilePath);
}
else
{
if (!sDirName.Contains("/network_drive/"))
sPhysicalFilePath = drive + sDirName.Replace("%20", " ") + sRequestedFile.Replace("%20", " ");
else if (sDirName.Contains("/network_drive/"))
{
Console.WriteLine("B4 workaround PATH: " + sDirName.Replace("%20", " ") + sRequestedFile.Replace("%20", " "));
sPhysicalFilePath = sDirName.Replace("/network_drive/", @"\\") + sRequestedFile.Replace("/network_drive/", @"\\");
Console.WriteLine("after workaround: " + sPhysicalFilePath);
}
}
if (sRequestedFile.Contains(".html"))
sMimeType = "text/html";
else if (sRequestedFile.Contains(".js"))
sMimeType = "text/javascript";
Console.WriteLine("File Requested : " + sPhysicalFilePath);
// Check if the URL contains "?&product"
if (sPhysicalFilePath.Contains("?&product"))
{
// Find the index of ".pkg" and add 4 to include the ".pkg" in the substring
int pkgIndex = sPhysicalFilePath.IndexOf(".pkg") + 4;
// Use substring method to get everything up to and including ".pkg"
string modifiedUrl = sPhysicalFilePath.Substring(0, pkgIndex);
sPhysicalFilePath = modifiedUrl;
Console.WriteLine("Modified URL: " + sPhysicalFilePath);
}
if (!System.IO.File.Exists(sPhysicalFilePath))
{
sErrorMessage = "<H2>404 Error! File Does Not Exists...</H2>";
SendHeader(sHttpVersion, "", sErrorMessage.Length, " 404 Not Found", ref mySocket);
SendToBrowser(sErrorMessage, ref mySocket);
mySocket.Close();
continue;
}
else
{
FileInfo fi = new FileInfo(sPhysicalFilePath);
long startRange = 0;
long endRange = fi.Length - 1;
// Check if the Range header is present and parse it
if (!string.IsNullOrEmpty(range_header) && range_header.StartsWith("bytes="))
{
// Remove the "bytes=" part to facilitate parsing
string range = range_header.Substring(6); // "0-65535" for the example
// Split the range by '-' to separate start and end values
string[] rangeParts = range.Split('-');
// Attempt to parse the start range, defaulting to 0 on failure
if (!long.TryParse(rangeParts[0], out startRange))
{
startRange = 0; // Default to the start of the file if parsing fails
}
// Attempt to parse the end range if specified, defaulting to file length minus one
if (rangeParts.Length > 1 && !string.IsNullOrEmpty(rangeParts[1]))
{
if (!long.TryParse(rangeParts[1], out endRange))
{
// Assuming fi represents the FileInfo object for the file being served
endRange = fi.Length - 1; // Default to the end of the file if parsing fails
}
}
else
{
// If no end range specified, use the file's total length
endRange = fi.Length - 1;
}
}
long contentLength = endRange - startRange + 1;
Console.WriteLine("Content Length: " + contentLength);
FileStream inputTempFile = new FileStream(sPhysicalFilePath, FileMode.Open, FileAccess.Read);
inputTempFile.Seek(startRange, SeekOrigin.Begin);
// Adjust the buffer size if necessary
byte[] buffer = new byte[4*1024*1024];
int bytesRead;
long bytesToSend = contentLength;
// Modify the status code and headers for partial content if a range request was made
string statusCode = !string.IsNullOrEmpty(range_header) ? " 206 Partial Content" : " 200 OK";
string contentRange = !string.IsNullOrEmpty(range_header) ? $"Content-Range: bytes {startRange}-{endRange}/{fi.Length}\r\n" : "";
SendHeader(sHttpVersion, sMimeType, bytesToSend, statusCode, ref mySocket, contentRange);
Console.WriteLine("File Size: " + fi.Length);
if (!is_head)
{
while (bytesToSend > 0 && (bytesRead = inputTempFile.Read(buffer, 0, buffer.Length)) > 0)
{
if (bytesToSend < bytesRead)
{
bytesRead = (int)bytesToSend; // Adjust the last read to the remaining bytes
}
SendToBrowser(buffer.Take(bytesRead).ToArray(), ref mySocket); // Ensure we send only the read bytes
bytesToSend -= bytesRead;
Console.WriteLine("Bytes Sent: " + bytesRead);
}
}
Console.WriteLine("File Sent");
inputTempFile.Close();
mySocket.Close();
}
SetText("Last Served File: " + sRequestedFile);
}
}
if (!is_running && mySocket != null)
mySocket.Close();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
th.Abort();
th2.Abort();
th3.Abort();
th4.Abort();
myListener.Stop();
}
catch (Exception) { }
try
{
ini.IniWriteValue("network", "ps4ip", metroTextBox1.Text);
ini.IniWriteValue("network", "pkgPath", pkgText.Text);
}
catch (Exception) { }
}
public static IEnumerable<string> GetFiles(string root, string searchPattern) //Required to ignore folders that require admin privileges
{
Stack<string> pending = new Stack<string>();
pending.Push(root);
while (pending.Count != 0)
{
var path = pending.Pop();
string[] next = null;
try
{
next = Directory.GetFiles(path, searchPattern);
}
catch { }
if (next != null && next.Length != 0)
foreach (var file in next) yield return file;
try
{
next = Directory.GetDirectories(path);
foreach (var subdir in next) pending.Push(subdir);
}
catch { }
}
}
private void clearDatabase()
{
try
{
SQLiteCommand sql_cmd = sql_con.CreateCommand();
sql_cmd.CommandText = "DELETE FROM homebrews;";
sql_cmd.ExecuteNonQuery();
}
catch (Exception ee)
{
MessageBox.Show(ee.ToString());
}
}
private void button6_Click(object sender, EventArgs e)
{
string hostName = Dns.GetHostName(); // Retrive the Name of HOST
Console.WriteLine(hostName);
// Get the IP
string myIP = Dns.GetHostByName(hostName).AddressList[0].ToString();
metroTextBox1.Text = myIP;
}
private void button7_Click(object sender, EventArgs e)
{
try
{
ini.IniWriteValue("network", "ps4ip", metroTextBox1.Text);
ini.IniWriteValue("network", "pkgPath", pkgText.Text);
}
catch (Exception) { }
}
private void button5_Click(object sender, EventArgs e)
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
dialog.ShowDialog();
pkgText.Text = dialog.SelectedPath;
}
private void button3_Click(object sender, EventArgs e)
{
if (pkgText.Text != "" && pkgText.Text != null && pkgText.Text != string.Empty && metroTextBox1.Text != "" && metroTextBox1.Text != null && metroTextBox1.Text != string.Empty)
{
//Multiple Threads to Download more than one pkg file
th = new Thread(new ThreadStart(StartListen));
th2 = new Thread(new ThreadStart(StartListen));
th3 = new Thread(new ThreadStart(StartListen));
th4 = new Thread(new ThreadStart(StartListen));
drive = Directory.GetDirectoryRoot(pkgText.Text);
if (!is_running)
{
try
{
groupControl1.Enabled = false;
networkGroup.Enabled = false;
//IPAddress localAddr = IPAddress.Parse(metroTextBox1.Text);
myListener = new TcpListener(80);
myListener.Start();
Console.WriteLine("Web Server Running...");
//start the thread which calls the method 'StartListen'
is_running = true;
//Task.Factory.StartNew(StartListen);
//Multi Threading Start
th.Start();
th2.Start();
th3.Start();
th4.Start();
lblProgress.Text = "Running...";
lblProgress.ForeColor = Color.Lime;
}
catch (Exception xx)
{
groupControl1.Enabled = true;
networkGroup.Enabled = true;
lblProgress.Location = new Point(x + 90, lblProgress.Location.Y);
Console.WriteLine("An Exception Occurred while Listening :" + xx.ToString());
lblProgress.Text = "Listening Error";
MessageBox.Show("Listening Error: " + xx.ToString());
lblProgress.ForeColor = Color.Red;
is_running = false;
}
}
else
{
// set everything back to normal
lblProgress.Location = new Point(x+90, lblProgress.Location.Y);
groupControl1.Enabled = true;
networkGroup.Enabled = true;
lblProgress.ForeColor = Color.Red;
lblProgress.Text = "Stopping ...";
myListener.Stop();
th.Abort();
th2.Abort();
th3.Abort();
th4.Abort();
lblProgress.Text = "Stopped";
is_running = false;
}
}
else
{
MessageBox.Show("IP or Pkg Path is empty or invalid", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void groupControl1_DragDrop_1(object sender, DragEventArgs e)
{
string[] pkgFolder = (string[])e.Data.GetData(DataFormats.FileDrop);
pkgText.Text = pkgFolder[0];
}
private void groupControl1_DragEnter_1(object sender, DragEventArgs e)
{
e.Effect = System.Windows.Forms.DragDropEffects.All;
}
private void button4_Click(object sender, EventArgs e)
{
clearDatabase();
if (pkgText.Text != "" && pkgText.Text != null && pkgText.Text != string.Empty && metroTextBox1.Text != "" && metroTextBox1.Text != null && metroTextBox1.Text != string.Empty)
{
string tmpPath = pkgText.Text;
IEnumerable<string> PkgFiles = GetFiles(tmpPath, "*.pkg");
int counter = 0;
progressBar1.Value = 0;
progressBar1.Maximum = PkgFiles.Count();
//SQLiteConnection sql_con = new SQLiteConnection("Data Source=store.db;");
int i = 0;
foreach (string pkgTitle in PkgFiles)
{
try
{
var pkgfile = PS4_Tools.PKG.SceneRelated.Read_PKG(pkgTitle);
pictureBox1.Image = BytesToBitmap(pkgfile.Image);
// safety check
string tid = pkgfile.Param.TitleID;
if (string.IsNullOrEmpty(tid))
tid = "UTID000" + i++;
string title = pkgfile.PS4_Title;
if (string.IsNullOrEmpty(title))
title = "Unknown title: 000" + i;
label9.Text = title;
label10.Text = tid;
label11.Text = calcsize(pkgTitle);
label12.Text = "storedata/ " + tid + ".png";
label13.Text = pkgfile.Param.APP_VER;
label14.Text = pkgfile.Param.PlaystationVersion.ToString();
if (!Directory.Exists(serverRoot + "/storedata"))
Directory.CreateDirectory(serverRoot + "/storedata");
SavePic(BytesToBitmap(pkgfile.Icon), serverRoot + "/storedata/" + tid + ".png");
//start listing on the given port
int rc = count_rows() + 1;
string pkg = "http://" + metroTextBox1.Text + "/" + pkgTitle.Substring(3).Replace(@"\", "/");
if (pkgText.Text.Contains(@"\\"))
{
pkg = "http://" + metroTextBox1.Text + "/network_drive/" + pkgTitle.Replace(@"\", "/");
}
//sql_con.Open();
SQLiteCommand sql_cmd = sql_con.CreateCommand();
sql_cmd.CommandText = "INSERT INTO homebrews (pid, id, name, desc, image, package, version, picpath, desc_1, desc_2, ReviewStars, Size, Author, apptype, pv, main_icon_path, main_menu_pic, releaseddate,number_downloads) VALUES(@pid, @id, @name, @desc, @image, @package, @version, @picpath, @desc_1, @desc_2, @ReviewStars, @Size, @Author, @apptype, @pv, @main_icon_path, @main_menu_pic, @releaseddate, @number_downloads);";
sql_cmd.Parameters.AddWithValue("@pid", rc.ToString());
sql_cmd.Parameters.AddWithValue("@id", tid);
sql_cmd.Parameters.AddWithValue("@name", title);
sql_cmd.Parameters.AddWithValue("@desc", "PKG Added via Store CDN tool");
sql_cmd.Parameters.AddWithValue("@image", "http://" + metroTextBox1.Text + "/storedata/" + tid + ".png");
sql_cmd.Parameters.AddWithValue("@package", pkg);
sql_cmd.Parameters.AddWithValue("@version", pkgfile.Param.APP_VER);
sql_cmd.Parameters.AddWithValue("@picpath", "/user/app/NPXS39041/storedata/" + tid + ".png");
sql_cmd.Parameters.AddWithValue("@desc_1", "");
sql_cmd.Parameters.AddWithValue("@desc_2", "");
sql_cmd.Parameters.AddWithValue("@ReviewStars", "0/5");
sql_cmd.Parameters.AddWithValue("@Size", calcsize(pkgTitle));
sql_cmd.Parameters.AddWithValue("@Author", "Store Tool");
sql_cmd.Parameters.AddWithValue("@apptype", apptype_info(pkgfile.PKG_Type, pkgTitle));
sql_cmd.Parameters.AddWithValue("@pv", pkgfile.Param.PlaystationVersion);
sql_cmd.Parameters.AddWithValue("@main_icon_path", "http://" + metroTextBox1.Text + "/storedata/" + tid + ".png");
sql_cmd.Parameters.AddWithValue("@main_menu_pic", "/user/app/NPXS39041/storedata/" + tid + ".png");
sql_cmd.Parameters.AddWithValue("@releaseddate", DateTime.Now.ToString());
sql_cmd.Parameters.AddWithValue("@number_downloads", "0");
sql_cmd.ExecuteNonQuery();
//main_icon_path
//sql_con.Dispose();
counter++;
//MessageBox.Show("App: " + pkgfile.Param.Title + ", has been successfully Added to the Database\n\nPlease copy the PKG to the pkgs folder in this tools root folder");
}
catch (Exception ex) { }
progressBar1.Value = (int)progressBar1.Value + 1;
progressBar1.Update();
progressBar1.Refresh();
}
PkgCount.Text = "Found " + counter.ToString() + " Valid Pkg(s) of " + PkgFiles.Count().ToString();
System.IO.File.Copy(serverRoot + "/store.db", serverRoot + "/store_readonly.db", true);
counter = 0;
}
else
{
MessageBox.Show("IP or Pkg Path is empty or invalid", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private bool add_to_start(bool add = true)
{
try
{
WshShell wshShell = new WshShell();
IWshRuntimeLibrary.IWshShortcut shortcut;
string startUpFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
if (add)
{
// Create the shortcut
shortcut = (IWshRuntimeLibrary.IWshShortcut)wshShell.CreateShortcut(startUpFolderPath + "\\" + Application.ProductName + ".lnk");
shortcut.TargetPath = Application.ExecutablePath;
shortcut.WorkingDirectory = Application.StartupPath;
shortcut.Description = "Store CDN Server";
// shortcut.IconLocation = Application.StartupPath + @"\App.ico";
shortcut.Save();
}
else
{
System.IO.File.Delete(startUpFolderPath + "\\" + Application.ProductName + ".lnk");
}
return true;
}
catch
{
return false;
}
}
private void button1_Click_3(object sender, EventArgs e)
{
RegistryKey rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (!isautostart)
{
try
{
if (rk == null)
throw new ArgumentException("rip reg key is null");
rk.SetValue("Store CDN Server", Application.ExecutablePath);
MessageBox.Show("CDN Server will now start on Windows Startup");
isautostart = true;
}
catch
{
try
{
add_to_start(true);
}
catch
{
MessageBox.Show("Failed to make shortcut");
}
MessageBox.Show("An error has occured when trying to set the reg key");
}
}
else
{
try
{
if (rk == null)
throw new ArgumentException("rip reg key is null");
rk.DeleteValue("Store CDN Server", false);
MessageBox.Show("Booting on statup is now disabled");
isautostart = false;
}
catch
{
try
{
add_to_start(false);
}
catch { };
MessageBox.Show("An error has occured when trying to delete the reg key");
}
}
button1.Text = isautostart ? "Disable" : "Enable";
button1.ForeColor = isautostart ? Color.Red : Color.Green;
}
}
}