Repository navigation
Expand file tree
/
Copy pathOneNoteSync.cs
More file actions
819 lines (706 loc) · 31.5 KB
/
Copy pathOneNoteSync.cs
File metadata and controls
819 lines (706 loc) · 31.5 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
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
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace NoteUI;
public class OneNoteSync : IDisposable
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNameCaseInsensitive = true,
};
private readonly HttpClient _http = new() { Timeout = TimeSpan.FromSeconds(15) };
private string _clientId = "";
private string? _accessToken;
private string? _refreshToken;
private string? _userName;
private Timer? _refreshTimer;
private string? _notebookId;
private string? _sectionId;
private const string GraphBase = "https://graph.microsoft.com/v1.0";
private const string NotebookName = "NoteUI";
private const string SectionName = "Notes";
private const string MetaPrefix = "<!-- noteui-meta:";
private const string MetaSuffix = ":noteui-meta -->";
public bool IsConfigured => !string.IsNullOrEmpty(_clientId);
public bool IsConnected => _accessToken != null;
public string? UserName => _userName;
public void Configure(string clientId)
{
_clientId = clientId;
}
public string? GetRefreshToken() => _refreshToken;
// ── OAuth2 Interactive Sign-In (PKCE) ───────────────────────
public async Task<(bool Success, string? Error)> SignInAsync()
{
if (!IsConfigured) return (false, Lang.T("onenote_not_configured"));
try
{
var codeVerifier = GenerateCodeVerifier();
var codeChallenge = GenerateCodeChallenge(codeVerifier);
var state = Guid.NewGuid().ToString("N");
var listener = new HttpListener();
var port = FindFreePort();
var redirectUri = $"http://localhost:{port}/";
listener.Prefixes.Add(redirectUri);
listener.Start();
var scopes = Uri.EscapeDataString("Notes.ReadWrite Mail.Read User.Read offline_access");
var authUrl = "https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize"
+ $"?client_id={_clientId}"
+ $"&redirect_uri={Uri.EscapeDataString(redirectUri)}"
+ "&response_type=code"
+ $"&scope={scopes}"
+ $"&state={state}"
+ $"&code_challenge={codeChallenge}"
+ "&code_challenge_method=S256";
Process.Start(new ProcessStartInfo(authUrl) { UseShellExecute = true });
var contextTask = listener.GetContextAsync();
var completed = await Task.WhenAny(contextTask, Task.Delay(TimeSpan.FromMinutes(2)));
if (completed != contextTask)
{
listener.Stop();
return (false, Lang.T("timeout"));
}
var context = await contextTask;
var query = context.Request.QueryString;
var code = query["code"];
var returnedState = query["state"];
var authError = query["error_description"];
// Show success or error page depending on result
var isSuccess = !string.IsNullOrEmpty(code) && returnedState == state;
var responseHtml = isSuccess
? "<html><body style='font-family:Segoe UI;text-align:center;padding:60px'>"
+ "<h2>" + Lang.T("onenote_auth_success") + "</h2>"
+ "<p>" + Lang.T("close_window") + "</p></body></html>"
: "<html><body style='font-family:Segoe UI;text-align:center;padding:60px'>"
+ "<h2>" + Lang.T("auth_cancelled") + "</h2></body></html>";
var buffer = Encoding.UTF8.GetBytes(responseHtml);
context.Response.ContentType = "text/html; charset=utf-8";
context.Response.ContentLength64 = buffer.Length;
await context.Response.OutputStream.WriteAsync(buffer);
context.Response.Close();
listener.Stop();
if (!isSuccess)
return (false, authError ?? Lang.T("auth_cancelled"));
// Exchange code for tokens
var tokenPayload = new Dictionary<string, string>
{
["client_id"] = _clientId,
["code"] = code,
["redirect_uri"] = redirectUri,
["grant_type"] = "authorization_code",
["code_verifier"] = codeVerifier,
["scope"] = "Notes.ReadWrite Mail.Read User.Read offline_access"
};
var tokenResp = await _http.PostAsync(
"https://login.microsoftonline.com/consumers/oauth2/v2.0/token",
new FormUrlEncodedContent(tokenPayload));
if (!tokenResp.IsSuccessStatusCode)
{
var errBody = await tokenResp.Content.ReadAsStringAsync();
return (false, $"Token error: {tokenResp.StatusCode}");
}
var tokenJson = await tokenResp.Content.ReadFromJsonAsync<JsonElement>();
ApplyTokenResponse(tokenJson);
// Fetch user display name
await FetchUserName();
return (true, null);
}
catch (Exception ex)
{
return (false, ex.Message);
}
}
// ── Refresh Token Sign-In ───────────────────────────────────
public async Task<bool> SignInWithRefreshTokenAsync(string refreshToken)
{
if (!IsConfigured || string.IsNullOrEmpty(refreshToken)) return false;
try
{
_refreshToken = refreshToken;
return await RefreshAccessTokenAsync();
}
catch { return false; }
}
private async Task<bool> RefreshAccessTokenAsync()
{
if (string.IsNullOrEmpty(_refreshToken) || string.IsNullOrEmpty(_clientId))
return false;
try
{
var payload = new Dictionary<string, string>
{
["client_id"] = _clientId,
["refresh_token"] = _refreshToken,
["grant_type"] = "refresh_token",
["scope"] = "Notes.ReadWrite Mail.Read User.Read offline_access"
};
var resp = await _http.PostAsync(
"https://login.microsoftonline.com/consumers/oauth2/v2.0/token",
new FormUrlEncodedContent(payload));
if (!resp.IsSuccessStatusCode) return false;
var json = await resp.Content.ReadFromJsonAsync<JsonElement>();
ApplyTokenResponse(json);
await FetchUserName();
return true;
}
catch { return false; }
}
private void ApplyTokenResponse(JsonElement json)
{
_accessToken = json.GetProperty("access_token").GetString();
if (json.TryGetProperty("refresh_token", out var rtProp))
_refreshToken = rtProp.GetString();
_http.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", _accessToken);
var expiresIn = json.TryGetProperty("expires_in", out var exp) ? exp.GetInt32() : 3600;
_refreshTimer?.Dispose();
_refreshTimer = new Timer(async _ => await RefreshAccessTokenAsync(),
null, TimeSpan.FromSeconds(Math.Max(60, expiresIn - 120)), Timeout.InfiniteTimeSpan);
}
private async Task FetchUserName()
{
try
{
var resp = await _http.GetAsync($"{GraphBase}/me?$select=displayName,mail");
if (resp.IsSuccessStatusCode)
{
var json = await resp.Content.ReadFromJsonAsync<JsonElement>();
_userName = json.TryGetProperty("displayName", out var dn) ? dn.GetString() : null;
if (string.IsNullOrEmpty(_userName) && json.TryGetProperty("mail", out var m))
_userName = m.GetString();
}
}
catch { }
}
// ── Notebook / Section management ───────────────────────────
private async Task<bool> EnsureNotebookAndSection(CancellationToken ct = default)
{
if (_notebookId != null && _sectionId != null) return true;
try
{
// Find notebook by listing all and matching client-side (OData $filter unreliable on OneNote API)
var nbResp = await _http.GetAsync($"{GraphBase}/me/onenote/notebooks?$select=id,displayName&$top=50", ct);
if (!nbResp.IsSuccessStatusCode) return false;
var nbJson = await nbResp.Content.ReadFromJsonAsync<JsonElement>(cancellationToken: ct);
string? foundNbId = null;
foreach (var nb in nbJson.GetProperty("value").EnumerateArray())
{
var name = nb.TryGetProperty("displayName", out var dn) ? dn.GetString() : null;
if (string.Equals(name, NotebookName, StringComparison.OrdinalIgnoreCase))
{
foundNbId = nb.GetProperty("id").GetString();
break;
}
}
if (foundNbId != null)
{
_notebookId = foundNbId;
}
else
{
ct.ThrowIfCancellationRequested();
var createResp = await _http.PostAsJsonAsync($"{GraphBase}/me/onenote/notebooks",
new { displayName = NotebookName }, ct);
if (!createResp.IsSuccessStatusCode) return false;
var created = await createResp.Content.ReadFromJsonAsync<JsonElement>(cancellationToken: ct);
_notebookId = created.GetProperty("id").GetString();
}
ct.ThrowIfCancellationRequested();
// Find section by listing all sections in notebook
var secResp = await _http.GetAsync($"{GraphBase}/me/onenote/notebooks/{_notebookId}/sections?$select=id,displayName&$top=50", ct);
if (!secResp.IsSuccessStatusCode) return false;
var secJson = await secResp.Content.ReadFromJsonAsync<JsonElement>(cancellationToken: ct);
string? foundSecId = null;
foreach (var sec in secJson.GetProperty("value").EnumerateArray())
{
var name = sec.TryGetProperty("displayName", out var dn) ? dn.GetString() : null;
if (string.Equals(name, SectionName, StringComparison.OrdinalIgnoreCase))
{
foundSecId = sec.GetProperty("id").GetString();
break;
}
}
if (foundSecId != null)
{
_sectionId = foundSecId;
}
else
{
ct.ThrowIfCancellationRequested();
var createSec = await _http.PostAsJsonAsync($"{GraphBase}/me/onenote/notebooks/{_notebookId}/sections",
new { displayName = SectionName }, ct);
if (!createSec.IsSuccessStatusCode) return false;
var createdSec = await createSec.Content.ReadFromJsonAsync<JsonElement>(cancellationToken: ct);
_sectionId = createdSec.GetProperty("id").GetString();
}
return true;
}
catch (OperationCanceledException) { throw; }
catch { return false; }
}
// ── Pull notes from OneNote ─────────────────────────────────
public async Task<List<NoteEntry>?> PullNotesAsync(CancellationToken ct = default)
{
if (!IsConnected) return null;
if (!await EnsureNotebookAndSection(ct)) return null;
try
{
var notes = new List<NoteEntry>();
// 1. Pull from our NoteUI section only (fast — limited scope)
if (_sectionId != null)
{
var pages = await ListPagesInSection(_sectionId, ct);
foreach (var page in pages)
{
ct.ThrowIfCancellationRequested();
var pageId = page.GetProperty("id").GetString()!;
var note = await PullPageContent(page, pageId, ct);
if (note != null)
notes.Add(note);
}
}
ct.ThrowIfCancellationRequested();
// 2. Pull Sticky Notes from Outlook (they sync via Exchange, not OneNote)
var stickyNotes = await PullOutlookStickyNotesAsync(ct);
if (stickyNotes != null)
notes.AddRange(stickyNotes);
return notes;
}
catch (OperationCanceledException) { throw; }
catch { return null; }
}
private async Task<List<JsonElement>> ListPagesInSection(string sectionId, CancellationToken ct = default)
{
var pages = new List<JsonElement>();
try
{
var url = $"{GraphBase}/me/onenote/sections/{sectionId}/pages?$select=id,title,lastModifiedDateTime,createdDateTime&$top=100&$orderby=lastModifiedDateTime desc";
while (!string.IsNullOrEmpty(url))
{
ct.ThrowIfCancellationRequested();
var resp = await _http.GetAsync(url, ct);
if (!resp.IsSuccessStatusCode) break;
var json = await resp.Content.ReadFromJsonAsync<JsonElement>(cancellationToken: ct);
foreach (var p in json.GetProperty("value").EnumerateArray())
pages.Add(p);
url = json.TryGetProperty("@odata.nextLink", out var next) ? next.GetString() : null;
}
}
catch (OperationCanceledException) { throw; }
catch { }
return pages;
}
private async Task<NoteEntry?> PullPageContent(JsonElement pageMeta, string pageId, CancellationToken ct = default)
{
try
{
// Retry once on failure (Graph API rate limiting)
var resp = await _http.GetAsync($"{GraphBase}/me/onenote/pages/{pageId}/content", ct);
if (!resp.IsSuccessStatusCode)
{
await Task.Delay(500, ct);
resp = await _http.GetAsync($"{GraphBase}/me/onenote/pages/{pageId}/content", ct);
}
if (!resp.IsSuccessStatusCode) return null;
var html = await resp.Content.ReadAsStringAsync();
// Extract NoteUI metadata if present
var meta = ExtractMeta(html);
var title = pageMeta.TryGetProperty("title", out var t) ? t.GetString() ?? "" : "";
var createdAt = pageMeta.TryGetProperty("createdDateTime", out var ca)
? (DateTime.TryParse(ca.GetString(), out var cdt) ? cdt : DateTime.Now) : DateTime.Now;
var updatedAt = pageMeta.TryGetProperty("lastModifiedDateTime", out var ua)
? (DateTime.TryParse(ua.GetString(), out var udt) ? udt : DateTime.Now) : DateTime.Now;
// Extract body content (between <body> tags, strip metadata comment)
var bodyContent = ExtractBodyText(html);
var note = new NoteEntry
{
Id = meta?.Id ?? pageId,
Title = title,
Content = bodyContent,
CreatedAt = createdAt,
UpdatedAt = updatedAt,
NoteType = meta?.NoteType ?? "note",
Color = meta?.Color ?? "Yellow",
IsPinned = meta?.IsPinned ?? false,
IsFavorite = meta?.IsFavorite ?? false,
IsArchived = meta?.IsArchived ?? false,
Tags = meta?.Tags ?? [],
Folder = meta?.Folder,
};
if (meta?.NoteType == "tasklist" && meta.Tasks != null)
note.Tasks = meta.Tasks;
return note;
}
catch { return null; }
}
// ── Pull Sticky Notes from Outlook ────────────────────────
private async Task<List<NoteEntry>?> PullOutlookStickyNotesAsync(CancellationToken ct = default)
{
try
{
var notes = new List<NoteEntry>();
var url = $"{GraphBase}/me/mailFolders/notes/messages?$select=id,subject,body,createdDateTime,lastModifiedDateTime&$top=100";
while (!string.IsNullOrEmpty(url))
{
ct.ThrowIfCancellationRequested();
var resp = await _http.GetAsync(url, ct);
if (!resp.IsSuccessStatusCode) break;
var json = await resp.Content.ReadFromJsonAsync<JsonElement>(cancellationToken: ct);
foreach (var msg in json.GetProperty("value").EnumerateArray())
{
var id = msg.GetProperty("id").GetString()!;
var subject = msg.TryGetProperty("subject", out var s) ? s.GetString() ?? "" : "";
var content = "";
if (msg.TryGetProperty("body", out var body))
{
var bodyContent = body.TryGetProperty("content", out var bc) ? bc.GetString() ?? "" : "";
var bodyType = body.TryGetProperty("contentType", out var bt) ? bt.GetString() : "text";
content = bodyType == "html" ? StripHtmlToPlain(bodyContent) : bodyContent;
}
if (string.IsNullOrWhiteSpace(content) && string.IsNullOrWhiteSpace(subject))
continue;
var createdAt = msg.TryGetProperty("createdDateTime", out var ca)
? (DateTime.TryParse(ca.GetString(), out var cdt) ? cdt : DateTime.Now) : DateTime.Now;
var updatedAt = msg.TryGetProperty("lastModifiedDateTime", out var ua)
? (DateTime.TryParse(ua.GetString(), out var udt) ? udt : DateTime.Now) : DateTime.Now;
notes.Add(new NoteEntry
{
Id = $"outlook-sticky-{id}",
Title = "",
Content = content.Trim(),
CreatedAt = createdAt,
UpdatedAt = updatedAt,
NoteType = "note",
Color = "Yellow",
});
}
url = json.TryGetProperty("@odata.nextLink", out var next) ? next.GetString() : null;
}
return notes;
}
catch (OperationCanceledException) { throw; }
catch
{
return null;
}
}
private static string StripHtmlToPlain(string html)
{
if (string.IsNullOrEmpty(html)) return "";
var text = Regex.Replace(html, @"<br\s*/?>", "\n", RegexOptions.IgnoreCase);
text = Regex.Replace(text, @"</p>\s*<p[^>]*>", "\n", RegexOptions.IgnoreCase);
text = Regex.Replace(text, @"</(div|p|li|tr|h[1-6])>", "\n", RegexOptions.IgnoreCase);
text = Regex.Replace(text, @"<[^>]+>", "", RegexOptions.IgnoreCase);
text = System.Net.WebUtility.HtmlDecode(text);
text = Regex.Replace(text, @"\n{3,}", "\n\n");
return text.Trim();
}
// ── Push notes to OneNote ───────────────────────────────────
public async Task<bool> PushNotesAsync(IReadOnlyList<NoteEntry> notes)
{
if (!IsConnected) return false;
if (!await EnsureNotebookAndSection()) return false;
try
{
// Get existing pages to map NoteUI IDs → OneNote page IDs
var existingPages = await GetExistingPageMap();
foreach (var note in notes)
{
var html = BuildPageHtml(note);
if (existingPages.TryGetValue(note.Id, out var pageId))
{
// Update existing page — PATCH replaces body content
await UpdatePage(pageId, note, html);
}
else
{
// Create new page
await CreatePage(html);
}
}
return true;
}
catch { return false; }
}
private async Task<Dictionary<string, string>> GetExistingPageMap()
{
var map = new Dictionary<string, string>(StringComparer.Ordinal);
var url = $"{GraphBase}/me/onenote/sections/{_sectionId}/pages?$select=id,title&$top=100";
while (!string.IsNullOrEmpty(url))
{
var resp = await _http.GetAsync(url);
if (!resp.IsSuccessStatusCode) break;
var json = await resp.Content.ReadFromJsonAsync<JsonElement>();
foreach (var p in json.GetProperty("value").EnumerateArray())
{
var pageId = p.GetProperty("id").GetString()!;
// Need to fetch content to read meta — but that's too slow for mapping
// Instead, fetch content for each to find the NoteUI ID
var contentResp = await _http.GetAsync($"{GraphBase}/me/onenote/pages/{pageId}/content");
if (contentResp.IsSuccessStatusCode)
{
var html = await contentResp.Content.ReadAsStringAsync();
var meta = ExtractMeta(html);
if (meta?.Id != null)
map[meta.Id] = pageId;
}
}
url = json.TryGetProperty("@odata.nextLink", out var next) ? next.GetString() : null;
}
return map;
}
private async Task<bool> CreatePage(string html)
{
var content = new StringContent(html, Encoding.UTF8, "text/html");
var resp = await _http.PostAsync($"{GraphBase}/me/onenote/sections/{_sectionId}/pages", content);
return resp.IsSuccessStatusCode;
}
private async Task<bool> UpdatePage(string pageId, NoteEntry note, string fullHtml)
{
// OneNote PATCH API uses JSON patch commands targeting element IDs
// Simpler approach: delete and recreate
var delResp = await _http.DeleteAsync($"{GraphBase}/me/onenote/pages/{pageId}");
if (!delResp.IsSuccessStatusCode && delResp.StatusCode != HttpStatusCode.NotFound)
return false;
// Small delay to let OneNote process the deletion
await Task.Delay(200);
return await CreatePage(fullHtml);
}
// ── HTML builders ───────────────────────────────────────────
private static string BuildPageHtml(NoteEntry note)
{
var sb = new StringBuilder();
sb.Append("<!DOCTYPE html><html><head>");
sb.Append($"<title>{EscapeHtml(note.Title)}</title>");
sb.Append("<meta name=\"created\" content=\"");
sb.Append(note.CreatedAt.ToUniversalTime().ToString("O"));
sb.Append("\" />");
sb.Append("</head><body>");
// Embed NoteUI metadata as hidden comment
sb.Append(BuildMetaComment(note));
// Content
if (note.NoteType == "tasklist")
{
foreach (var task in note.Tasks)
{
var check = task.IsDone ? "☑" : "☐";
sb.Append($"<p data-tag=\"to-do\">{check} {EscapeHtml(task.Text)}</p>");
}
}
else
{
var content = note.Content;
if (content.StartsWith("{\\rtf", StringComparison.Ordinal))
content = RtfToSimpleHtml(content);
else
content = PlainTextToHtml(content);
sb.Append(content);
}
sb.Append("</body></html>");
return sb.ToString();
}
private static string BuildMetaComment(NoteEntry note)
{
var meta = new OneNoteMetadata
{
Id = note.Id,
NoteType = note.NoteType,
Color = note.Color,
IsPinned = note.IsPinned,
IsFavorite = note.IsFavorite,
IsArchived = note.IsArchived,
Tags = note.Tags.Count > 0 ? note.Tags : null,
Folder = note.Folder,
Tasks = note.NoteType == "tasklist" ? note.Tasks : null,
};
var json = JsonSerializer.Serialize(meta, new JsonSerializerOptions { DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull });
return $"{MetaPrefix}{json}{MetaSuffix}";
}
private static OneNoteMetadata? ExtractMeta(string html)
{
var start = html.IndexOf(MetaPrefix, StringComparison.Ordinal);
if (start < 0) return null;
start += MetaPrefix.Length;
var end = html.IndexOf(MetaSuffix, start, StringComparison.Ordinal);
if (end < 0) return null;
var json = html[start..end];
try
{
return JsonSerializer.Deserialize<OneNoteMetadata>(json, JsonOptions);
}
catch { return null; }
}
// ── RTF → HTML (basic) ──────────────────────────────────────
private static string RtfToSimpleHtml(string rtf)
{
// Simple RTF to HTML: strip RTF control words, keep text
var sb = new StringBuilder();
sb.Append("<div>");
bool inGroup = false;
int depth = 0;
int i = 0;
var textBuf = new StringBuilder();
while (i < rtf.Length)
{
char c = rtf[i];
if (c == '{') { depth++; i++; continue; }
if (c == '}') { depth--; i++; continue; }
if (c == '\\')
{
i++;
if (i >= rtf.Length) break;
if (rtf[i] == '\'')
{
// Hex-encoded character
if (i + 2 < rtf.Length && byte.TryParse(rtf.AsSpan(i + 1, 2),
System.Globalization.NumberStyles.HexNumber, null, out var b))
{
textBuf.Append((char)b);
i += 3;
}
else i++;
}
else if (rtf[i] == '\n' || rtf[i] == '\r') { i++; }
else
{
// Read control word
var wordStart = i;
while (i < rtf.Length && char.IsLetter(rtf[i])) i++;
var word = rtf[wordStart..i];
// Skip optional numeric parameter
while (i < rtf.Length && (char.IsDigit(rtf[i]) || rtf[i] == '-')) i++;
if (i < rtf.Length && rtf[i] == ' ') i++;
if (word is "par" or "line")
{
if (textBuf.Length > 0)
{
sb.Append($"<p>{EscapeHtml(textBuf.ToString())}</p>");
textBuf.Clear();
}
}
else if (word is "tab")
{
textBuf.Append('\t');
}
// Skip other control words (fonttbl, colortbl, etc.)
}
}
else if (c == '\r' || c == '\n')
{
i++;
}
else
{
textBuf.Append(c);
i++;
}
}
if (textBuf.Length > 0)
sb.Append($"<p>{EscapeHtml(textBuf.ToString())}</p>");
sb.Append("</div>");
return sb.ToString();
}
private static string PlainTextToHtml(string text)
{
if (string.IsNullOrWhiteSpace(text)) return "<p></p>";
var lines = text.Split('\n');
var sb = new StringBuilder();
foreach (var line in lines)
sb.Append($"<p>{EscapeHtml(line.TrimEnd('\r'))}</p>");
return sb.ToString();
}
private static string ExtractBodyText(string html)
{
// Remove the metadata comment
var cleaned = html;
var metaStart = cleaned.IndexOf(MetaPrefix, StringComparison.Ordinal);
if (metaStart >= 0)
{
var metaEnd = cleaned.IndexOf(MetaSuffix, metaStart, StringComparison.Ordinal);
if (metaEnd >= 0)
cleaned = cleaned[..metaStart] + cleaned[(metaEnd + MetaSuffix.Length)..];
}
// Extract text between body tags
var bodyStart = cleaned.IndexOf("<body", StringComparison.OrdinalIgnoreCase);
if (bodyStart >= 0)
{
var bodyTagEnd = cleaned.IndexOf('>', bodyStart);
if (bodyTagEnd >= 0) cleaned = cleaned[(bodyTagEnd + 1)..];
}
var bodyEnd = cleaned.IndexOf("</body>", StringComparison.OrdinalIgnoreCase);
if (bodyEnd >= 0) cleaned = cleaned[..bodyEnd];
// Convert HTML to plain text
cleaned = Regex.Replace(cleaned, @"<br\s*/?>", "\n", RegexOptions.IgnoreCase);
cleaned = Regex.Replace(cleaned, @"</p>\s*<p[^>]*>", "\n", RegexOptions.IgnoreCase);
cleaned = Regex.Replace(cleaned, @"<p[^>]*>", "", RegexOptions.IgnoreCase);
cleaned = Regex.Replace(cleaned, @"</p>", "\n", RegexOptions.IgnoreCase);
cleaned = Regex.Replace(cleaned, @"<[^>]+>", "", RegexOptions.IgnoreCase);
cleaned = WebUtility.HtmlDecode(cleaned);
return cleaned.Trim();
}
private static string EscapeHtml(string text)
{
return WebUtility.HtmlEncode(text);
}
// ── Merge logic ─────────────────────────────────────────────
public static List<NoteEntry> MergeWithLocal(
IReadOnlyList<NoteEntry> local, IReadOnlyList<NoteEntry> remote)
{
var merged = new Dictionary<string, NoteEntry>(StringComparer.Ordinal);
foreach (var n in local)
merged[n.Id] = n;
foreach (var n in remote)
{
if (!merged.TryGetValue(n.Id, out var existing)
|| n.UpdatedAt.ToUniversalTime() >= existing.UpdatedAt.ToUniversalTime())
merged[n.Id] = n;
}
return merged.Values.ToList();
}
// ── Helpers ──────────────────────────────────────────────────
private static string GenerateCodeVerifier()
{
var bytes = new byte[32];
RandomNumberGenerator.Fill(bytes);
return Convert.ToBase64String(bytes)
.TrimEnd('=').Replace('+', '-').Replace('/', '_');
}
private static string GenerateCodeChallenge(string verifier)
{
var hash = SHA256.HashData(Encoding.ASCII.GetBytes(verifier));
return Convert.ToBase64String(hash)
.TrimEnd('=').Replace('+', '-').Replace('/', '_');
}
private static int FindFreePort()
{
var listener = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return port;
}
public void Dispose()
{
_refreshTimer?.Dispose();
_http.Dispose();
}
// ── Metadata model ──────────────────────────────────────────
private class OneNoteMetadata
{
public string? Id { get; set; }
public string? NoteType { get; set; }
public string? Color { get; set; }
public bool IsPinned { get; set; }
public bool IsFavorite { get; set; }
public bool IsArchived { get; set; }
public List<string>? Tags { get; set; }
public string? Folder { get; set; }
public List<TaskItem>? Tasks { get; set; }
}
}