-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathProgram.cs
221 lines (182 loc) · 7.83 KB
/
Program.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
using Microsoft.EntityFrameworkCore;
using System.IO.Compression;
using Amazon.S3;
using Amazon.S3.Transfer;
using System.Text.Json;
using Amazon.S3.Model;
using Amazon;
using System.Diagnostics;
namespace portaBLe
{
public class AppContext : DbContext
{
public AppContext(DbContextOptions<AppContext> options)
: base(options)
{ }
public DbSet<Player> Players { get; set; }
public DbSet<Score> Scores { get; set; }
public DbSet<Leaderboard> Leaderboards { get; set; }
}
public class Program
{
public static RootObject ParseJson(string path)
{
using FileStream openStream = File.OpenRead(path);
using ZipArchive archive = new ZipArchive(openStream, ZipArchiveMode.Read);
ZipArchiveEntry entry = archive.Entries[0];
using Stream entryStream = entry.Open();
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
return JsonSerializer.Deserialize<RootObject>(entryStream, options);
}
public static void InitializeDatabase(IHost host)
{
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
var dbContext = services.GetRequiredService<AppContext>();
dbContext.Database.EnsureCreated();
try {
dbContext.Database.Migrate();
} catch { }
}
}
public static async Task ImportDump(IHost host)
{
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
var dbContextFactory = services.GetRequiredService<IDbContextFactory<AppContext>>();
var env = services.GetRequiredService<IWebHostEnvironment>();
using var dbContext = dbContextFactory.CreateDbContext();
var dump = ParseJson(env.WebRootPath + "/dump.zip");
DataImporter.ImportJsonData(dump, dbContext);
await ScoresRefresh.Refresh(dbContext);
await PlayersRefresh.Refresh(dbContext);
await LeaderboardsRefresh.Refresh(dbContext);
}
}
private static string ReconstructKey(string shuffledKey, int[] indices)
{
char[] originalKey = new char[indices.Length];
for (int i = 0; i < indices.Length; i++)
{
originalKey[indices[i]] = shuffledKey[i];
}
return new string(originalKey);
}
public static AmazonS3Client GetS3Client()
{
string shuffledAccessKey = "7LUZH3R3MAAIU3KED3FD";
int[] accessKeyIndices = { 18, 6, 12, 8, 11, 9, 16, 10, 19, 0, 3, 2, 14, 17, 1, 13, 15, 4, 5, 7 };
string shuffledSecretKey = "ms9+qvcBzcLHCVhClxPALWOALxLBcd6EahJFxfQ9";
int[] secretKeyIndices = { 31, 13, 29, 0, 19, 14, 3, 2, 38, 5, 7, 24, 12, 23, 8, 17, 25, 21, 4, 39, 20, 28, 33, 1, 6, 26, 15, 36, 18, 16, 34, 22, 30, 37, 9, 35, 11, 32, 27, 10 };
string accessKey = ReconstructKey(shuffledAccessKey, accessKeyIndices);
string secretKey = ReconstructKey(shuffledSecretKey, secretKeyIndices);
return new AmazonS3Client(accessKey, secretKey, RegionEndpoint.USEast1);
}
public static async Task<string> UploadDatabaseAsync(string filePath)
{
var client = GetS3Client();
var fileTransferUtility = new TransferUtility(client);
// Create a unique name for the database file
var dbName = $"db-{DateTime.UtcNow:yyyyMMddHHmmss}-{new Random().Next(1000, 9999)}.db";
var key = $"{dbName}";
await fileTransferUtility.UploadAsync(filePath, "portabledbs", key);
// Save the database name to a file in wwwroot
File.WriteAllText(Path.Combine("wwwroot", "current_db_name.txt"), dbName);
return dbName;
}
public static async Task<bool> DownloadDatabaseFileAsync(string fileName, string localPath)
{
try
{
var request = new GetObjectRequest
{
BucketName = "portabledbs",
Key = fileName
};
using (var response = await GetS3Client().GetObjectAsync(request))
using (var responseStream = response.ResponseStream)
using (var fileStream = new FileStream(localPath, FileMode.Create, FileAccess.Write))
{
await responseStream.CopyToAsync(fileStream);
}
return true;
}
catch (AmazonS3Exception e)
{
if (e.ErrorCode == "NoSuchKey")
{
Console.WriteLine("File not found in S3.");
return false;
}
throw; // Re-throw the exception if it's not handled here.
}
}
public static async Task DownloadDatabaseIfNeeded(string webRootPath)
{
var dbNameFile = Path.Combine(webRootPath, "current_db_name.txt");
if (File.Exists(dbNameFile))
{
var dbName = File.ReadAllText(dbNameFile);
var localDbPath = Path.Combine(webRootPath, "Database.db");
if (!File.Exists(localDbPath))
{
bool downloaded = await DownloadDatabaseFileAsync(dbName, localDbPath);
if (downloaded)
{
Console.WriteLine("Database downloaded successfully.");
}
else
{
Console.WriteLine("Failed to download database.");
}
}
}
else
{
Console.WriteLine("Database name file not found.");
}
}
public string GetCurrentDatabaseName()
{
var path = Path.Combine("wwwroot", "current_db_name.txt");
return File.ReadAllText(path);
}
public static async Task Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
try {
// Remove downloading remote DB if you want to recreate it fresh
await DownloadDatabaseIfNeeded(builder.Environment.WebRootPath);
// Store your version of DB in S3 for deploy
//await UploadDatabaseAsync($"{builder.Environment.WebRootPath}/Database.db");
var connectionString = $"Data Source={builder.Environment.WebRootPath}/Database.db;";
builder.Services.AddDbContextFactory<AppContext>(options => options.UseSqlite(connectionString));
builder.Services.AddRazorPages();
var app = builder.Build();
InitializeDatabase(app);
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
// JSON zip to Database. Takes 5-20 minutes and 8-15GB of RAM
//await ImportDump(app);
await app.RunAsync();
} catch (Exception e) {
Console.WriteLine(e.Message + " " + e.StackTrace);
}
}
}
}