Repository navigation
Expand file tree
/
Copy pathLocalization.vb
More file actions
1547 lines (1464 loc) · 112 KB
/
Copy pathLocalization.vb
File metadata and controls
1547 lines (1464 loc) · 112 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
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Imports System.IO
Imports System.Net.Http
Imports System.Text
Imports System.Text.Json
Imports System.Threading
Imports System.Threading.Tasks
''' <summary>
''' Modulo helper per la gestione del supporto multilingua e l'interrogazione dell'API di traduzione Google Translate.
''' </summary>
Public Module AppLanguages
Private ReadOnly SharedHttpClient As New HttpClient()
Private ReadOnly RtlCodes As New HashSet(Of String)(StringComparer.OrdinalIgnoreCase) From {
"ar", "fa", "he", "iw", "ur", "yi", "ps", "sd", "ug", "syc"
}
''' <summary>
''' Restituisce true se il codice lingua specificato utilizza l'orientamento di scrittura da destra a sinistra (RTL).
''' </summary>
Public Function IsRtl(code As String) As Boolean
If String.IsNullOrEmpty(code) Then Return False
Dim baseCode = code.Split("-"c)(0)
Return RtlCodes.Contains(baseCode)
End Function
''' <summary>
''' Recupera l'elenco delle lingue supportate interrogando l'API REST di Google Translate.
''' </summary>
Public Async Function FetchSupportedLanguages() As Task(Of List(Of LanguageInfo))
Dim langs As New List(Of LanguageInfo)()
Try
Dim url = "https://translate.googleapis.com/translate_a/l?client=gtx&hl=en"
Dim response = Await SharedHttpClient.GetStringAsync(url)
Using doc As JsonDocument = JsonDocument.Parse(response)
Dim tlElement As JsonElement = Nothing
If doc.RootElement.TryGetProperty("tl", tlElement) Then
For Each prop In tlElement.EnumerateObject()
langs.Add(New LanguageInfo With {
.Code = prop.Name,
.Name = prop.Value.ToString()
})
Next
langs.Sort(Function(a, b) a.Name.CompareTo(b.Name))
End If
End Using
Catch ex As Exception
Debug.WriteLine($"Failed to fetch supported languages: {ex.Message}")
End Try
Return langs
End Function
End Module
''' <summary>
''' Servizio singleton per la gestione della cache delle traduzioni (UI e messaggi chat) persistente su file disco.
''' Ottimizzato per mantenere in RAM ESCLUSIVAMENTE i dizionari della lingua attualmente attiva/impostata.
''' </summary>
Public Class TranslationCacheService
Private Shared ReadOnly _instance As New TranslationCacheService()
Public Shared ReadOnly Property Instance As TranslationCacheService
Get
Return _instance
End Get
End Property
Private ReadOnly _httpClient As New HttpClient()
Private ReadOnly _cacheLock As New Object()
Private _activeLanguage As String = "en"
Private _activeUiTranslations As New Dictionary(Of String, String)(StringComparer.OrdinalIgnoreCase)
Private _activeMessageTranslations As New Dictionary(Of String, String)(StringComparer.Ordinal)
Private _dirty As Boolean = False
Private _flushCts As CancellationTokenSource = Nothing
' Supporto multi-provider e privacy opt-in (TODO #69)
Private _activeProvider As ITranslationProvider = GoogleTranslationProvider.Instance
Private _privacyConsentAccepted As Boolean = False
Private Sub New()
End Sub
''' <summary>Percorso del file JSON per la persistenza delle traduzioni su disco.</summary>
Public Shared ReadOnly Property CacheFilePath As String
Get
Dim dataDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "data")
Dim dataPath = Path.Combine(dataDir, "translations_cache.json")
If File.Exists(dataPath) Then Return dataPath
Dim rootPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "translations_cache.json")
If File.Exists(rootPath) Then
Try
If Not Directory.Exists(dataDir) Then Directory.CreateDirectory(dataDir)
File.Move(rootPath, dataPath)
Return dataPath
Catch
Return rootPath
End Try
End If
If Not Directory.Exists(dataDir) Then
Try
Directory.CreateDirectory(dataDir)
Catch
End Try
End If
Return dataPath
End Get
End Property
''' <summary>Indica se l'utente ha esplicitamente acconsentito all'invio dei messaggi non in cache al fornitore di traduzione (TODO #69).</summary>
Public Property PrivacyConsentAccepted As Boolean
Get
SyncLock _cacheLock
Return _privacyConsentAccepted
End SyncLock
End Get
Set(value As Boolean)
SyncLock _cacheLock
_privacyConsentAccepted = value
End SyncLock
End Set
End Property
''' <summary>Provider di traduzione attualmente configurato ed attivo (Google, LibreTranslate, Ollama, OpenAI-compatible).</summary>
Public Property ActiveProvider As ITranslationProvider
Get
SyncLock _cacheLock
Return If(_activeProvider, GoogleTranslationProvider.Instance)
End SyncLock
End Get
Set(value As ITranslationProvider)
SyncLock _cacheLock
_activeProvider = If(value, GoogleTranslationProvider.Instance)
End SyncLock
End Set
End Property
''' <summary>
''' Configura il provider e lo stato di consenso privacy del servizio di traduzione (TODO #69).
''' </summary>
Public Sub Configure(config As TranslationConfig)
If config Is Nothing Then Return
SyncLock _cacheLock
_privacyConsentAccepted = config.PrivacyConsentAccepted
_activeProvider = TranslationProviderRegistry.CreateProvider(config, _httpClient)
End SyncLock
End Sub
''' <summary>
''' Imposta la lingua attiva, scarica su disco eventuali modifiche della lingua precedente,
''' rilascia dalla memoria RAM i dizionari non utilizzati e carica solo quelli della nuova lingua.
''' </summary>
Public Async Function SetActiveLanguageAsync(langCode As String) As Task
If String.IsNullOrWhiteSpace(langCode) Then langCode = "en"
' Flush immediato se c'erano modifiche pendenti sulla vecchia lingua
If _dirty Then
Await FlushCacheImmediateAsync()
End If
SyncLock _cacheLock
_activeLanguage = langCode.ToLowerInvariant()
_activeUiTranslations.Clear()
_activeMessageTranslations.Clear()
End SyncLock
' Carica i dati per la lingua attiva dal file persistente
Await LoadActiveLanguageFromDiskAsync(_activeLanguage)
' Integra i valori UI predefiniti
SyncLock _cacheLock
Dim sourceDict As Dictionary(Of String, String) = Nothing
Select Case _activeLanguage
Case "it"
sourceDict = AppLocalizations.ItStrings
Case "fr"
sourceDict = AppLocalizations.FrStrings
Case "es"
sourceDict = AppLocalizations.EsStrings
Case "de"
sourceDict = AppLocalizations.DeStrings
Case Else
sourceDict = AppLocalizations.EnStrings
End Select
If sourceDict IsNot Nothing Then
For Each kvp In sourceDict
If Not _activeUiTranslations.ContainsKey(kvp.Key) Then
_activeUiTranslations(kvp.Key) = kvp.Value
End If
Next
End If
End SyncLock
End Function
''' <summary>
''' Restituisce un'istanza di AppLocalizations configurata con le traduzioni correnti in RAM.
''' </summary>
Public Function GetActiveLocalizations() As AppLocalizations
SyncLock _cacheLock
Return New AppLocalizations(_activeUiTranslations)
End SyncLock
End Function
Private Async Function LoadActiveLanguageFromDiskAsync(langCode As String) As Task
Dim filePath = CacheFilePath
If Not File.Exists(filePath) Then Return
Try
Dim jsonContent = Await File.ReadAllTextAsync(filePath)
If String.IsNullOrWhiteSpace(jsonContent) Then Return
Using doc As JsonDocument = JsonDocument.Parse(jsonContent)
Dim root = doc.RootElement
SyncLock _cacheLock
' 1. Lettura traduzioni UI ("ui" -> langCode)
Dim uiElement As JsonElement = Nothing
If root.TryGetProperty("ui", uiElement) AndAlso uiElement.ValueKind = JsonValueKind.Object Then
Dim langUiElement As JsonElement = Nothing
If uiElement.TryGetProperty(langCode, langUiElement) AndAlso langUiElement.ValueKind = JsonValueKind.Object Then
For Each prop In langUiElement.EnumerateObject()
_activeUiTranslations(prop.Name) = prop.Value.GetString()
Next
End If
End If
' 2. Retrocompatibilità: "cached_translations" -> langCode
Dim cachedElement As JsonElement = Nothing
If root.TryGetProperty("cached_translations", cachedElement) AndAlso cachedElement.ValueKind = JsonValueKind.Object Then
Dim langCachedElement As JsonElement = Nothing
If cachedElement.TryGetProperty(langCode, langCachedElement) AndAlso langCachedElement.ValueKind = JsonValueKind.Object Then
For Each prop In langCachedElement.EnumerateObject()
If Not _activeUiTranslations.ContainsKey(prop.Name) Then
_activeUiTranslations(prop.Name) = prop.Value.GetString()
End If
Next
End If
End If
' 3. Lettura messaggi chat/DOM tradotti ("messages" -> langCode)
Dim msgElement As JsonElement = Nothing
If root.TryGetProperty("messages", msgElement) AndAlso msgElement.ValueKind = JsonValueKind.Object Then
Dim langMsgElement As JsonElement = Nothing
If msgElement.TryGetProperty(langCode, langMsgElement) AndAlso langMsgElement.ValueKind = JsonValueKind.Object Then
For Each prop In langMsgElement.EnumerateObject()
_activeMessageTranslations(prop.Name) = prop.Value.GetString()
Next
End If
End If
End SyncLock
End Using
Catch ex As Exception
Debug.WriteLine($"[TranslationCacheService] Error reading cache from disk: {ex.Message}")
End Try
End Function
''' <summary>
''' Recupera una traduzione messaggio memorizzata in cache se presente.
''' </summary>
Public Function TryGetCachedMessage(text As String, targetLang As String, ByRef translatedText As String) As Boolean
If String.IsNullOrEmpty(text) Then
translatedText = text
Return True
End If
SyncLock _cacheLock
If String.Equals(targetLang, _activeLanguage, StringComparison.OrdinalIgnoreCase) Then
Return _activeMessageTranslations.TryGetValue(text, translatedText)
End If
End SyncLock
translatedText = Nothing
Return False
End Function
''' <summary>
''' Salva una traduzione messaggio nella cache e pianifica la persistenza su disco con debounce.
''' </summary>
Public Sub CacheMessage(text As String, translatedText As String, targetLang As String)
If String.IsNullOrEmpty(text) OrElse String.IsNullOrEmpty(translatedText) Then Return
SyncLock _cacheLock
If String.Equals(targetLang, _activeLanguage, StringComparison.OrdinalIgnoreCase) Then
_activeMessageTranslations(text) = translatedText
_dirty = True
End If
End SyncLock
If _dirty Then
ScheduleFlushDebounced()
End If
End Sub
''' <summary>
''' Salva più traduzioni messaggi in batch nella cache in un'unica operazione.
''' </summary>
Public Sub CacheMessagesBatch(items As IEnumerable(Of KeyValuePair(Of String, String)), targetLang As String)
SyncLock _cacheLock
If String.Equals(targetLang, _activeLanguage, StringComparison.OrdinalIgnoreCase) Then
For Each item In items
If Not String.IsNullOrEmpty(item.Key) AndAlso Not String.IsNullOrEmpty(item.Value) Then
_activeMessageTranslations(item.Key) = item.Value
_dirty = True
End If
Next
End If
End SyncLock
If _dirty Then
ScheduleFlushDebounced()
End If
End Sub
Private Sub ScheduleFlushDebounced()
If _flushCts IsNot Nothing Then
Try
_flushCts.Cancel()
_flushCts.Dispose()
Catch
End Try
End If
_flushCts = New CancellationTokenSource()
Dim token = _flushCts.Token
Dim ignore = Task.Run(Async Function()
Try
Await Task.Delay(500, token)
If token.IsCancellationRequested Then Return
Await FlushCacheImmediateAsync()
Catch ex As OperationCanceledException
' Operazione annullata per nuovo arrivo dati
Catch ex As Exception
Debug.WriteLine($"[TranslationCacheService] Debounced flush error: {ex.Message}")
End Try
End Function)
End Sub
''' <summary>
''' Scrive immediatamente su file disco lo stato della cache unificandolo ai dati già esistenti.
''' </summary>
Public Async Function FlushCacheImmediateAsync() As Task
Dim currentLang As String
Dim uiCopy As Dictionary(Of String, String)
Dim msgCopy As Dictionary(Of String, String)
SyncLock _cacheLock
If Not _dirty Then Return
_dirty = False
currentLang = _activeLanguage
uiCopy = New Dictionary(Of String, String)(_activeUiTranslations)
msgCopy = New Dictionary(Of String, String)(_activeMessageTranslations)
End SyncLock
Dim filePath = CacheFilePath
Try
' Carica l'intero file esistente per non sovrascrivere altre lingue memorizzate su disco
Dim fullData As New Dictionary(Of String, Object)()
Dim allUi As New Dictionary(Of String, Dictionary(Of String, String))(StringComparer.OrdinalIgnoreCase)
Dim allMessages As New Dictionary(Of String, Dictionary(Of String, String))(StringComparer.OrdinalIgnoreCase)
If File.Exists(filePath) Then
Try
Dim existingJson = Await File.ReadAllTextAsync(filePath)
If Not String.IsNullOrWhiteSpace(existingJson) Then
Using doc As JsonDocument = JsonDocument.Parse(existingJson)
Dim root = doc.RootElement
Dim uiEl As JsonElement = Nothing
If root.TryGetProperty("ui", uiEl) AndAlso uiEl.ValueKind = JsonValueKind.Object Then
For Each langProp In uiEl.EnumerateObject()
Dim dict As New Dictionary(Of String, String)(StringComparer.OrdinalIgnoreCase)
For Each item In langProp.Value.EnumerateObject()
dict(item.Name) = item.Value.GetString()
Next
allUi(langProp.Name) = dict
Next
End If
Dim msgEl As JsonElement = Nothing
If root.TryGetProperty("messages", msgEl) AndAlso msgEl.ValueKind = JsonValueKind.Object Then
For Each langProp In msgEl.EnumerateObject()
Dim dict As New Dictionary(Of String, String)(StringComparer.Ordinal)
For Each item In langProp.Value.EnumerateObject()
dict(item.Name) = item.Value.GetString()
Next
allMessages(langProp.Name) = dict
Next
End If
End Using
End If
Catch ex As Exception
Debug.WriteLine($"[TranslationCacheService] Read before write warning: {ex.Message}")
End Try
End If
' Aggiorna la sezione della lingua attiva
allUi(currentLang) = uiCopy
allMessages(currentLang) = msgCopy
fullData("ui") = allUi
fullData("messages") = allMessages
' Mantiene retrocompatibilità con cached_translations
fullData("cached_translations") = allUi
Dim dirName = Path.GetDirectoryName(filePath)
If Not String.IsNullOrEmpty(dirName) AndAlso Not Directory.Exists(dirName) Then
Directory.CreateDirectory(dirName)
End If
Dim options As New JsonSerializerOptions With {
.WriteIndented = True
}
Dim serialized = JsonSerializer.Serialize(fullData, options)
Await File.WriteAllTextAsync(filePath, serialized)
Catch ex As Exception
Debug.WriteLine($"[TranslationCacheService] Failed to save cache file: {ex.Message}")
End Try
End Function
''' <summary>
''' Traduce un singolo testo restituendo il risultato dettagliato (successo, testo tradotto, messaggio d'errore).
''' Rispetta rigorosamente il vincolo di Privacy Opt-In (TODO #69): se il consenso non è concesso, nessun dato lascia il computer.
''' </summary>
Public Async Function TranslateSingleDetailedAsync(text As String, targetLang As String, Optional cancellationToken As CancellationToken = Nothing) As Task(Of TranslationResult)
If String.IsNullOrEmpty(text) Then Return TranslationResult.Succeeded(text)
Dim cached As String = Nothing
If TryGetCachedMessage(text, targetLang, cached) AndAlso Not String.IsNullOrEmpty(cached) Then
Return TranslationResult.Succeeded(cached)
End If
' Verifica Privacy Opt-in: se non autorizzato, non invia richieste di rete
If Not PrivacyConsentAccepted Then
Return TranslationResult.Failed("PRIVACY_CONSENT_REQUIRED", text)
End If
Dim provider = ActiveProvider
Try
Dim res = Await provider.TranslateSingleAsync(text, targetLang, cancellationToken)
If res.Success AndAlso Not String.IsNullOrEmpty(res.TranslatedText) AndAlso res.TranslatedText <> text Then
CacheMessage(text, res.TranslatedText, targetLang)
End If
Return res
Catch ex As Exception
Debug.WriteLine($"[TranslationCacheService] Translation error via {provider.DisplayName}: {ex.Message}")
Return TranslationResult.Failed($"Provider unreachable: {ex.Message}", text)
End Try
End Function
''' <summary>
''' Traduce un singolo testo interrogando preventivamente la cache su disco/RAM prima di effettuare chiamate al provider configurato.
''' </summary>
Public Async Function TranslateSingleAsync(text As String, targetLang As String) As Task(Of String)
Dim res = Await TranslateSingleDetailedAsync(text, targetLang)
Return If(res.Success AndAlso Not String.IsNullOrEmpty(res.TranslatedText), res.TranslatedText, text)
End Function
''' <summary>
''' Traduce un elenco di testi inviando al fornitore configurato solo le frasi non ancora in cache.
''' Rispetta il vincolo di Privacy Opt-In: in assenza di autorizzazione, nessun dato viene trasmesso (TODO #69).
''' </summary>
Public Async Function TranslateBatchDetailedAsync(texts As List(Of String), targetLang As String, Optional cancellationToken As CancellationToken = Nothing) As Task(Of TranslationBatchResult)
If texts Is Nothing OrElse texts.Count = 0 Then Return TranslationBatchResult.Succeeded(New List(Of String)())
Dim results As New List(Of String)(New String(texts.Count - 1) {})
Dim missingIndices As New List(Of Integer)()
Dim missingTexts As New List(Of String)()
For i As Integer = 0 To texts.Count - 1
Dim t = texts(i)
Dim cached As String = Nothing
If TryGetCachedMessage(t, targetLang, cached) AndAlso Not String.IsNullOrEmpty(cached) Then
results(i) = cached
Else
missingIndices.Add(i)
missingTexts.Add(t)
End If
Next
' Se tutti i testi erano già memorizzati in cache, ritorna immediatamente senza accessi di rete!
If missingTexts.Count = 0 Then
Return TranslationBatchResult.Succeeded(results)
End If
' Controllo Privacy Opt-in (TODO #69)
If Not PrivacyConsentAccepted Then
For j As Integer = 0 To missingIndices.Count - 1
results(missingIndices(j)) = missingTexts(j)
Next
Return TranslationBatchResult.Failed("PRIVACY_CONSENT_REQUIRED", results)
End If
Dim provider = ActiveProvider
Try
Dim batchRes = Await provider.TranslateBatchAsync(missingTexts, targetLang, cancellationToken)
If batchRes.Success Then
Dim newCacheEntries As New List(Of KeyValuePair(Of String, String))()
For j As Integer = 0 To missingIndices.Count - 1
Dim origIndex = missingIndices(j)
Dim translatedPart = If(j < batchRes.Translations.Count AndAlso Not String.IsNullOrEmpty(batchRes.Translations(j)), batchRes.Translations(j), missingTexts(j))
results(origIndex) = translatedPart
If translatedPart <> missingTexts(j) Then
newCacheEntries.Add(New KeyValuePair(Of String, String)(missingTexts(j), translatedPart))
End If
Next
If newCacheEntries.Count > 0 Then
CacheMessagesBatch(newCacheEntries, targetLang)
End If
Return TranslationBatchResult.Succeeded(results)
Else
For j As Integer = 0 To missingIndices.Count - 1
results(missingIndices(j)) = missingTexts(j)
Next
Return TranslationBatchResult.Failed(batchRes.ErrorMessage, results)
End If
Catch ex As Exception
Debug.WriteLine($"[TranslationCacheService] Batch translation provider error ({provider.DisplayName}): {ex.Message}")
For j As Integer = 0 To missingIndices.Count - 1
results(missingIndices(j)) = missingTexts(j)
Next
Return TranslationBatchResult.Failed($"Provider error: {ex.Message}", results)
End Try
End Function
''' <summary>
''' Traduce un elenco di testi estraendo ed inviando al provider solo le frasi non ancora in cache.
''' </summary>
Public Async Function TranslateBatchAsync(texts As List(Of String), targetLang As String) As Task(Of List(Of String))
Dim res = Await TranslateBatchDetailedAsync(texts, targetLang)
Return res.Translations
End Function
Private Async Function TranslateTextHttpAsync(text As String, targetLang As String) As Task(Of String)
Dim res = Await GoogleTranslationProvider.Instance.TranslateSingleAsync(text, targetLang, CancellationToken.None)
Return If(res.Success, res.TranslatedText, text)
End Function
End Class
''' <summary>
''' Gestisce i dizionari di localizzazione dell'interfaccia utente (Inglese e Italiano) e il servizio di traduzione automatica.
''' </summary>
Public Class AppLocalizations
Private ReadOnly _translations As Dictionary(Of String, String)
Public Sub New(translations As Dictionary(Of String, String))
_translations = If(translations, New Dictionary(Of String, String)())
End Sub
''' <summary>Dizionario di localizzazione di fallback per l'interfaccia in lingua Inglese.</summary>
Public Shared ReadOnly EnStrings As New Dictionary(Of String, String)(StringComparer.OrdinalIgnoreCase) From {
{"settings", "Settings"},
{"theme", "Theme"},
{"system", "System"},
{"light", "Light"},
{"dark", "Dark"},
{"match_cohesive", "Match this setting in your chat apps for a cohesive look."},
{"manage_accounts", "Manage Accounts"},
{"add_account", "Add account"},
{"always_show_tab_bar", "Always show tab bar"},
{"updates", "Updates"},
{"check_updates_launch", "Check for updates on launch"},
{"check_now", "Check Now"},
{"devtools", "DevTools"},
{"debug_active_tab", "Debug active tab"},
{"delete_account_title", "Delete Account"},
{"delete_account_confirm", "Delete ""{name}""? This will remove all data for this account."},
{"delete_account_last", "You cannot delete the last active account."},
{"cancel", "Cancel"},
{"delete", "Delete"},
{"rename", "Rename"},
{"language", "Language"},
{"translate_to_lang", "Translate to {lang}"},
{"translate_all_messages", "Translate all messages"},
{"toggle_window", "Toggle Window"},
{"exit", "Exit"},
{"translate_message_button", "Translate message button "},
{"keep_app_in_english", "Keep app UI in English"},
{"full_page_translation", "Translate entire page"},
{"show_translate_all_messages_button", "Title bar translate all messages button"},
{"reload_active_tab", "Reload active tab"},
{"use_beta_channel", "Use beta update channel"},
{"notifications", "Notifications"},
{"show_message_popup", "Show message popup"},
{"accounts_count_info", "Configured accounts: {count} of {max}"},
{"max_accounts_reached", "Maximum limit of {max} accounts reached."},
{"max_accounts_downgrade_notice", "Downgrade notice: you have {count} active accounts, exceeding the maximum limit of {max}. Existing accounts are preserved and fully functional, but adding new accounts is disabled until you are below the limit."},
{"accounts_downgrade_blocked", "Cannot add account: you have {count} configured accounts, exceeding the current limit of {max}. Delete one or more accounts or increase the limit to add new accounts."},
{"max_accounts", "Max accounts:"},
{"add_whatsapp_account", "Add WhatsApp account"},
{"add_telegram_account", "Add Telegram account"},
{"add_openclaw_account", "Add OpenClaw account"},
{"add_hermes_account", "Add Hermes Agent account"},
{"openclaw_server_url", "Gateway / Tailscale URL:"},
{"openclaw_auth_token", "Gateway Auth Token:"},
{"test_connection", "Test Connection"},
{"connection_testing", "Testing..."},
{"connection_success", "✓ Online"},
{"connection_failed", "✗ Unreachable"},
{"select_platform", "Select platform"},
{"about", "About"},
{"about_title", "About HidaChat"},
{"app_description", "Portable, lightweight, multi-account desktop client for Windows (WhatsApp, Telegram, OpenClaw, Hermes)."},
{"author", "Author"},
{"release_date", "Release Date"},
{"license", "License"},
{"runtime_environment", "Environment & Framework"},
{"portable_directory", "Portable Data Path"},
{"github_repository", "GitHub Repository"},
{"report_issue", "Report Issue"},
{"view_releases", "View Releases"},
{"bulk_sender", "Excel / CSV Bulk Sender"},
{"custom_css", "Custom CSS"},
{"enable_custom_css", "Enable custom CSS rules"},
{"custom_css_placeholder", "/* Write or paste your custom CSS for WhatsApp and Telegram Web here */"},
{"apply_css", "Apply CSS"},
{"css_applied", "CSS applied successfully!"},
{"css_preset_oled", "OLED Pure Dark"},
{"css_preset_compact", "Compact Layout"},
{"css_preset_font", "Modern Font"},
{"css_preset_reset", "Clear"},
{"contact_online", "Online"},
{"contact_typing", "typing..."},
{"spellchecker", "Spellchecker"},
{"enable_spellchecker", "Enable native spellchecker in chat inputs"},
{"spellchecker_language", "Dictionary language"},
{"spellchecker_lang_auto", "Automatic (follow app language)"},
{"spellchecker_restart_hint", "Changes will apply when reloading tabs or restarting HidaChat."},
{"dnd_mode", "Do Not Disturb (Focus Mode)"},
{"dnd_enable", "Silence all notifications and sounds"},
{"dnd_duration", "Duration"},
{"dnd_30m", "For 30 minutes"},
{"dnd_1h", "For 1 hour"},
{"dnd_2h", "For 2 hours"},
{"dnd_8h", "For 8 hours"},
{"dnd_indefinite", "Until turned off"},
{"dnd_active_until", "Do Not Disturb active until {time}"},
{"dnd_active_indefinite", "Do Not Disturb active (indefinite)"},
{"update_insufficient_permissions", "Cannot update automatically." & vbCrLf & "The application lacks write permissions in the installation directory." & vbCrLf & vbCrLf & "Please move the application to a writable location (e.g. Documents, Desktop, or USB drive)." & vbCrLf & "Avoid protected system directories like Program Files." & vbCrLf & vbCrLf & "Available version: v{version}"},
{"update_insufficient_permissions_title", "Insufficient Permissions"},
{"update_missing_checksum", "Cannot verify update integrity." & vbCrLf & vbCrLf & "No valid SHA-256 cryptographic checksum was provided with this version on GitHub." & vbCrLf & vbCrLf & "The update has been aborted for security reasons."},
{"update_integrity_failed_title", "Update Integrity Error"},
{"update_checksum_mismatch", "Update integrity check failed!" & vbCrLf & vbCrLf & "The SHA-256 cryptographic hash of the downloaded update file does not match the expected hash:" & vbCrLf & vbCrLf & "Computed: {computed}" & vbCrLf & "Expected: {expected}" & vbCrLf & vbCrLf & "The update has been aborted to ensure system safety."},
{"update_download_error", "Update download failed or timed out:" & vbCrLf & vbCrLf & "{error}"},
{"update_download_error_title", "Update Download Error"},
{"update_signature_invalid", "Digital signature verification failed on the update executable." & vbCrLf & vbCrLf & "The update has been aborted for security reasons."},
{"update_already_latest", "You already have the latest version (v{version})!"},
{"update_already_latest_title", "Up to Date"},
{"update_no_new_version", "The remote version (v{remote}) is older than or equal to current version (v{current})."},
{"update_no_new_version_title", "Update"},
{"update_available_prompt", "A new version of HidaChat (v{version}) is available!" & vbCrLf & vbCrLf & "Would you like to download and install the update now?"},
{"update_available_title", "Update Available"},
{"update_install_error", "An error occurred while installing the update:" & vbCrLf & vbCrLf & "{error}"},
{"update_install_error_title", "Update Error"},
{"update_check_failed", "Failed to check for updates:" & vbCrLf & vbCrLf & "{error}"},
{"update_check_failed_network", "Unable to check for updates. Please check your internet connection or try again later."},
{"update_check_failed_title", "Update Check"},
{"update_no_asset", "No update package is attached to the remote release."},
{"settings_corrupt_recovery_title", "Settings Recovery"},
{"settings_corrupt_recovered_msg", "The 'settings.json' configuration file was corrupted and has been archived as '{file}'." & vbCrLf & vbCrLf & "Settings and accounts have been successfully restored from the last available backup (.bak)."},
{"settings_corrupt_reset_title", "Configuration Error"},
{"settings_corrupt_reset_msg", "The 'settings.json' configuration file was corrupted and has been archived as '{file}'." & vbCrLf & vbCrLf & "A valid backup could not be recovered: the application has started with default settings."},
{"network_drive_warning_title", "Network Drive Warning"},
{"network_drive_warning_msg", "HidaChat is running from a network drive ({path})." & vbCrLf & vbCrLf & "Warning: Microsoft WebView2 does not support storing browser profiles on network drives or SMB shares. This frequently causes WhatsApp Web to lose its session or disconnect on restart." & vbCrLf & vbCrLf & "It is strongly recommended to run HidaChat from a local drive (e.g. C:\HidaChat)."},
{"network_drive_staging_info", "HidaChat is running from a network drive ({path})." & vbCrLf & vbCrLf & "Local Session Staging is ACTIVE: your chat sessions and login data are handled on local disk and synchronized to the network share on exit to prevent WebView2 session loss."},
{"network_drive_section", "Network Drives"},
{"enable_network_profile_staging", "Enable local staging for network drives"},
{"enable_network_profile_staging_hint", "Improves session stability and prevents WhatsApp disconnection when running from network shares (SMB/UNC)."},
{"network_drive_session_conflict", "Warning: Account '{name}' appears to be active on another computer ({machine}). Simultaneous usage may cause disconnects."},
{"secret_decrypt_error_title", "Credential Decryption Warning"},
{"secret_decrypt_error_msg", "Could not decrypt the stored Tailscale AuthKey: the application folder was opened on a different computer or Windows user profile (DPAPI protection is machine/user-bound)." & vbCrLf & vbCrLf & "To re-enable Tailscale integration, please re-enter the AuthKey in Settings."},
{"folder_locked_title", "Application Folder in Use"},
{"folder_locked_msg", "The HidaChat folder is currently locked and in use by another instance or computer:" & vbCrLf & vbCrLf & "• Machine: {machine}" & vbCrLf & "• User: {user}" & vbCrLf & "• PID: {pid}" & vbCrLf & "• Started at: {time}" & vbCrLf & vbCrLf & "To prevent WebView2 profile and session data corruption, running multiple concurrent instances from the same folder is not allowed."},
{"close", "Close"},
{"tab_hibernation_section", "Tab Hibernation"},
{"enable_tab_hibernation", "Enable inactive tab hibernation"},
{"enable_tab_hibernation_hint", "Reduces RAM usage by suspending background tabs when idle. They resume instantly when selected."},
{"tab_hibernation_timeout", "Inactivity timeout:"},
{"cache_section", "Cache & Storage"},
{"disk_cache_limit", "Chromium disk cache limit:"},
{"disk_cache_limit_hint", "Limits disk space used by Chromium HTTP cache per profile (applied upon tab reload)."},
{"smart_clean_cache_btn", "Clean Cache (keep login)"},
{"smart_clean_cache_hint", "Deletes temporary files, HTTP cache, shaders and GPU cache without logging out (cookies, sessions and IndexedDB remain intact)."},
{"smart_clean_cache_confirm_title", "Clean Cache"},
{"smart_clean_cache_confirm_msg", "Do you want to clean temporary files and browser caches for all accounts? Login sessions and credentials will be preserved."},
{"smart_clean_cache_success_title", "Cache Cleaned"},
{"smart_clean_cache_success_msg", "Cache cleanup completed successfully! Account sessions and logins were preserved."},
{"account_clean_cache", "Clean account cache"},
{"hibernated_badge_tooltip", "Tab hibernated (auto-resumes on click)"},
{"account_repair_tab", "Repair tab (reset corrupted database)"},
{"account_repair_confirm_title", "Repair Tab"},
{"account_repair_confirm_msg", "This will repair the tab's local database and service worker cache, then reload the page to fix white screens and data corruption. Continue?"},
{"account_repair_success_title", "Repair Completed"},
{"account_repair_success_msg", "The tab's storage has been repaired and the page has been reloaded."},
{"shutdown_dialog_title", "Closing HidaChat"},
{"shutdown_dialog_header", "Saving data and closing..."},
{"shutdown_stage_settings", "Saving settings and account preferences..."},
{"shutdown_stage_webviews", "Gracefully terminating web browser processes..."},
{"shutdown_stage_network_sync", "Synchronizing profiles and chat sessions to network share..."},
{"shutdown_stage_tsnet", "Stopping network proxy and releasing lock leases..."},
{"shutdown_stage_complete", "Finalizing and closing..."},
{"tailscale_dialog_title", "Tailscale Connection Status"},
{"tailscale_dialog_header", "Unable to load {platform}: {name}"},
{"tailscale_error_tsnet_needs_login", "The embedded Tailscale node requires authentication. Please log in to connect to your Tailnet and access the service."},
{"tailscale_error_tsnet_stopped", "The embedded Tailscale service (tsnet) is not running or failed to initialize."},
{"tailscale_error_node_unreachable", "Tailscale connection is active, but the remote host '{host}' is unreachable or offline. Please check that the remote device is powered on and connected to your Tailnet."},
{"tailscale_error_client_disconnected", "The Tailscale client is not running or disconnected on this computer. Please launch and connect Tailscale, then try again."},
{"tailscale_error_generic_failure", "Unable to reach the server '{host}'. A network or connection timeout error occurred."},
{"tailscale_btn_retry", "Retry"},
{"tailscale_btn_login", "Log in to Tailscale"},
{"tailscale_btn_settings", "Open Settings"},
{"tailscale_btn_close", "Close"},
{"storage_recovery_dialog_title", "Storage Integrity Recovery"},
{"storage_recovery_dialog_header", "Repairing local storage and database..."},
{"storage_recovery_stage_checking", "Checking IndexedDB and storage integrity for {account}..."},
{"storage_recovery_stage_detected", "Storage corruption detected for {account}. Rebuilding database..."},
{"storage_recovery_stage_repairing", "Purging corrupted IndexedDB/ServiceWorker caches (preserving logins)..."},
{"storage_recovery_stage_reloading", "Reloading web view and mounting clean database..."},
{"storage_recovery_stage_completed", "Storage recovery completed successfully!"},
{"translation_privacy_title", "Translation & Privacy Notice"},
{"translation_privacy_header", "Authorize Message Translation"},
{"translation_privacy_body", "To translate chat messages not yet cached locally, their text will be sent to the configured translation provider ({provider})." & vbLf & vbLf & "Cloud providers (e.g. Google Translate) transmit message content to remote servers. You can also configure a local or self-hosted provider (LibreTranslate, Ollama, LM Studio) in Settings to keep all data on your machine." & vbLf & vbLf & "Do you want to authorize message translations?"},
{"translation_privacy_allow", "Allow & Enable"},
{"translation_privacy_settings", "Configure Provider..."},
{"translation_consent_declined", "Translation cancelled: privacy consent required"},
{"translation_provider", "Translation Provider"},
{"translation_privacy_consent_checkbox", "I consent to sending message text to the selected translation provider"},
{"translation_url", "Endpoint URL:"},
{"translation_model", "Model Name:"},
{"translation_api_key", "API Key (optional):"},
{"translation_test_btn", "Test Connection"},
{"translation_test_success", "✓ Connected successfully ({latency} ms)"},
{"translation_test_failure", "✗ Connection failed: {error}"},
{"translation_provider_unreachable", "Translation failed: Provider unreachable"}
}
''' <summary>Dizionario di localizzazione nativa per l'interfaccia in lingua Italiana.</summary>
Public Shared ReadOnly ItStrings As New Dictionary(Of String, String)(StringComparer.OrdinalIgnoreCase) From {
{"settings", "Impostazioni"},
{"theme", "Tema"},
{"system", "Sistema"},
{"light", "Chiaro"},
{"dark", "Scuro"},
{"match_cohesive", "Abbina questa impostazione nelle tue app per un aspetto coerente."},
{"manage_accounts", "Gestione Account"},
{"add_account", "Aggiungi account"},
{"add_whatsapp_account", "Aggiungi account WhatsApp"},
{"add_telegram_account", "Aggiungi account Telegram"},
{"add_openclaw_account", "Aggiungi account OpenClaw"},
{"add_hermes_account", "Aggiungi account Hermes Agent"},
{"openclaw_server_url", "URL Gateway / Tailscale:"},
{"openclaw_auth_token", "Token di Autenticazione Gateway:"},
{"test_connection", "Verifica Connessione"},
{"connection_testing", "Verifica in corso..."},
{"connection_success", "✓ In linea"},
{"connection_failed", "✗ Non raggiungibile"},
{"select_platform", "Seleziona piattaforma"},
{"always_show_tab_bar", "Mostra sempre la barra delle schede"},
{"updates", "Aggiornamenti"},
{"check_updates_launch", "Controlla aggiornamenti all'avvio"},
{"check_now", "Controlla Ora"},
{"devtools", "Strumenti di sviluppo"},
{"debug_active_tab", "Debug scheda attiva"},
{"delete_account_title", "Elimina Account"},
{"delete_account_confirm", "Eliminare ""{name}""? Tutti i dati di questo account verranno rimossi."},
{"delete_account_last", "Non è possibile eliminare l'unico account attivo."},
{"cancel", "Annulla"},
{"delete", "Elimina"},
{"rename", "Rinomina"},
{"language", "Lingua"},
{"translate_to_lang", "Traduci in {lang}"},
{"translate_all_messages", "Traduci tutti i messaggi"},
{"toggle_window", "Mostra / Nascondi finestra"},
{"exit", "Esci"},
{"translate_message_button", "Pulsante traduci messaggio"},
{"keep_app_in_english", "Mantieni interfaccia in inglese"},
{"full_page_translation", "Traduci l'intera pagina"},
{"show_translate_all_messages_button", "Pulsante traduci tutto nella barra del titolo"},
{"reload_active_tab", "Ricarica scheda attiva"},
{"use_beta_channel", "Usa canale di aggiornamento beta"},
{"notifications", "Notifiche"},
{"show_message_popup", "Mostra popup messaggio"},
{"accounts_count_info", "Account configurati: {count} su {max}"},
{"max_accounts_reached", "Raggiunto il limite massimo di {max} account."},
{"max_accounts_downgrade_notice", "Avviso di downgrade: sono presenti {count} account attivi rispetto al limite massimo di {max}. Gli account esistenti restano attivi e funzionanti, ma non sarà possibile aggiungerne di nuovi finché non si rientra nel limite."},
{"accounts_downgrade_blocked", "Impossibile aggiungere un account: sono presenti {count} account rispetto al limite massimo impostato di {max}. Rimuovi uno o più account o aumenta il limite per poterne aggiungere altri."},
{"max_accounts", "Max account:"},
{"about", "Informazioni"},
{"about_title", "Informazioni su HidaChat"},
{"app_description", "Client desktop Windows portatile, leggero e multi-account (WhatsApp, Telegram, OpenClaw, Hermes)."},
{"author", "Autore"},
{"release_date", "Data di rilascio"},
{"license", "Licenza"},
{"runtime_environment", "Ambiente e Framework"},
{"portable_directory", "Percorso Dati Portatile"},
{"github_repository", "Repository GitHub"},
{"report_issue", "Segnala Problema"},
{"view_releases", "Visualizza Release"},
{"bulk_sender", "Invio Massivo Excel / CSV"},
{"custom_css", "CSS Personalizzato"},
{"enable_custom_css", "Abilita regole CSS personalizzate"},
{"custom_css_placeholder", "/* Inserisci qui il tuo CSS personalizzato per WhatsApp e Telegram Web */"},
{"apply_css", "Applica CSS"},
{"css_applied", "CSS applicato con successo!"},
{"css_preset_oled", "OLED Nero Puro"},
{"css_preset_compact", "Layout Compatto"},
{"css_preset_font", "Font Moderno"},
{"css_preset_reset", "Ripristina"},
{"contact_online", "Online"},
{"contact_typing", "sta scrivendo..."},
{"spellchecker", "Controllo Ortografico"},
{"enable_spellchecker", "Abilita correttore ortografico nei campi di testo"},
{"spellchecker_language", "Lingua del dizionario"},
{"spellchecker_lang_auto", "Automatica (segue la lingua dell'app)"},
{"spellchecker_restart_hint", "Le modifiche avranno effetto ricaricando le schede o riavviando HidaChat."},
{"dnd_mode", "Non Disturbare (Focus Mode)"},
{"dnd_enable", "Disattiva tutte le notifiche e i suoni"},
{"dnd_duration", "Durata"},
{"dnd_30m", "Per 30 minuti"},
{"dnd_1h", "Per 1 ora"},
{"dnd_2h", "Per 2 ore"},
{"dnd_8h", "Per 8 ore"},
{"dnd_indefinite", "Fino a disattivazione"},
{"dnd_active_until", "Non Disturbare attivo fino alle {time}"},
{"dnd_active_indefinite", "Non Disturbare attivo (indefinito)"},
{"update_insufficient_permissions", "Impossibile aggiornare automaticamente." & vbCrLf & "L'applicazione non dispone dei permessi di scrittura nella cartella di installazione." & vbCrLf & vbCrLf & "Sposta l'applicazione in una cartella scrivibile dall'utente (es. Documenti, Desktop, o cartella su chiavetta USB)." & vbCrLf & "Evita directory di sistema protette come Programmi." & vbCrLf & vbCrLf & "Versione disponibile: v{version}"},
{"update_insufficient_permissions_title", "Permessi Insufficienti"},
{"update_missing_checksum", "Impossibile verificare l'integrità dell'aggiornamento." & vbCrLf & vbCrLf & "Nessun checksum crittografico SHA-256 valido è stato fornito con questa versione su GitHub." & vbCrLf & vbCrLf & "L'aggiornamento è stato interrotto per garantire la sicurezza del sistema."},
{"update_integrity_failed_title", "Errore Integrità Aggiornamento"},
{"update_checksum_mismatch", "Verifica di integrità fallita!" & vbCrLf & vbCrLf & "L'impronta crittografica SHA-256 del file di aggiornamento scaricato non corrisponde a quella attesa:" & vbCrLf & vbCrLf & "Hash calcolato: {computed}" & vbCrLf & "Hash atteso: {expected}" & vbCrLf & vbCrLf & "L'aggiornamento è stato interrotto per garantire la sicurezza del sistema."},
{"update_download_error", "Download dell'aggiornamento non riuscito o timeout superato:" & vbCrLf & vbCrLf & "{error}"},
{"update_download_error_title", "Errore Download Aggiornamento"},
{"update_signature_invalid", "Verifica della firma digitale fallita sull'eseguibile di aggiornamento." & vbCrLf & vbCrLf & "L'installazione è stata interrotta per garantire la sicurezza del sistema."},
{"update_already_latest", "Hai già la versione più recente (v{version})!"},
{"update_already_latest_title", "Aggiornato"},
{"update_no_new_version", "La versione remota (v{remote}) è precedente o uguale a quella corrente (v{current})."},
{"update_no_new_version_title", "Aggiornamento"},
{"update_available_prompt", "È disponibile una nuova versione di HidaChat (v{version})!" & vbCrLf & vbCrLf & "Desideri scaricare ed installare l'aggiornamento ora?"},
{"update_available_title", "Aggiornamento Disponibile"},
{"update_install_error", "Errore durante l'installazione dell'aggiornamento:" & vbCrLf & vbCrLf & "{error}"},
{"update_install_error_title", "Errore Aggiornamento"},
{"update_check_failed", "Errore durante la verifica degli aggiornamenti:" & vbCrLf & vbCrLf & "{error}"},
{"update_check_failed_network", "Impossibile verificare la presenza di aggiornamenti. Verifica la connessione Internet o riprova più tardi."},
{"update_check_failed_title", "Verifica Aggiornamenti"},
{"update_no_asset", "Nessun pacchetto di aggiornamento valido allegato alla versione remota."},
{"settings_corrupt_recovery_title", "Ripristino Impostazioni"},
{"settings_corrupt_recovered_msg", "Il file di configurazione 'settings.json' risultava danneggiato ed è stato archiviato come '{file}'." & vbCrLf & vbCrLf & "Le impostazioni e gli account sono stati ripristinati con successo dall'ultimo backup (.bak) disponibile."},
{"settings_corrupt_reset_title", "Errore Configurazione"},
{"settings_corrupt_reset_msg", "Il file di configurazione 'settings.json' risultava danneggiato ed è stato archiviato come '{file}'." & vbCrLf & vbCrLf & "Non è stato possibile recuperare un backup valido: l'applicazione è stata avviata con le impostazioni predefinite."},
{"network_drive_warning_title", "Avviso Unità di Rete"},
{"network_drive_warning_msg", "HidaChat è in esecuzione da un'unità di rete ({path})." & vbCrLf & vbCrLf & "Attenzione: Microsoft WebView2 non supporta l'archiviazione dei profili browser su unità di rete o condivisioni SMB. Questo causa frequentemente la disconnessione o la perdita della sessione di WhatsApp ad ogni riavvio." & vbCrLf & vbCrLf & "Si raccomanda di eseguire HidaChat da un disco locale (es. C:\HidaChat)."},
{"network_drive_staging_info", "HidaChat è in esecuzione su un'unità di rete ({path})." & vbCrLf & vbCrLf & "Lo Staging Locale delle Sessioni è ATTIVO: le credenziali e i database vengono gestiti localmente e risincronizzati automaticamente sulla cartella di rete alla chiusura per prevenire disconnessioni di WebView2."},
{"network_drive_section", "Unità di Rete"},
{"enable_network_profile_staging", "Abilita staging locale per dischi di rete"},
{"enable_network_profile_staging_hint", "Migliora la stabilità e previene la perdita della sessione WhatsApp quando l'app risiede su cartelle di rete (SMB/UNC)."},
{"network_drive_session_conflict", "Attenzione: L'account '{name}' risulta già attivo su un altro computer ({machine}). L'uso simultaneo può causare disconnessioni."},
{"secret_decrypt_error_title", "Avviso Decifratura Credenziali"},
{"secret_decrypt_error_msg", "Impossibile decifrare la chiave Tailscale AuthKey memorizzata: la cartella dell'applicazione è stata aperta su un computer o profilo utente Windows differente rispetto a dove è stata salvata (la protezione DPAPI è vincolata alla macchina/utente locale)." & vbCrLf & vbCrLf & "Per riattivare l'integrazione con Tailscale, reinserisci l'AuthKey nelle Impostazioni."},
{"folder_locked_title", "Cartella Applicazione in Uso"},
{"folder_locked_msg", "La cartella di HidaChat è attualmente bloccata ed in uso da un'altra postazione o processo:" & vbCrLf & vbCrLf & "• Computer: {machine}" & vbCrLf & "• Utente: {user}" & vbCrLf & "• PID: {pid}" & vbCrLf & "• Avviato il: {time}" & vbCrLf & vbCrLf & "Per prevenire la corruzione dei profili WebView2 e dei dati di sessione, non è consentito avviare contemporaneamente più istanze dalla stessa cartella."},
{"close", "Chiudi"},
{"tab_hibernation_section", "Ibernazione Schede"},
{"enable_tab_hibernation", "Abilita ibernazione schede inattive"},
{"enable_tab_hibernation_hint", "Riduce il consumo di memoria RAM sospendendo le schede in background inattive. Si riattivano istantaneamente quando vengono selezionate."},
{"tab_hibernation_timeout", "Tempo di inattività:"},
{"cache_section", "Cache e Archiviazione"},
{"disk_cache_limit", "Limite cache disco Chromium:"},
{"disk_cache_limit_hint", "Limita lo spazio massimo su disco occupato dalla cache HTTP di Chromium per profilo (applicato alla ricarica della scheda)."},
{"smart_clean_cache_btn", "Pulisci Cache (preserva login)"},
{"smart_clean_cache_hint", "Elimina file temporanei, cache HTTP, shader e GPU senza disconnettere gli account (cookie, sessioni e IndexedDB rimangono intatti)."},
{"smart_clean_cache_confirm_title", "Pulizia Cache"},
{"smart_clean_cache_confirm_msg", "Vuoi eseguire la pulizia dei file temporanei e della cache browser per tutti gli account? Le sessioni di accesso e le credenziali verranno preservate."},
{"smart_clean_cache_success_title", "Pulizia Completata"},
{"smart_clean_cache_success_msg", "Pulizia cache completata con successo! Le sessioni degli account sono state preservate."},
{"account_clean_cache", "Pulisci cache account"},
{"hibernated_badge_tooltip", "Scheda ibernata (risveglio automatico al click)"},
{"account_repair_tab", "Ripara scheda (ripristina database corrotto)"},
{"account_repair_confirm_title", "Ripara Scheda"},
{"account_repair_confirm_msg", "Questa operazione ripristinerà il database locale e la cache dei service worker della scheda, quindi ricaricherà la pagina per risolvere schermate bianche o corruzioni dei dati. Continuare?"},
{"account_repair_success_title", "Riparazione Completata"},
{"account_repair_success_msg", "Lo storage della scheda è stato riparato e la pagina è stata ricaricata."},
{"shutdown_dialog_title", "Chiusura di HidaChat"},
{"shutdown_dialog_header", "Salvataggio dati e chiusura in corso..."},
{"shutdown_stage_settings", "Salvataggio impostazioni e preferenze account..."},
{"shutdown_stage_webviews", "Chiusura controllata delle sessioni browser..."},
{"shutdown_stage_network_sync", "Sincronizzazione profili e chat su cartella di rete..."},
{"shutdown_stage_tsnet", "Arresto proxy di rete e rilascio risorse..."},
{"shutdown_stage_complete", "Finalizzazione e chiusura..."},
{"tailscale_dialog_title", "Stato Connessione Tailscale"},
{"tailscale_dialog_header", "Impossibile caricare {platform}: {name}"},
{"tailscale_error_tsnet_needs_login", "Il nodo Tailscale integrato richiede l'autenticazione. Effettua il login per connetterti alla tua Tailnet e accedere al servizio."},
{"tailscale_error_tsnet_stopped", "Il servizio Tailscale integrato (tsnet) non è in esecuzione o non è riuscito ad avviarsi."},
{"tailscale_error_node_unreachable", "La connessione Tailscale è attiva, ma l'host remoto '{host}' non è raggiungibile o è spento. Verifica che il dispositivo remoto sia acceso e connesso alla tua Tailnet."},
{"tailscale_error_client_disconnected", "Il client Tailscale non risulta attivo o connesso su questo computer. Avvia e connetti Tailscale, quindi riprova."},
{"tailscale_error_generic_failure", "Impossibile raggiungere il server '{host}'. Si è verificato un errore di rete o timeout di connessione."},
{"tailscale_btn_retry", "Riprova"},
{"tailscale_btn_login", "Accedi a Tailscale"},
{"tailscale_btn_settings", "Apri Impostazioni"},
{"tailscale_btn_close", "Chiudi"},
{"storage_recovery_dialog_title", "Ripristino Integrità Storage"},
{"storage_recovery_dialog_header", "Ripristino storage locale e database in corso..."},
{"storage_recovery_stage_checking", "Verifica integrità IndexedDB e storage per {account}..."},
{"storage_recovery_stage_detected", "Rilevata corruzione dello storage per {account}. Rigenerazione database..."},
{"storage_recovery_stage_repairing", "Pulizia cache IndexedDB/ServiceWorker corrotte (sessioni salvaguardate)..."},
{"storage_recovery_stage_reloading", "Ricaricamento vista web e inizializzazione database pulito..."},
{"storage_recovery_stage_completed", "Ripristino storage completato con successo!"},
{"translation_privacy_title", "Informativa sulla Privacy e Traduzioni"},
{"translation_privacy_header", "Autorizzazione Traduzione Messaggi"},
{"translation_privacy_body", "Per tradurre i messaggi di chat non ancora presenti nella cache locale, il relativo testo verrà inviato al fornitore di traduzione configurato ({provider})." & vbLf & vbLf & "I provider in cloud (come Google Translate) trasmettono il contenuto dei messaggi a server remoti. Puoi anche configurare un provider locale o self-hosted (LibreTranslate, Ollama, LM Studio) nelle Impostazioni per mantenere tutti i dati sul tuo computer." & vbLf & vbLf & "Vuoi autorizzare la traduzione dei messaggi?"},
{"translation_privacy_allow", "Consenti e Attiva"},
{"translation_privacy_settings", "Configura Provider..."},
{"translation_consent_declined", "Traduzione annullata: consenso privacy non concesso"},
{"translation_provider", "Fornitore di Traduzione"},
{"translation_privacy_consent_checkbox", "Acconsento all'invio del testo dei messaggi al provider di traduzione selezionato"},
{"translation_url", "URL Endpoint:"},
{"translation_model", "Nome Modello:"},
{"translation_api_key", "Chiave API (opzionale):"},
{"translation_test_btn", "Testa Connessione"},
{"translation_test_success", "✓ Connesso con successo ({latency} ms)"},
{"translation_test_failure", "✗ Connessione non riuscita: {error}"},
{"translation_provider_unreachable", "Traduzione non riuscita: Provider non raggiungibile"}
}
''' <summary>Dizionario di localizzazione nativa per l'interfaccia in lingua Francese.</summary>
Public Shared ReadOnly FrStrings As New Dictionary(Of String, String)(StringComparer.OrdinalIgnoreCase) From {
{"settings", "Paramètres"},
{"theme", "Thème"},
{"system", "Système"},
{"light", "Clair"},
{"dark", "Sombre"},
{"match_cohesive", "Harmonisez ce paramètre dans vos applications pour un aspect cohérent."},
{"manage_accounts", "Gestion des comptes"},
{"add_account", "Ajouter un compte"},
{"add_whatsapp_account", "Ajouter un compte WhatsApp"},
{"add_telegram_account", "Ajouter un compte Telegram"},
{"add_openclaw_account", "Ajouter un compte OpenClaw"},
{"add_hermes_account", "Ajouter un compte Hermes Agent"},
{"openclaw_server_url", "URL Passerelle / Tailscale :"},
{"openclaw_auth_token", "Jeton d'authentification Passerelle :"},
{"test_connection", "Tester la connexion"},
{"connection_testing", "Vérification..."},
{"connection_success", "✓ En ligne"},
{"connection_failed", "✗ Inaccessible"},
{"select_platform", "Sélectionner la plateforme"},
{"always_show_tab_bar", "Toujours afficher la barre des onglets"},
{"updates", "Mises à jour"},
{"check_updates_launch", "Rechercher les mises à jour au démarrage"},
{"check_now", "Vérifier maintenant"},
{"devtools", "Outils de développement"},
{"debug_active_tab", "Déboguer l'onglet actif"},
{"delete_account_title", "Supprimer le compte"},
{"delete_account_confirm", "Supprimer ""{name}"" ? Toutes les données de ce compte seront supprimées."},
{"delete_account_last", "Vous ne pouvez pas supprimer le seul compte actif."},
{"cancel", "Annuler"},
{"delete", "Supprimer"},
{"rename", "Renommer"},
{"language", "Langue"},
{"translate_to_lang", "Traduire en {lang}"},
{"translate_all_messages", "Traduire tous les messages"},
{"toggle_window", "Afficher / Masquer la fenêtre"},
{"exit", "Quitter"},
{"translate_message_button", "Bouton de traduction du message"},
{"keep_app_in_english", "Conserver l'interface en anglais"},
{"full_page_translation", "Traduire toute la page"},
{"show_translate_all_messages_button", "Bouton de traduction de tous les messages dans la barre"},
{"reload_active_tab", "Recharger l'onglet actif"},
{"use_beta_channel", "Utiliser le canal de mise à jour bêta"},
{"notifications", "Notifications"},
{"show_message_popup", "Afficher la notification popup"},
{"accounts_count_info", "Comptes configurés : {count} sur {max}"},
{"max_accounts_reached", "Limite maximale de {max} comptes atteinte."},
{"max_accounts_downgrade_notice", "Avis de déclassement : vous avez {count} comptes actifs dépassant la limite maximale de {max}. Les comptes existants sont conservés et opérationnels, mais l'ajout de nouveaux comptes est désactivé jusqu'à ce que vous soyez sous la limite."},
{"accounts_downgrade_blocked", "Impossible d'ajouter un compte : vous avez {count} comptes configurés pour une limite de {max}. Supprimez un ou plusieurs comptes ou augmentez la limite pour en ajouter de nouveaux."},
{"max_accounts", "Comptes maximum :"},
{"about", "À propos"},
{"about_title", "À propos de HidaChat"},
{"app_description", "Client de bureau multi-comptes léger et portable pour Windows (WhatsApp, Telegram, OpenClaw, Hermes)."},
{"author", "Auteur"},
{"release_date", "Date de version"},
{"license", "Licence"},
{"runtime_environment", "Environnement et Framework"},
{"portable_directory", "Répertoire de données portable"},
{"github_repository", "Dépôt GitHub"},
{"report_issue", "Signaler un problème"},
{"view_releases", "Voir les versions"},
{"bulk_sender", "Envoi en masse Excel / CSV"},
{"custom_css", "CSS Personnalisé"},
{"enable_custom_css", "Activer les règles CSS personnalisées"},
{"custom_css_placeholder", "/* Écrivez ou collez ici votre CSS personnalisé pour WhatsApp et Telegram Web */"},
{"apply_css", "Appliquer le CSS"},
{"css_applied", "CSS appliqué avec succès !"},
{"css_preset_oled", "OLED Noir Pur"},
{"css_preset_compact", "Disposition compacte"},
{"css_preset_font", "Police moderne"},
{"css_preset_reset", "Effacer"},