-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFiles.txt
More file actions
641 lines (535 loc) · 18.3 KB
/
Files.txt
File metadata and controls
641 lines (535 loc) · 18.3 KB
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
/*
File containing routes for the interweb, if you want to create your own server,
then use these routes or modify them for your server.
*/
namespace PaintPower.Networking;
public class Routes
{
// Server check routes
public static string serverCheck()
{
return "api/servercheck/";
}
public static string checkActiveServer()
{
return serverCheck();
}
// Create a new project without uploading it.
public static string createNew()
{
return "api/projects/create";
}
// Upload project routes
public static string uploadNew() {
return "api/projects/new/upload/paintfile/";
}
public static string uploadUpdate(string id)
{
return $"api/projects/{id}/upload/paintfile/";
}
// Download project routes
public static string downloadProject(string id)
{
return $"api/projects/{id}/download";
}
// Mystuff routes
public static string userProjectsRoute(string username = "")
{
if (username != string.Empty)
{
return $"api/list/projects/{username}";
}
return "api/mystuff/projects";
}
// For testing a custom server.
public static string testServerListProjects()
{
return "api/listProjects/";
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using PaintPower.ProjectSystem;
using PaintPower.Logging;
namespace PaintPower.Networking;
// Networking class for the PaintPower Engine.
// Mainly to be used for the 'Coco xPaint Project', but it will lie
// here in the engine because it's open source. So anyone can create their own server.
public class Server
{
//*--- Domain security. ---*//
private static List<Domain> AllowedDomainsList = new List<Domain>();
private bool isConnected = false;
public void AllowDomain(Domain domain) => AllowedDomainsList.Add(domain);
public bool IsDomainAllowed(Domain domain) => AllowedDomainsList.Contains(domain);
public void ClearAllowedDomains() => AllowedDomainsList.Clear();
public void RemoveDomain(Domain domain) { AllowedDomainsList.Remove(domain); }
public Domain CurrentDomain = new Domain("www.cocoink.ink/f/PaintPower");
public void closeAllConnections()
{
AllowedDomainsList.Clear();
}
// Make a valid url.
public string makeUrl(string addon = "")
{
string url = $"{URLifyer.URLify(CurrentDomain)}{addon}";
Log.QuickLog($"Url made: {url}");
return url;
}
// Create, register, and add default domains.
public void loadDefaultDomains()
{
// Clear old list
AllowedDomainsList.Clear();
// Create Coco links, Paint links, random links, and more!
// Creating a custom server? Make a issue on GitHub and I'll add it here!
Domain d1 = new Domain("xpaint.cocoink.ink");
Domain d2 = new Domain("paint.cocoink.ink");
Domain d3 = new Domain("127.0.0.1:5500/f/xPaint");
Domain d4 = new Domain("127.0.0.1:5000/f/xPaint");
Domain d5 = new Domain("127.0.0.1:3000/f/xPaint");
Domain d12 = new Domain("0.0.0.0:5500/f/xPaint");
Domain d6 = new Domain("127.0.0.1:8000");
Domain d7 = new Domain("localhost:5500");
Domain d8 = new Domain("localhost:5000");
Domain d9 = new Domain("localhost:8000");
Domain d10 = new Domain("localhost:3000");
Domain d11 = new Domain("github.com");
Domain d13 = new Domain("paint-website.onrender.com");
Domain d14 = new Domain("paintpower.cocoink.ink");
Domain d15 = new Domain("www.cocoink.ink");
Domain d16 = new Domain("www.cocoink.ink/f/xPaint");
Domain d17 = new Domain("www.cocoink.ink/f/Paint");
Domain d18 = new Domain("www.cocoink.ink/f/PaintPower");
Domain d19 = new Domain("negro.org");
Domain d20 = new Domain("example.com");
// Add to list
AllowDomain(d1); AllowDomain(d2); AllowDomain(d3); AllowDomain(d4); AllowDomain(d5);
AllowDomain(d6); AllowDomain(d7); AllowDomain(d8); AllowDomain(d9); AllowDomain(d10);
AllowDomain(d11); AllowDomain(d12); AllowDomain(d13); AllowDomain(d14); AllowDomain(d15);
AllowDomain(d16); AllowDomain(d17); AllowDomain(d18); AllowDomain(d19); AllowDomain(d20);
#if DEBUG
setActiveDomain(d3);
#else
setActiveDomain(d16);
#endif
}
public void setActiveDomain(Domain domain)
{
CurrentDomain = domain;
}
//*--- Networking ---*//
public async Task InitServer()
{
loadDefaultDomains();
isConnected = await checkConnection();
}
public async Task<bool> checkConnection()
{
var domain = CurrentDomain;
if (domain == null) throw new ArgumentNullException(nameof(domain));
if (!IsDomainAllowed(domain)) throw new UnauthorizedAccessException("Domain not allowed");
try
{
return await Net.PerformGetRequest(makeUrl(Routes.checkActiveServer())) == "Ok.";
}
catch
{
return false;
}
}
public async Task<object?> GetFromServer(string url)
{
var domain = CurrentDomain;
if (domain == null) throw new ArgumentNullException(nameof(domain));
if (!IsDomainAllowed(domain)) throw new UnauthorizedAccessException("Domain not allowed");
return await Net.PerformGetRequest(url);
}
/* Download a project made by the user */
public async Task DownloadProject(string savePath)
{
string url = URLifyer.URLify(CurrentDomain);
await Net.DownloadFileAsync(url, savePath);
}
/* Save the project and load it into the editor. */
public async Task DownloadProjectAndLoad(string savePath)
{
try
{
await DownloadProject(savePath);
}
catch (Exception e)
{
Log.QuickLog(e.Message);
}
PaintPower_Engine.App.OpenProjectFile(savePath);
}
public async Task UploadProject(PaintProject project)
{
#pragma warning disable
PaintPower_Engine.App.RunSavingAnimation();
try
{
await Net.UploadFileAsync(
$"{URLifyer.URLify(CurrentDomain)}api/upload/projects/1/",
project.ProjectPath,
project.Metadata.name // send project title
);
}
finally
{
MainWindow.App._isSavingAnimationRunning = false;
}
}
// If the user is signed in, then get a list of their projects from the server.
public async Task ListUserProjects()
{
string url =
#if DEBUG
makeUrl(Routes.testServerListProjects());
#else
makeUrl(Routes.userProjectsRoute());
#endif
GetFromServer(url); // Do nothing with the data for now...
}
public string Username { get; set; }
public async Task<bool> Login(string username, string password)
{
if (await IsLoggedIn()) await Logout();
await Net.Login(username, password);
if (await IsLoggedIn()) Username = username;
return await IsLoggedIn();
}
public async Task Logout()
{
if (await IsLoggedIn()) await Net.PerformPostRequest(PaintPower_Engine.App.server.makeUrl("logout"), new Dictionary<string, bool> {{ "redirect", false }});
if (!await IsLoggedIn()) Username = "";
}
public async Task<bool> IsLoggedIn()
{
var response = await Net.PerformGetRequest(makeUrl("api/whoami"));
return response != null && !response.Contains("Not logged in");
}
public Server()
{
InitServer();
}
}
/*
Actual networking
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using PaintPower;
using PaintPower.Logging;
public class Net
{
private static readonly HttpClientHandler handler = new HttpClientHandler
{
UseCookies = true,
CookieContainer = new CookieContainer(),
AllowAutoRedirect = true
};
// Shared HttpClient instance (recommended for performance)
private static readonly HttpClient client = new HttpClient(handler);
private static async Task<string?> getCSRF_Token()
{
return PaintPower_Engine.App.server.CurrentDomain?.CSRF_Token;
}
// GET request method
public static async Task<string?> PerformGetRequest(string url)
{
try
{
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode(); // Throws if not 2xx
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("GET Response:");
Console.WriteLine(responseBody);
return responseBody;
}
catch (HttpRequestException e)
{
Console.WriteLine($"GET request error: {e.Message}");
return null;
}
}
// POST request method
public static async Task PerformPostRequest<T>(string url, T data)
{
try
{
string json = JsonSerializer.Serialize(data);
var content = new StringContent(json, Encoding.UTF8, "application/json");
Log.QuickLog($"Body: {content}");
HttpResponseMessage response = await client.PostAsync(url, content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("POST Response:");
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine($"POST request error: {e.Message}");
}
}
public static async Task DownloadFileAsync(string url, string destinationPath)
{
try
{
using var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
response.EnsureSuccessStatusCode();
await using var stream = await response.Content.ReadAsStreamAsync();
await using var fileStream = File.Create(destinationPath);
byte[] buffer = new byte[81920]; // 80 KB chunks
int bytesRead;
while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await fileStream.WriteAsync(buffer, 0, bytesRead);
}
}
catch (Exception ex)
{
Console.WriteLine($"Download error: {ex.Message}");
}
}
public static async Task UploadFileAsync(string url, string filePath, string projectTitle)
{
Debug.WriteLine(url);
try
{
using var form = new MultipartFormDataContent();
await using var fileStream = File.OpenRead(filePath);
var fileContent = new StreamContent(fileStream);
fileContent.Headers.ContentType =
new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
// File field (multer expects "file")
form.Add(fileContent, "file", Path.GetFileName(filePath));
// Add project title
form.Add(new StringContent(projectTitle, Encoding.UTF8), "title");
using var response = await client.PostAsync(url, form);
response.EnsureSuccessStatusCode();
Debug.WriteLine("Upload complete.");
}
catch (Exception ex)
{
Debug.WriteLine($"Upload error: {ex.Message}");
}
}
public static async Task<bool> Login(string username, string password)
{
try
{
var data = new Dictionary<string, string>
{
{ "username", username },
{ "password", password }
};
var content = new FormUrlEncodedContent(data);
var response = await client.PostAsync(
PaintPower_Engine.App.server.makeUrl("login"),
content
);
Log.QuickLog($"Login status: {response.GetHashCode()}");
// If login fails, server returns 400 with text
if (!response.IsSuccessStatusCode)
return false;
// If login succeeds, server redirects to "/"
return true;
}
catch (Exception ex)
{
Log.QuickLog($"Login error: {ex.Message}");
return false;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PaintPower.Networking;
// A class for a domain.
public class Domain
{
public bool IsConnected { get; set; }
public bool IsDisconnected { get; set; }
public bool IsAllowed { get; set; }
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public string Type { get; set; } = string.Empty;
public string Protocol = string.Empty;
public string Host = string.Empty; public static string Port = string.Empty;
public string? Username = string.Empty;
public string? Password = string.Empty;
public string domain = string.Empty;
public string CSRF_Token = string.Empty;
public Domain(string nDomain, string nProtocol = "http", string nName = "", string nHost = "", string nPort = "") {
// Initalize domain
IsAllowed = false;
IsConnected = false;
IsDisconnected = false;
Name = nName;
Host = nHost;
Port = nPort;
domain = nDomain;
Protocol = nProtocol;
}
public override string ToString()
{
return $"Domain: {Name} ({Protocol}://{Host}:{Port})";
}
}
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Platform.Storage;
using PaintPower.Dialogs;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Text.Json;
using System.Threading.Tasks;
namespace PaintPower.ProjectSystem;
public class PaintProject
{
public string ProjectPath { get; set; } = ""; // Path to zip file.
public TempWorkspace Workspace { get; }
public ProjectMetadata Metadata { get; set; }
public List<PaintSprite> Sprites { get; private set; } = new(); // Sprite list
public string ProjectName { get; private set; } = string.Empty;
public PaintProject()
{
Workspace = new TempWorkspace();
Metadata = new ProjectMetadata();
}
// -------------------------
// CREATE NEW PROJECT
// -------------------------
public void CreateNew()
{
var loader = new ProjectLoader();
loader.LoadDefaultProject(this);
// ProjectPath stays empty → user must Save As
ProjectPath = "";
Metadata = new ProjectMetadata { name = "Untitled", OpenFile = null };
SaveMetadata();
}
// -------------------------
// SAVE NEW PROJECT
// -------------------------
public async Task<ProjectLoaderResult> SaveNewProject(Window owner)
{
var savePicker = await owner.StorageProvider.SaveFilePickerAsync(
new FilePickerSaveOptions
{
Title = "Create New Project",
DefaultExtension = "xPaint",
SuggestedFileName = $"{Metadata.name}.xPaint",
ShowOverwritePrompt = true
});
if (savePicker == null)
{
return new ProjectLoaderResult
{
Mode = ProjectLoaderMode.New,
Path = string.Empty
};
}
PaintPower_Engine.window.Title = $"PaintPower - {Metadata.name}";
return new ProjectLoaderResult
{
Mode = ProjectLoaderMode.New,
Path = savePicker.Path.LocalPath
};
}
// -------------------------
// LOAD EXISTING PROJECT
// -------------------------
public void Load(string projectPath)
{
ProjectPath = projectPath;
if (Directory.Exists(Workspace.Root)) { }
// Extract ZIP into temp workspace
ZipFile.ExtractToDirectory(projectPath, Workspace.Root, overwriteFiles: true);
// Load metadata
string metaPath = Path.Combine(Workspace.Root, "project.json");
if (File.Exists(metaPath))
{
string json = File.ReadAllText(metaPath);
Metadata = JsonSerializer.Deserialize<ProjectMetadata>(json) ?? new ProjectMetadata();
}
else
{
Metadata = new ProjectMetadata();
}
// Now that the project is loaded
LoadSprites();
}
// -------------------------
// SAVE PROJECT
// -------------------------
public async Task SaveToDisk()
{
// Always update metadata first
SaveMetadata();
// If no path yet -> ask user where to save
if (string.IsNullOrWhiteSpace(ProjectPath))
{
PaintPower_Engine.App.isNewProject = true; // Keep isNewProject checks
var result = await SaveNewProject(MainWindow.window);
if (string.IsNullOrWhiteSpace(result.Path))
return; // user cancelled
ProjectPath = result.Path;
PaintPower_Engine.App.isNewProject = false;
}
// Recreate ZIP
// Run ZIP creation on background thread
await Task.Run(() =>
{
if (File.Exists(ProjectPath))
File.Delete(ProjectPath);
ZipFile.CreateFromDirectory(Workspace.Root, ProjectPath);
});
}
private void SaveMetadata()
{
string json = JsonSerializer.Serialize(Metadata, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(Path.Combine(Workspace.Root, "project.json"), json);
}
public void LoadSprites()
{
string spritesDir = Path.Combine(Workspace.ItemsDir, "sprites");
if (!Directory.Exists(spritesDir))
return;
foreach (var dir in Directory.GetDirectories(spritesDir))
{
var sprite = new PaintSprite
{
Name = Path.GetFileName(dir),
SpriteFolder = dir
};
Sprites.Add(sprite);
}
}
}
// -------------------------
// PROJECT METADATA STRUCT
// -------------------------
public class ProjectMetadata
{
public string name { get; set; } = "Untitled Project";
public string? OpenFile { get; set; }
}