Files
epg/scripts/commands/create-database.js

76 lines
2.0 KiB
JavaScript
Raw Normal View History

2022-01-06 12:59:37 +03:00
const { db, file, parser, logger } = require('../core')
const { program } = require('commander')
const _ = require('lodash')
const options = program
.option(
'--max-clusters <max-clusters>',
'Set maximum number of clusters',
parser.parseNumber,
2022-01-15 02:01:37 +03:00
256
2022-01-06 12:59:37 +03:00
)
.option('--channels <channels>', 'Set path to channels.xml file', 'sites/**/*.channels.xml')
.parse(process.argv)
.opts()
async function main() {
logger.info('Starting...')
logger.info(`Number of clusters: ${options.maxClusters}`)
2022-01-21 17:00:04 +03:00
await saveToDatabase(await getChannels())
2022-01-06 12:59:37 +03:00
logger.info('Done')
}
main()
2022-01-21 17:00:04 +03:00
async function getChannels() {
2022-01-06 12:59:37 +03:00
logger.info(`Loading channels...`)
2022-01-21 17:00:04 +03:00
const channels = []
2022-01-06 12:59:37 +03:00
const files = await file.list(options.channels)
for (const filepath of files) {
2022-01-06 16:01:23 +03:00
const dir = file.dirname(filepath)
2022-01-12 13:27:27 +03:00
const filename = file.basename(filepath)
2022-01-20 23:20:57 +03:00
const [_, site] = filename.match(/([a-z0-9-.]+)_/i) || [null, null]
if (!site) continue
const configPath = `${dir}/${site}.config.js`
const config = require(file.resolve(configPath))
if (config.ignore) continue
const [__, gid] = filename.match(/_([a-z-]+)\.channels\.xml/i) || [null, null]
2022-01-06 12:59:37 +03:00
const items = await parser.parseChannels(filepath)
for (const item of items) {
2022-01-14 16:41:04 +03:00
const countryCode = item.xmltv_id.split('.')[1]
item.country = countryCode ? countryCode.toUpperCase() : null
2022-01-06 16:01:23 +03:00
item.channelsPath = filepath
2022-01-20 23:20:57 +03:00
item.configPath = configPath
2022-01-14 17:29:21 +03:00
item.gid = gid
2022-01-06 12:59:37 +03:00
channels.push(item)
}
}
logger.info(`Found ${channels.length} channels`)
2022-01-21 17:00:04 +03:00
return channels
2022-01-06 12:59:37 +03:00
}
2022-01-21 17:00:04 +03:00
async function saveToDatabase(channels = []) {
2022-01-06 12:59:37 +03:00
logger.info('Saving to the database...')
2022-01-15 18:21:41 +03:00
await db.channels.load()
2022-01-09 18:15:38 +03:00
await db.channels.reset()
2022-01-06 12:59:37 +03:00
const chunks = split(_.shuffle(channels), options.maxClusters)
for (const [i, chunk] of chunks.entries()) {
for (const item of chunk) {
item.cluster_id = i + 1
2022-01-09 18:15:38 +03:00
await db.channels.insert(item)
2022-01-06 12:59:37 +03:00
}
}
}
function split(arr, n) {
let result = []
for (let i = n; i > 0; i--) {
result.push(arr.splice(0, Math.ceil(arr.length / i)))
}
return result
}