1+ using System ;
2+ using System . Diagnostics ;
3+ using System . IO ;
4+ using System . Net ;
5+ using System . Reflection ;
6+ using System . Windows . Forms ;
7+
8+ namespace SwitchInputLanguage
9+ {
10+ public static class UpdateChecker
11+ {
12+ private const string Owner = "sumonchai" ;
13+ private const string Repo = "Switch-Input-Language" ;
14+ private const string ApiUrl = "https://api.github.com/repos/" + Owner + "/" + Repo + "/releases/latest" ;
15+
16+ private static readonly Version CurrentVersion = Assembly . GetExecutingAssembly ( ) . GetName ( ) . Version ;
17+
18+ public static void CheckForUpdate ( Form owner )
19+ {
20+ try
21+ {
22+ var request = ( HttpWebRequest ) WebRequest . Create ( ApiUrl ) ;
23+ request . UserAgent = "SwitchInputLanguage" ;
24+ request . Timeout = 8000 ;
25+
26+ using var response = request . GetResponse ( ) ;
27+ using var reader = new StreamReader ( response . GetResponseStream ( ) ) ;
28+ string json = reader . ReadToEnd ( ) ;
29+
30+ string tag = ParseTag ( json ) ;
31+ if ( string . IsNullOrEmpty ( tag ) ) return ;
32+
33+ string versionStr = tag . TrimStart ( 'v' , 'V' , 'r' ) ;
34+ if ( ! Version . TryParse ( versionStr , out Version latest ) ) return ;
35+
36+ if ( latest > CurrentVersion )
37+ {
38+ var result = MessageBox . Show (
39+ $ "มีเวอร์ชันใหม่: { tag } \n เวอร์ชันปัจจุบัน: { CurrentVersion } \n \n ต้องการดาวน์โหลดเลยหรือไม่?",
40+ "พบการอัปเดต" ,
41+ MessageBoxButtons . YesNo ,
42+ MessageBoxIcon . Information ) ;
43+
44+ if ( result == DialogResult . Yes )
45+ {
46+ string downloadUrl = ParseDownloadUrl ( json ) ;
47+ if ( ! string . IsNullOrEmpty ( downloadUrl ) )
48+ Process . Start ( new ProcessStartInfo ( downloadUrl ) { UseShellExecute = true } ) ;
49+ }
50+ }
51+ else
52+ {
53+ MessageBox . Show ( "คุณใช้เวอร์ชันล่าสุดแล้ว" , "ไม่มีการอัปเดต" , MessageBoxButtons . OK , MessageBoxIcon . Information ) ;
54+ }
55+ }
56+ catch ( WebException )
57+ {
58+ MessageBox . Show ( "ไม่สามารถเชื่อมต่ออินเทอร์เน็ตได้" , "ข้อผิดพลาด" , MessageBoxButtons . OK , MessageBoxIcon . Warning ) ;
59+ }
60+ catch ( Exception ex )
61+ {
62+ MessageBox . Show ( $ "เกิดข้อผิดพลาด: { ex . Message } ", "ข้อผิดพลาด" , MessageBoxButtons . OK , MessageBoxIcon . Error ) ;
63+ }
64+ }
65+
66+ private static string ParseTag ( string json )
67+ {
68+ int i = json . IndexOf ( "\" tag_name\" " ) ;
69+ if ( i < 0 ) return null ;
70+ int q1 = json . IndexOf ( '"' , i + 10 ) ;
71+ int q2 = json . IndexOf ( '"' , q1 + 1 ) ;
72+ return q1 >= 0 && q2 > q1 ? json . Substring ( q1 + 1 , q2 - q1 - 1 ) : null ;
73+ }
74+
75+ private static string ParseDownloadUrl ( string json )
76+ {
77+ int i = json . IndexOf ( "\" browser_download_url\" " ) ;
78+ if ( i < 0 ) return null ;
79+ int q1 = json . IndexOf ( '"' , i + 23 ) ;
80+ int q2 = json . IndexOf ( '"' , q1 + 1 ) ;
81+ return q1 >= 0 && q2 > q1 ? json . Substring ( q1 + 1 , q2 - q1 - 1 ) : null ;
82+ }
83+ }
84+ }
0 commit comments