1
0
mirror of https://github.com/comatory/fb2iCal synced 2024-12-28 17:30:51 +01:00
Facebook-Events-iCal-Converter/lib/parser.js

95 lines
2.1 KiB
JavaScript
Raw Normal View History

2019-10-15 22:45:03 +02:00
const dayjs = require('dayjs')
const cheerio = require('cheerio')
2019-10-15 09:22:08 +02:00
2019-10-17 22:14:08 +02:00
// NOTE: Specific formatting for `ics` library
const parseDates = (startDate, endDate) => {
2019-10-17 22:14:08 +02:00
const start = startDate ? [
startDate.year(),
startDate.month() + 1,
startDate.date(),
startDate.hour(),
startDate.minute(),
2019-10-17 22:14:08 +02:00
] : (() => {
const now = dayjs()
return [
now.year(),
now.month() + 1,
now.date()
]
})()
const diffInMinutes = endDate ?
endDate.diff(startDate, 'minutes') :
120
const duration = { minutes: diffInMinutes }
2019-10-15 09:22:08 +02:00
return {
start,
duration,
2019-10-15 22:45:03 +02:00
}
}
2019-10-15 22:45:03 +02:00
const parseEventData = (eventData) => {
const startDate = eventData.startDate && dayjs(eventData.startDate)
const endDate = eventData.endDate && dayjs(eventData.endDate)
const { start, duration } = parseDates(startDate, endDate)
const { location } = eventData || {}
const { address } = location || {}
2019-10-15 22:45:03 +02:00
2019-10-17 22:14:08 +02:00
const locationStr = location ? [
location.name || '',
address.streetAddress || '',
address.addressLocality || '',
address.postalCode || '',
address.addressCountry || '',
2019-10-17 22:14:08 +02:00
].join(' ') : ''
const cleanedLocationStr = locationStr.replace(/\r?\n|\r/g, ' ')
const title = eventData.name || ''
const url = eventData.url || ''
const description = eventData.description || ''
2019-10-15 22:45:03 +02:00
return {
start,
duration,
2019-10-17 22:14:08 +02:00
location: cleanedLocationStr,
title,
url,
description,
}
}
2019-10-15 22:45:03 +02:00
const parseHTML = (html) => {
try {
// NOTE: Mobile web should have serialized
// event info in one of the script tags
const $ = cheerio.load(html)
const $scripts = $('head script[type="application/ld+json"]')
const rawData = $scripts.toArray().reduce((data, node) => {
const firstNode = node.children[0]
2019-10-15 22:45:03 +02:00
if (!firstNode || !firstNode.data) {
return data
}
2019-10-15 22:45:03 +02:00
if (firstNode.data.startsWith('//<![CDATA')) {
return firstNode.data
}
2019-10-15 22:45:03 +02:00
return data
}, null)
2019-10-15 22:45:03 +02:00
2019-10-17 22:14:08 +02:00
const eventData = rawData ?
JSON.parse(rawData.slice(12, -5)) :
{}
const data = parseEventData(eventData)
2019-10-15 22:45:03 +02:00
return data
} catch (err) {
throw err
return
2019-10-15 09:22:08 +02:00
}
}
module.exports = parseHTML