Fix images in Medium

This commit is contained in:
Thomas Rogers 2024-11-22 17:42:05 +01:00
parent c27af0141e
commit 7bebb45400

View file

@ -13,6 +13,37 @@ export class MediumHandler extends ContentHandler {
return u.hostname.endsWith('medium.com')
}
addImages(document: Document): Document {
const pictures = document.querySelectorAll('picture')
pictures.forEach((pict) => {
const source = pict.querySelector('source')
if (source) {
const srcSet = source.getAttribute('srcSet')
const sources = (srcSet || '')
.split(', ')
.map((src) => src.split(' '))
.sort((a, b) =>
Number(a[1].replace('w', '')) > Number(b[1].replace('w', ''))
? -1
: 1
)
// This should be the largest image in the source set.
if (sources && sources.length && Array.isArray(sources[0])) {
const url = sources[0][0]
const img = document.createElement('img')
img.src = url
pict.after(img)
pict.remove()
}
}
})
return document
}
async preHandle(url: string): Promise<PreHandleResult> {
console.log('prehandling medium url', url)
@ -22,9 +53,10 @@ export class MediumHandler extends ContentHandler {
const response = await axios.get(res.toString())
const dom = parseHTML(response.data).document
const imageAddedDom = this.addImages(dom)
return {
title: dom.title,
content: response.data as string,
content: imageAddedDom.body.outerHTML,
url: res.toString(),
}
} catch (error) {