iobroker.ical 1.12.1 → 1.12.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -0
- package/admin/words.js +2 -2
- package/docs/de/README.md +12 -3
- package/docs/en/README.md +14 -5
- package/io-package.json +13 -13
- package/main.js +1 -1
- package/package.json +11 -11
- package/lib/tools.js +0 -99
package/README.md
CHANGED
|
@@ -26,6 +26,9 @@ Siehe deutsche [Version hier](docs/de/README.md).
|
|
|
26
26
|
Placeholder for the next version (at the beginning of the line):
|
|
27
27
|
### **WORK IN PROGRESS**
|
|
28
28
|
-->
|
|
29
|
+
### 1.12.2 (2022-06-03)
|
|
30
|
+
* (Apollon77) Fix displaying rest-time of event in one case
|
|
31
|
+
|
|
29
32
|
### 1.12.1 (2022-03-22)
|
|
30
33
|
* (Apollon77) Adjust colorize of dates to also show dates started in the past with todays color
|
|
31
34
|
|
package/admin/words.js
CHANGED
|
@@ -22,7 +22,7 @@ systemDictionary = {
|
|
|
22
22
|
"Use by full day:": { "en": "Replace 00:00 with", "de": "Ersetze 00:00 mit", "ru": "Заменять 00:00 на", "pt": "Substitua 00:00 com", "nl": "Vervang 00:00 met", "fr": "Remplacer 00:00 avec", "it": "Sostituisci 00:00 con", "es": "Reemplace 00:00 con", "pl": "Zamień 00:00 na", "zh-cn": "将 00:00 替换为"},
|
|
23
23
|
"color": { "en": "Color", "de": "Farbe", "ru": "Цвет", "pt": "Cor", "nl": "Kleur", "fr": "Couleur", "it": "Colore", "es": "Color", "pl": "Kolor", "zh-cn": "颜色"},
|
|
24
24
|
"display": { "en": "display", "de": "anzeigen", "ru": "показать в списке", "pt": "mostrar", "nl": "weergeven", "fr": "afficher", "it": "display", "es": "monitor", "pl": "pokaz", "zh-cn": "展示"},
|
|
25
|
-
"enabled": { "en": "enabled", "de": "
|
|
25
|
+
"enabled": { "en": "enabled", "de": "Aktiviert", "ru": "активно", "pt": "ativado", "nl": "actief", "fr": "activée", "it": "abilitato", "es": "habilitado", "pl": "włączony", "zh-cn": "启用"},
|
|
26
26
|
"filter": { "en": "Filter", "de": "Filter", "ru": "Фильтр", "pt": "Filtro", "nl": "Filter", "fr": "Filtre", "it": "Filtro", "es": "Filtrar", "pl": "Filtr", "zh-cn": "筛选"},
|
|
27
27
|
"filterregex": { "en": "Filter as regular expression", "de": "Filter als regulärer Ausdruck", "ru": "Фильтровать как регулярное выражение", "pt": "Filtrar como expressão regular", "nl": "Filter als reguliere expressie", "fr": "Filtrer en tant qu'expression régulière", "it": "Filtra come espressione regolare", "es": "Filtrar como expresión regular.", "pl": "Filtruj jako wyrażenie regularne", "zh-cn": "过滤为正则表达式"},
|
|
28
28
|
"iCal adapter settings": { "en": "iCal adapter settings", "de": "iCal Adapter Einstellungen", "ru": "iCal Настройки", "pt": "Configurações do adaptador iCal", "nl": "iCal Instellingen", "fr": "Paramètres de l'adaptateur iCal", "it": "Impostazioni della scheda iCal", "es": "Configuración del adaptador iCal", "pl": "Ustawienia adaptera iCal", "zh-cn": "iCal 适配器设置"},
|
|
@@ -31,4 +31,4 @@ systemDictionary = {
|
|
|
31
31
|
"sslignore": { "en": "Ignore SSL errors", "de": "SSL-Fehler ignorieren", "ru": "Игнор ошибок SSL", "pt": "Ignorar erros de SSL", "nl": "SSL fout negeren", "fr": "Ignorer les erreurs SSL", "it": "Ignora errori SSL", "es": "Ignorar los errores de SSL", "pl": "Zignoruj błędy SSL", "zh-cn": "忽略 SSL 错误"},
|
|
32
32
|
"url": { "en": "Calendar URL or file name", "de": "Kalender URL oder Dateiname", "ru": "URL календаря или имя файла", "pt": "URL do calendário ou nome do arquivo", "nl": "Agend URL of bestandsnaam", "fr": "URL du calendrier ou nom de fichier", "it": "URL del calendario o nome del file", "es": "URL del calendario o nombre del archivo", "pl": "URL kalendarza lub nazwa pliku", "zh-cn": "日历 URL 或文件名"},
|
|
33
33
|
"user": { "en": "Username", "de": "Benutzername", "ru": "Имя пользователя", "pt": "Nome de usuário", "nl": "Gebruikersnaam", "fr": "Nom d'utilisateur", "it": "Nome utente", "es": "Nombre de usuario", "pl": "Nazwa Użytkownika", "zh-cn": "用户名"},
|
|
34
|
-
};
|
|
34
|
+
};
|
package/docs/de/README.md
CHANGED
|
@@ -33,7 +33,7 @@ Bedeutung der Optionen im Konfigfile:
|
|
|
33
33
|
|
|
34
34
|
- `preview`: 7 heisst, dass Termine 7 Tage im voraus angezeigt werden
|
|
35
35
|
- `runEveryMinutes`: 30 bedeutet dass der Adapter automatisch alle 30min den Kalender neu einliesst. Bei 0 wird nicht automatisch eingelesen
|
|
36
|
-
- `colorize`: true Termine am heutigen Tag werden rot gefärbt, Termine am morgigen Tag orange, diese Option überstimmt die Option everyCalOneColor
|
|
36
|
+
- `colorize`: true Termine am heutigen Tag sowie aktuell laufende Termine werden rot gefärbt, Termine am morgigen Tag orange, diese Option überstimmt die Option everyCalOneColor
|
|
37
37
|
- `debug`: false bei true werden erweiterte Ausgaben ins CCU.IO Log geschrieben
|
|
38
38
|
- `defColor`: `white` legt die Standardfarbe der Kalendereinträge fest
|
|
39
39
|
- `fulltime`: ` ` legt fest durch welchen String bei ganztägigen Terminen die Uhrzeit 00:00 ersetzt wird. Bei Leerzeichen (zwischen den Hochkommas) wird dir Uhrzeit bei ganztägigen Terminen weggelassen
|
|
@@ -47,7 +47,10 @@ Bedeutung der Optionen im Konfigfile:
|
|
|
47
47
|
- `Events`:
|
|
48
48
|
- `name`: "Urlaub":
|
|
49
49
|
- `enabled`: true # legt fest, ob das Event bearbeitet wird
|
|
50
|
+
- `Set ID`: Hier kann ein zusätzlicher State eingetragen werden, welcher aktualisiert wird, wenn das Event aktiv ist
|
|
51
|
+
- `On / Off`: Hier kann ein alternativer Wert in den bei 'Set ID' hinterlegten State geschrieben werden
|
|
50
52
|
- `display`: false # legt fest, ob das Event auch in dem iCalEvents angezeigt wird, oder nur ausgewertet wird
|
|
53
|
+
- `Set Ack`: false # Ack "aus" steuert den State um z.B. etwas zu schalten. #true Ack "an" aktualisiert den Wert
|
|
51
54
|
|
|
52
55
|
Durch setzen eines Events (in diesem Beispiel „Urlaub“), werden die Kalender nach dem String „Urlaub“ durchsucht.
|
|
53
56
|
Sollte ein Termin mit dem Stichwort „Urlaub“ in einem Kalender stehen, so wird automatisch eine State mit dem
|
|
@@ -55,6 +58,12 @@ Bedeutung der Optionen im Konfigfile:
|
|
|
55
58
|
Es wird für jeden Tag des preview Zeitraums ein Status angelegt. Achtung!
|
|
56
59
|
Es wird nach einem Substring gesucht, d.h. ein Eintrag im Kalender „Urlaub“ wird genauso erkannt wie ein
|
|
57
60
|
Eintrag „Urlaub Eltern“. Dies ist beim festlegen der Ereignisse zu berücksichtigen.
|
|
61
|
+
|
|
62
|
+
- Erklärung zu den States unter ical.0.events.0
|
|
63
|
+
- Das Event im Pfad ical.0.events.0.later wird auf true gesetzt, wenn es heute noch stattfindet aber noch nicht begonnen ist
|
|
64
|
+
- Das Event im Pfad ical.0.events.0.now wird auf true gesetzt, wenn es aktuell aktiv ist
|
|
65
|
+
- Das Event im Pfad ical.0.events.0.today wird auf true gesetzt, wenn das Event am heutigen Tag aktiv ist
|
|
66
|
+
- Hinweis: Termine der Vortage werden nicht angezeigt
|
|
58
67
|
|
|
59
68
|
Durch Anpassen der CSS im VIS können die Styles von heutigen (Standard rot) und morgigen Terminen (Standard Orange) festegelegt werden:
|
|
60
69
|
- `iCalWarn` - Zeilenanfang Kalendereintrag heute
|
|
@@ -72,13 +81,13 @@ Dazu mit der rechten Maustaste auf dem Kalender in der Kalender App klicken und
|
|
|
72
81
|
Zum Einbinden eines Google Kalenders muss die Kalendereinstellung des Google Kalenders aufgerufen werden (mit der Maus auf "runter Pfeil" neben dem Kalender klicken). Die URL des Kalenders bekommt man durch klicken auf das `ICAL` Symbol neben dem Feld "Privatadresse". Diese URL dann entweder in den Settings bei defaultURL eintragen, oder sie bei `read URL` angeben, also z.B. `readURL https://www.google.com/calendar/ical/xxxxxxxx/basic.ics`.
|
|
73
82
|
|
|
74
83
|
#### OwnCloud Kalender
|
|
75
|
-
Zum Einbinden von
|
|
84
|
+
Zum Einbinden von geteilten Kalendern einer OwnCloud muss man dort in der Kalenderansicht in OwnCloud diesen Kalender als geteilten Kalender freigeben und dort den Link zum Kalender anzeigen lassen und diese URL (https://<DOMAIN>/remote.php/dav/calendars/USER/xxxxxxx_shared_by_xxxxxx?export) entsprechend in den ioBroker.ical Adapter mit Nutzername und Passwort angeben.
|
|
76
85
|
|
|
77
86
|
#### NextCloud Kalender
|
|
78
87
|
Zum Einbinden eines NextCloud Kalenders muss in der Kalenderansicht in NextCloud der Herunterladen-Link des einzelnen gewünschte Kalender eines Anwenders kopiert werden.
|
|
79
88
|
Dazu als Anwender in Nextcloud einloggen und zum 'Kalender' wechseln. In der linken Spalte den gewünschten Kalender bei dem Kreis mit den drei Punkten anklicken.
|
|
80
89
|
Im Menu mit der Maus über 'Herunterladen' schweben und mittels Rechtsklick den Link kopieren.
|
|
81
|
-
Bsp.: https
|
|
90
|
+
Bsp.: https://<DOMAIN>/remote.php/dav/calendars/MEINCALENDER/personal/?export (wichtig ist, dass hier "?export" im Link enthalten ist).
|
|
82
91
|
|
|
83
92
|
Diese URL in den ioBroker.ical Adapter mit Nutzername und Passwort angeben. Dieses muss für alle gewünschten Kalender aller User einzeln erfolgen.
|
|
84
93
|
|
package/docs/en/README.md
CHANGED
|
@@ -35,7 +35,7 @@ Meaning of the options in the config file:
|
|
|
35
35
|
|
|
36
36
|
- `preview`: 7 # means that appointments are displayed 7 days in advance
|
|
37
37
|
- `runEveryMinutes`: 30 # means that the adapter automatically rewists the calendar every 30 minutes. If 0 is not read automatically
|
|
38
|
-
- `colorize`: true # Today's appointments will be colored red, tomorrow's appointments will be orange, this option overrides the option everyCalOneColor
|
|
38
|
+
- `colorize`: true # Today's appointments and appointments which are currently running will be colored red, tomorrow's appointments will be orange, this option overrides the option everyCalOneColor
|
|
39
39
|
- `debug`: false # if true, extended output is written to the CCU.IO log
|
|
40
40
|
- `defColor`:` white` # sets the default color of the calendar entries
|
|
41
41
|
- `fulltime`: ` ` # determines by which string the time 00:00 is replaced for all day appointments. For spaces (between the quotes), the time is omitted for all-day appointments
|
|
@@ -49,7 +49,10 @@ Meaning of the options in the config file:
|
|
|
49
49
|
- `Events`:
|
|
50
50
|
- `name`:" vacation ":
|
|
51
51
|
- `enabled`: true # determines if the event will be edited
|
|
52
|
+
- `Set ID`: An additional state can be entered here, which is updated when the event is active
|
|
53
|
+
- `On / Off`: Here, an alternative value can be written to the state stored under 'Set ID'
|
|
52
54
|
- `display`: false # determines whether the event is also displayed in the iCalEvents, or only evaluated
|
|
55
|
+
- `Set Ack`: false # Ack "off" controls the state, e.g. to switch something. #true Ack "on" updates the value
|
|
53
56
|
|
|
54
57
|
By setting an event (in this example "vacation"), the calendars are searched for the string "vacation".
|
|
55
58
|
If an appointment with the keyword "vacation" is in a calendar, then automatically a state with the
|
|
@@ -57,7 +60,14 @@ Meaning of the options in the config file:
|
|
|
57
60
|
A status is created for each day of the preview period. Danger!
|
|
58
61
|
It is searched for a substring, i. an entry in the calendar "vacation" is recognized as well as a
|
|
59
62
|
Entry "holiday parents". This must be taken into account when setting the events.
|
|
60
|
-
|
|
63
|
+
|
|
64
|
+
- Explanation of the states under ical.0.events.0
|
|
65
|
+
- The event in the path ical.0.events.0.later is set to true if it is still happening today but has not started yet
|
|
66
|
+
- The event in path ical.0.events.0.now is set to true if it is currently active
|
|
67
|
+
- The event in the path ical.0.events.0.today is set to true if the event is active today
|
|
68
|
+
- Note: events from previous days are not displayed
|
|
69
|
+
|
|
70
|
+
|
|
61
71
|
By adjusting the CSS in the VIS, the styles of today's (standard red) and tomorrow's dates (standard orange) can be set:
|
|
62
72
|
- `iCalWarn` - Newline calendar entry today
|
|
63
73
|
- `iCalPreWarn` - beginning of line calendar entry tomorrow
|
|
@@ -74,17 +84,16 @@ To do this, right-click on the calendar in the Calendar app and select Share Set
|
|
|
74
84
|
To include a Google Calendar, you must go to the Google Calendar calendar setting (mouse click on the "down arrow" next to the calendar). The URL of the calendar can be found by clicking on the `ICAL` symbol next to the field" Private address ". Then enter this URL either in the settings at defaultURL, or specify it in `read URL`, eg. `readURL https: // www.google.com / calendar / ical / xxxxxxxx / basic.ics`.
|
|
75
85
|
|
|
76
86
|
#### OwnCloud Calendar
|
|
77
|
-
To include a hardcooked calendar of an OwnCloud, you have to approve this calendar in the calendar view in OwnCloud as a hardcourt calendar and
|
|
87
|
+
To include a hardcooked calendar of an OwnCloud, you have to approve this calendar in the calendar view in OwnCloud as a hardcourt calendar and share the link. This URL (https://<DOMAIN>/remote.php/dav/calendars/USER/xxxxxxx_shared_by_xxxxxx?export) have to be added in the ioBroker.ical adapter with username and password.
|
|
78
88
|
|
|
79
89
|
#### NextCloud Calendar
|
|
80
90
|
To include a NextCloud calendar, the download link of the single desired calendar of a user must be copied in the calendar view in NextCloud.
|
|
81
91
|
To do this, log in to NextCloud as a user and go to 'Calendar'. In the left column, click on the desired calendar by the circle with three dots.
|
|
82
92
|
In the menu that appears hover with the mouse over 'Download' and right click to copy the link.
|
|
83
|
-
Example: https
|
|
93
|
+
Example: https://<DOMAN>/remote.php/dav/calendars/MYCALENDAR/personal/?export (it is important that the link contains "?export").
|
|
84
94
|
|
|
85
95
|
Enter this URL into the ioBroker.ical adapter with username and password. This must be done individually for all desired calendars of all users.
|
|
86
96
|
|
|
87
|
-
|
|
88
97
|
#### Baikal lightweight CalDAV+CardDAV Server
|
|
89
98
|
The Baikal server offers the "ics-export" plugin that allows to export a calendar as a single ICal file. This export plugin is selected with the URL and allows seamless integration with this ioBroker adaptor. Please add the export filter to the URL of your calendar (`https://SERVER/baikal/cal.php/calendars/path/to/calendar?export&accept=ical`). If you encounter authentication issues, please change the `WebDAV authentication type` from `DIGEST` to `BASIC` in the admin settings of the WebUI of the Baikal server.
|
|
90
99
|
|
package/io-package.json
CHANGED
|
@@ -1,8 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"common": {
|
|
3
3
|
"name": "ical",
|
|
4
|
-
"version": "1.12.
|
|
4
|
+
"version": "1.12.2",
|
|
5
5
|
"news": {
|
|
6
|
+
"1.12.2": {
|
|
7
|
+
"en": "Fix displaying rest-time of event in one case",
|
|
8
|
+
"de": "Anzeige der Ruhezeit des Ereignisses in einem Fall behoben",
|
|
9
|
+
"ru": "Исправлено отображение времени отдыха события в одном случае",
|
|
10
|
+
"pt": "Corrigida a exibição do tempo de descanso do evento em um caso",
|
|
11
|
+
"nl": "Repareer de weergave van de rusttijd van de gebeurtenis in één geval",
|
|
12
|
+
"fr": "Correction de l'affichage du temps de repos de l'événement dans un cas",
|
|
13
|
+
"it": "Risolto il problema con la visualizzazione del tempo di riposo dell'evento in un caso",
|
|
14
|
+
"es": "Corrección que muestra el tiempo de descanso del evento en un caso",
|
|
15
|
+
"pl": "Naprawiono wyświetlanie czasu spoczynku zdarzenia w jednym przypadku",
|
|
16
|
+
"zh-cn": "修复在一种情况下显示事件的休息时间"
|
|
17
|
+
},
|
|
6
18
|
"1.12.1": {
|
|
7
19
|
"en": "Adjust colorize of dates to also show dates started in the past with todays color",
|
|
8
20
|
"de": "Passen Sie die Farbgebung von Daten an, um auch in der Vergangenheit begonnene Daten in der heutigen Farbe anzuzeigen",
|
|
@@ -74,18 +86,6 @@
|
|
|
74
86
|
"es": "->",
|
|
75
87
|
"pl": "->",
|
|
76
88
|
"zh-cn": "->"
|
|
77
|
-
},
|
|
78
|
-
"1.11.2": {
|
|
79
|
-
"en": "Change one logline to debug",
|
|
80
|
-
"de": "Ändern Sie eine Protokollzeile in Debug",
|
|
81
|
-
"ru": "Измените одну строку журнала для отладки",
|
|
82
|
-
"pt": "Alterar uma linha de log para depurar",
|
|
83
|
-
"nl": "Eén loglijn wijzigen om te debuggen",
|
|
84
|
-
"fr": "Changer une ligne de connexion pour déboguer",
|
|
85
|
-
"it": "Cambia una logline in debug",
|
|
86
|
-
"es": "Cambiar un logline para depurar",
|
|
87
|
-
"pl": "Zmień jeden logline na debugowanie",
|
|
88
|
-
"zh-cn": "更改一个日志行以进行调试"
|
|
89
89
|
}
|
|
90
90
|
},
|
|
91
91
|
"title": "iCal Calendar",
|
package/main.js
CHANGED
|
@@ -1239,7 +1239,7 @@ function formatDate(_date, _end, withTime, fullDay) {
|
|
|
1239
1239
|
} else {
|
|
1240
1240
|
// check if date is in the past and if so we show the end time instead
|
|
1241
1241
|
_class = 'ical_today';
|
|
1242
|
-
const dateDiff = (treatAsUTC(_end.getTime()) - Date.now());
|
|
1242
|
+
const dateDiff = (treatAsUTC(_end.getTime()) - treatAsUTC(Date.now()));
|
|
1243
1243
|
let daysleft = Math.round( dateDiff/ (1000 * 60 * 60 * 24));
|
|
1244
1244
|
const hoursleft = Math.round(dateDiff / (1000 * 60 * 60));
|
|
1245
1245
|
const minutesleft = Math.round(dateDiff / (1000 * 60));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "iobroker.ical",
|
|
3
|
-
"version": "1.12.
|
|
3
|
+
"version": "1.12.2",
|
|
4
4
|
"description": "Allows read information from google calender and from iCal.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "bluefox",
|
|
@@ -37,19 +37,18 @@
|
|
|
37
37
|
"cloneextend": "^0.0.3",
|
|
38
38
|
"request": "^2.88.2",
|
|
39
39
|
"json-schema": "^0.4.0",
|
|
40
|
-
"rrule": "2.6.
|
|
40
|
+
"rrule": "2.6.9"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
|
-
"@alcalzone/release-script": "^3.5.
|
|
44
|
-
"@alcalzone/release-script-plugin-iobroker": "^3.5.
|
|
45
|
-
"@alcalzone/release-script-plugin-license": "^3.5.
|
|
46
|
-
"@iobroker/testing": "^2.
|
|
47
|
-
"
|
|
43
|
+
"@alcalzone/release-script": "^3.5.9",
|
|
44
|
+
"@alcalzone/release-script-plugin-iobroker": "^3.5.9",
|
|
45
|
+
"@alcalzone/release-script-plugin-license": "^3.5.9",
|
|
46
|
+
"@iobroker/testing": "^2.6.0",
|
|
47
|
+
"@iobroker/adapter-dev": "^1.0.0",
|
|
48
48
|
"chai": "^4.3.6",
|
|
49
49
|
"chai-string": "^1.5.0",
|
|
50
|
-
"eslint": "^8.
|
|
51
|
-
"
|
|
52
|
-
"mocha": "^9.2.2",
|
|
50
|
+
"eslint": "^8.16.0",
|
|
51
|
+
"mocha": "^10.0.0",
|
|
53
52
|
"set-value": "^4.1.0",
|
|
54
53
|
"ansi-regex": "^6.0.1"
|
|
55
54
|
},
|
|
@@ -64,7 +63,8 @@
|
|
|
64
63
|
"test:integration": "mocha test/integration --exit",
|
|
65
64
|
"test": "npm run test:js && npm run test:package",
|
|
66
65
|
"lint": "eslint",
|
|
67
|
-
"release": "release-script"
|
|
66
|
+
"release": "release-script",
|
|
67
|
+
"translate": "translate-adapter"
|
|
68
68
|
},
|
|
69
69
|
"license": "MIT"
|
|
70
70
|
}
|
package/lib/tools.js
DELETED
|
@@ -1,99 +0,0 @@
|
|
|
1
|
-
const axios = require('axios').default;
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Tests whether the given variable is a real object and not an Array
|
|
5
|
-
* @param {any} it The variable to test
|
|
6
|
-
* @returns {it is Record<string, any>}
|
|
7
|
-
*/
|
|
8
|
-
function isObject(it) {
|
|
9
|
-
// This is necessary because:
|
|
10
|
-
// typeof null === 'object'
|
|
11
|
-
// typeof [] === 'object'
|
|
12
|
-
// [] instanceof Object === true
|
|
13
|
-
return Object.prototype.toString.call(it) === '[object Object]';
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* Tests whether the given variable is really an Array
|
|
18
|
-
* @param {any} it The variable to test
|
|
19
|
-
* @returns {it is any[]}
|
|
20
|
-
*/
|
|
21
|
-
function isArray(it) {
|
|
22
|
-
if (typeof Array.isArray === 'function') return Array.isArray(it);
|
|
23
|
-
return Object.prototype.toString.call(it) === '[object Array]';
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* Translates text to the target language. Automatically chooses the right translation API.
|
|
28
|
-
* @param {string} text The text to translate
|
|
29
|
-
* @param {string} targetLang The target languate
|
|
30
|
-
* @param {string} [yandexApiKey] The yandex API key. You can create one for free at https://translate.yandex.com/developers
|
|
31
|
-
* @returns {Promise<string>}
|
|
32
|
-
*/
|
|
33
|
-
async function translateText(text, targetLang, yandexApiKey) {
|
|
34
|
-
if (targetLang === 'en') {
|
|
35
|
-
return text;
|
|
36
|
-
} else if (!text) {
|
|
37
|
-
return '';
|
|
38
|
-
}
|
|
39
|
-
if (yandexApiKey) {
|
|
40
|
-
return translateYandex(text, targetLang, yandexApiKey);
|
|
41
|
-
} else {
|
|
42
|
-
return translateGoogle(text, targetLang);
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
/**
|
|
47
|
-
* Translates text with Yandex API
|
|
48
|
-
* @param {string} text The text to translate
|
|
49
|
-
* @param {string} targetLang The target languate
|
|
50
|
-
* @param {string} apiKey The yandex API key. You can create one for free at https://translate.yandex.com/developers
|
|
51
|
-
* @returns {Promise<string>}
|
|
52
|
-
*/
|
|
53
|
-
async function translateYandex(text, targetLang, apiKey) {
|
|
54
|
-
if (targetLang === 'zh-cn') {
|
|
55
|
-
targetLang = 'zh';
|
|
56
|
-
}
|
|
57
|
-
try {
|
|
58
|
-
const url = `https://translate.yandex.net/api/v1.5/tr.json/translate?key=${apiKey}&text=${encodeURIComponent(text)}&lang=en-${targetLang}`;
|
|
59
|
-
const response = await axios({url, timeout: 15000});
|
|
60
|
-
if (response.data && response.data.text && isArray(response.data.text)) {
|
|
61
|
-
return response.data.text[0];
|
|
62
|
-
}
|
|
63
|
-
throw new Error('Invalid response for translate request');
|
|
64
|
-
} catch (e) {
|
|
65
|
-
throw new Error(`Could not translate to "${targetLang}": ${e}`);
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
/**
|
|
70
|
-
* Translates text with Google API
|
|
71
|
-
* @param {string} text The text to translate
|
|
72
|
-
* @param {string} targetLang The target languate
|
|
73
|
-
* @returns {Promise<string>}
|
|
74
|
-
*/
|
|
75
|
-
async function translateGoogle(text, targetLang) {
|
|
76
|
-
try {
|
|
77
|
-
const url = `http://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=${targetLang}&dt=t&q=${encodeURIComponent(text)}&ie=UTF-8&oe=UTF-8`;
|
|
78
|
-
const response = await axios({url, timeout: 15000});
|
|
79
|
-
if (isArray(response.data)) {
|
|
80
|
-
// we got a valid response
|
|
81
|
-
return response.data[0][0][0];
|
|
82
|
-
}
|
|
83
|
-
throw new Error('Invalid response for translate request');
|
|
84
|
-
} catch (e) {
|
|
85
|
-
if (e.response && e.response.status === 429) {
|
|
86
|
-
throw new Error(
|
|
87
|
-
`Could not translate to "${targetLang}": Rate-limited by Google Translate`
|
|
88
|
-
);
|
|
89
|
-
} else {
|
|
90
|
-
throw new Error(`Could not translate to "${targetLang}": ${e}`);
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
module.exports = {
|
|
96
|
-
isArray,
|
|
97
|
-
isObject,
|
|
98
|
-
translateText
|
|
99
|
-
};
|