From dbd9221931ddffa0f205398cb54af046d9759d5a Mon Sep 17 00:00:00 2001 From: Alexander Borsuk Date: Fri, 5 May 2023 00:49:32 +0200 Subject: [PATCH] Fixed improperly encoded windows-1251 names when sharing bookmarks in vk Signed-off-by: Alexander Borsuk --- src/ge0.ts | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/ge0.ts b/src/ge0.ts index 2bc313b..c227494 100644 --- a/src/ge0.ts +++ b/src/ge0.ts @@ -9,10 +9,34 @@ function replaceInTemplate(template: string, data: Record) { return template.replace(pattern, (_, token) => data[token] || ''); } +function fromWindows1251(percentEncoded: string) { + const decoder = new TextDecoder('windows-1251', { fatal: true, ignoreBOM: false }); + // https://stackoverflow.com/a/69769015 + return percentEncoded.replace( + /(?:%[0-9A-F]{2})+/g, + // @ts-expect-error JS allows typed arrays from string arrays, but TS doesn't know that. + (s) => decoder.decode(Uint8Array.from(s.replaceAll('%', ',0x').slice(1).split(','))), + ); +} + function normalizeNameAndTitle(name: string | undefined): [string, string] { let title = 'Organic Maps'; if (name) { - name = decodeURIComponent(name.replace(/\+|_/g, ' ')); + name = name.replace(/\+|_/g, ' '); // Convert underscores back to spaces. + try { + name = decodeURIComponent(name); + } catch (ex: any) { + try { + // There are some cases when coordinates are correct, but the name is not encoded properly, for example: + // %DF%F0%EA%EE%E2%F1%EA%EE%E5_%F3%F7%E0%F1%F2%EA%EE%E2%EE%E5_%EB%E5%F1%ED%E8%F7%E5%F1%F2%E2%EE + // %C8%EB%EE%E2%E0%E9%F1%EA%EE%E5_%F3%F7%E0%F1%F2%EA%EE%E2%EE%E5_%EB%E5%F1%ED%E8%F7%E5%F1%F2%E2%EE + // Looks like vk.com incorrectly uses Windows-1251 to encode some shared links when querying previews. + name = fromWindows1251(name); + } catch (ex: any) { + name = '😃'; + } + } + name = name.replace("'", '’'); // To embed in popup. title = name + ' | ' + title; } else {