Skip to content

Instantly share code, notes, and snippets.

@shombando
Forked from kebot/gen-epub.ts
Last active September 15, 2023 17:11
Show Gist options
  • Save shombando/87a58583f02bb543b0a98bb24f813039 to your computer and use it in GitHub Desktop.
Save shombando/87a58583f02bb543b0a98bb24f813039 to your computer and use it in GitHub Desktop.
Generate Epub for Omnivore Articles
// get a list of articles based on search endpoint
import { gql, GraphQLClient } from 'npm:graphql-request'
import sanitizeHtml from 'npm:sanitize-html'
import epub, { Chapter } from 'npm:epub-gen-memory'
const OMNIVORE_API_KEY = ''
const OMNIVORE_ENDPOINT = 'https://api-prod.omnivore.app/api/graphql'
const graphQLClient = new GraphQLClient(OMNIVORE_ENDPOINT, {
headers: {
authorization: OMNIVORE_API_KEY
}
})
async function getUnreadArticles () {
const query = gql`
{
articles {
... on ArticlesSuccess {
edges {
cursor,
node {
title
slug
description
url
savedAt
language
subscription
isArchived
author
}
}
}
}
}
`
type Edge = {
cursor: string,
node: {
title: string,
slug: string,
url: string
savedAt: string
language: string
subscription: string
isArchived: boolean
author: string
}
}
const data = await graphQLClient.request<{articles: { edges: Edge[] }}>(query)
return data.articles.edges.map(e => e.node)
}
async function getArticle (slug: string) {
const query = gql`{
article (username: "K.Y.", slug: "${slug}") {
... on ArticleSuccess {
article {
id, slug, url, content
}
}
}
}`
const data = await graphQLClient.request<{
article: {
article: {
id: string,
slug: string,
url: string,
content: string
}
}
}>(query)
const sanitizedArticle = sanitizeHtml(data.article.article.content)
return {
...data.article.article,
content: sanitizedArticle
}
}
// mark sended
async function makeMagazine () {
console.log('〰️ getting article list')
const articles = await getUnreadArticles()
console.log('🤖 done')
const chapters: Chapter[] = []
for (const article of articles) {
if (!article.isArchived) {
console.log(`fetching ${article.title}`)
const content = (await getArticle(article.slug)).content
chapters.push({
title: article.title !== null ? article.title : "N/A",
author: article.author !== null ? article.author : "N/A",
content,
url: article.url !== null ? article.url : "N/A"
})
console.log(`✅ done`)
}
}
// make a PDF and save it
const fileBuffer = await epub.default({
title: 'Test Articles',
author: 'Omnivore',
// cover: article.image,
}, chapters)
await Deno.writeFile('./output.epub', fileBuffer)
console.log('📚 Success')
}
await makeMagazine()
Deno.exit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment