Skip to content

Commit 235fe40

Browse files
committed
Added update checker
1 parent 2824568 commit 235fe40

File tree

5 files changed

+159
-13
lines changed

5 files changed

+159
-13
lines changed

.idea/.idea.CutCode/.idea/workspace.xml

Lines changed: 30 additions & 12 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

CutCode.CrossPlatform/App.axaml.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using System;
22
using System.Diagnostics;
33
using System.Drawing;
4+
using System.Threading;
45
using Avalonia;
56
using Avalonia.Controls.ApplicationLifetimes;
67
using Avalonia.Markup.Xaml;
@@ -45,6 +46,8 @@ public override void OnFrameworkInitializationCompleted()
4546
{
4647
DataBaseManager.Current.ChangeTheme(ThemeService.Current.IsLightTheme);
4748
};
49+
var updateThread = new Thread(UpdateChecker.Run);
50+
updateThread.Start();
4851
}
4952
base.OnFrameworkInitializationCompleted();
5053
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
using System;
2+
using System.Net;
3+
using System.Net.Http;
4+
using System.Text;
5+
using System.Threading.Tasks;
6+
using Avalonia.Threading;
7+
using CutCode.CrossPlatform.Interfaces;
8+
using Newtonsoft.Json;
9+
10+
namespace CutCode.CrossPlatform.Helpers
11+
{
12+
public class UpdateReqModel
13+
{
14+
public bool NewUpdate { get; set; }
15+
public string UpdateVersion { get; set; }
16+
}
17+
public static class UpdateChecker
18+
{
19+
private static string _updateUrl = "http://127.0.0.1:7676";
20+
private static HttpClient client = new HttpClient();
21+
private static string _currentVersion = "v3.0.0";
22+
public static async void Run()
23+
{
24+
await Task.Delay(TimeSpan.FromSeconds(4));
25+
var internetAvailable = IsInternetAvailable();
26+
if (!internetAvailable) return;
27+
try
28+
{
29+
var response = await client.GetAsync($"{_updateUrl}/check_update/{_currentVersion}");
30+
if (!response.IsSuccessStatusCode) return;
31+
string responseString = await response.Content.ReadAsStringAsync();
32+
var responseJson = JsonConvert.DeserializeObject<UpdateReqModel>(responseString);
33+
if (responseJson is { NewUpdate: true })
34+
{
35+
await Dispatcher.UIThread.InvokeAsync(() =>
36+
{
37+
NotificationManager.Current.CreateNotification(
38+
"Update",
39+
$"New version({responseJson.UpdateVersion}) is available. Download it from the release page on the Github repository",
40+
10);
41+
});
42+
}
43+
}
44+
catch
45+
{
46+
return;
47+
}
48+
}
49+
50+
public static bool IsInternetAvailable()
51+
{
52+
try
53+
{
54+
using (var client = new WebClient())
55+
using (client.OpenRead("http://google.com/generate_204"))
56+
return true;
57+
}
58+
catch
59+
{
60+
return false;
61+
}
62+
}
63+
}
64+
}

CutCode.CrossPlatform/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ public static void Main(string[] args)
2424
public static AppBuilder BuildAvaloniaApp()
2525
=> AppBuilder.Configure<App>()
2626
.UsePlatformDetect()
27-
.LogToTrace(level: LogEventLevel.Information)
27+
.LogToTrace()
2828
.UseReactiveUI();
2929
}
3030
}

CutCodeAPI/update_API.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
from fastapi import FastAPI, Depends, HTTPException, status
2+
from fastapi.middleware.cors import CORSMiddleware
3+
from fastapi.security import HTTPBasic, HTTPBasicCredentials
4+
from fastapi import Body
5+
from decouple import config
6+
from typing import List
7+
import uvicorn
8+
9+
10+
11+
12+
app = FastAPI()
13+
app.add_middleware(
14+
CORSMiddleware,
15+
allow_origins=["*"],
16+
allow_credentials=True,
17+
allow_methods=["*"],
18+
allow_headers=["*"],
19+
)
20+
21+
username = config("UpdateUserName")
22+
password = config("UpdatePassword")
23+
security = HTTPBasic()
24+
async def authorize(credentials: HTTPBasicCredentials):
25+
if credentials.username == username and credentials.password == password:
26+
return True
27+
else:
28+
return False
29+
30+
versions:List[str] = ["v3.0.0"]
31+
32+
# For adding updates
33+
@app.post("/add_update")
34+
async def add_update(req:str = Body(...), credentials: HTTPBasicCredentials = Depends(security)):
35+
if await authorize(credentials):
36+
versions.append(req)
37+
return {"Error":False, "ErrorMessage":""}
38+
else:
39+
raise HTTPException(
40+
status_code=status.HTTP_401_UNAUTHORIZED,
41+
detail="You are not authorized to add updates",
42+
headers={"WWW-Authenticate": "Basic"}
43+
)
44+
45+
46+
# For requesting for updates
47+
@app.get("/check_update/{req}")
48+
async def check_update(req:str):
49+
try:
50+
if versions.index(req) != versions[-1]:
51+
return {"NewUpdate":True, "UpdateVersion":versions[-1]}
52+
else:
53+
return {"NewUpdate":False, "UpdateVersion":versions[-1]}
54+
except ValueError as e:
55+
print(e)
56+
return {"NewUpdate":True, "UpdateVersion":versions[-1]}
57+
58+
59+
60+
if __name__ == "__main__":
61+
uvicorn.run("update_API:app", port=7676, host='0.0.0.0', reload=True)

0 commit comments

Comments
 (0)