Update scripts

This commit is contained in:
freearhey 2023-10-02 06:31:57 +03:00
parent b7214db4fb
commit ca254a6df0
37 changed files with 1091 additions and 915 deletions

1
scripts/commands/channels/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/replace.ts

View file

@ -1,160 +0,0 @@
const { api, parser, xml, file, logger } = require('../../core')
const { transliterate } = require('transliteration')
const nodeCleanup = require('node-cleanup')
const { program } = require('commander')
const inquirer = require('inquirer')
program
.argument('<filepath>', 'Path to *.channels.xml file to edit')
.option('-c, --country <name>', 'Source country', 'us')
.parse(process.argv)
const filepath = program.args[0]
const options = program.opts()
const defaultCountry = options.country
const newLabel = ` [new]`
let site
let channels = []
async function main() {
if (!(await file.exists(filepath))) {
throw new Error(`File "${filepath}" does not exists`)
return
}
let result = await parser.parseChannels(filepath)
site = result.site
channels = result.channels
channels = channels.map(c => {
c.xmltv_id = c.xmltv_id
return c
})
await api.channels.load()
const buffer = []
for (const channel of channels) {
if (channel.xmltv_id) {
if (channel.xmltv_id !== '-') {
buffer.push(`${channel.xmltv_id}/${channel.lang}`)
}
continue
}
let choices = await getOptions(channel)
const question = {
name: 'option',
message: `Choose an option:`,
type: 'list',
choices,
pageSize: 10
}
await inquirer.prompt(question).then(async selected => {
switch (selected.option) {
case 'Overwrite':
const input = await getInput(channel)
channel.xmltv_id = input.xmltv_id
break
case 'Skip':
channel.xmltv_id = '-'
break
default:
const [name, xmltv_id] = selected.option
.replace(/ \[.*\]/, '')
.split('|')
.map(i => i.trim().replace(newLabel, ''))
channel.xmltv_id = xmltv_id
break
}
const found = buffer.includes(`${channel.xmltv_id}/${channel.lang}`)
if (found) {
const question = {
name: 'option',
message: `"${channel.xmltv_id}" already on the list. Choose an option:`,
type: 'list',
choices: ['Skip', 'Add', 'Delete'],
pageSize: 5
}
await inquirer.prompt(question).then(async selected => {
switch (selected.option) {
case 'Skip':
channel.xmltv_id = '-'
break
case 'Delete':
channel.delete = true
break
default:
break
}
})
} else {
if (channel.xmltv_id !== '-') {
buffer.push(`${channel.xmltv_id}/${channel.lang}`)
}
}
})
}
}
main()
function save() {
if (!file.existsSync(filepath)) return
channels = channels.filter(c => !c.delete)
const output = xml.create(channels, site)
file.writeSync(filepath, output)
logger.info(`\nFile '${filepath}' successfully saved`)
}
nodeCleanup(() => {
save()
})
async function getInput(channel) {
const name = channel.name.trim()
const input = await inquirer.prompt([
{
name: 'xmltv_id',
message: ' ID:',
type: 'input',
default: generateCode(name, defaultCountry)
}
])
return { name, xmltv_id: input['xmltv_id'] }
}
async function getOptions(channel) {
const channels = await api.channels.all()
const channelId = generateCode(channel.name, defaultCountry)
const similar = await getSimilar(channels, channelId)
let variants = []
variants.push(`${channel.name.trim()} | ${channelId}${newLabel}`)
similar.forEach(i => {
let alt_names = i.alt_names.length ? ` (${i.alt_names.join(',')})` : ''
let closed = i.closed ? `[closed:${i.closed}]` : ``
let replaced_by = i.replaced_by ? `[replaced_by:${i.replaced_by}]` : ''
variants.push(`${i.name}${alt_names} | ${i.id} ${closed}${replaced_by}[api]`)
})
variants.push(`Overwrite`)
variants.push(`Skip`)
return variants
}
async function getSimilar(list, channelId) {
const normChannelId = channelId.split('.')[0].slice(0, 8).toLowerCase()
return list.filter(i => i.id.split('.')[0].toLowerCase().startsWith(normChannelId))
}
function generateCode(name, country) {
const id = transliterate(name)
.replace(/\+/gi, 'Plus')
.replace(/^\&/gi, 'And')
.replace(/[^a-z\d]+/gi, '')
return `${id}.${country}`
}

View file

@ -0,0 +1,181 @@
import { DATA_DIR } from '../../constants'
import { Storage, Collection, Dictionary, Logger } from '@freearhey/core'
import { ChannelsParser, XML, ApiChannel } from '../../core'
import { Channel } from 'epg-grabber'
import { transliterate } from 'transliteration'
import nodeCleanup from 'node-cleanup'
import { program } from 'commander'
import inquirer, { QuestionCollection } from 'inquirer'
program
.argument('<filepath>', 'Path to *.channels.xml file to edit')
.option('-c, --country <name>', 'Source country', 'us')
.parse(process.argv)
const filepath = program.args[0]
const programOptions = program.opts()
const defaultCountry = programOptions.country
const newLabel = ` [new]`
let site: string
let options = new Collection()
async function main() {
const storage = new Storage()
if (!(await storage.exists(filepath))) {
throw new Error(`File "${filepath}" does not exists`)
}
const parser = new ChannelsParser({ storage })
const parsedChannels = await parser.parse(filepath)
options = parsedChannels.map((channel: Channel) => {
return {
channel,
delete: false
}
})
const dataStorage = new Storage(DATA_DIR)
const channelsContent = await dataStorage.json('channels.json')
const channels = new Collection(channelsContent).map(data => new ApiChannel(data))
const buffer = new Dictionary()
options.forEach(async (option: { channel: Channel; delete: boolean }) => {
const channel = option.channel
if (channel.xmltv_id) {
if (channel.xmltv_id !== '-') {
buffer.set(`${channel.xmltv_id}/${channel.lang}`, true)
}
return
}
let choices = getOptions(channels, channel)
const question: QuestionCollection = {
name: 'option',
message: `Choose an option:`,
type: 'list',
choices,
pageSize: 10
}
await inquirer.prompt(question).then(async selected => {
switch (selected.option) {
case 'Overwrite':
const input = await getInput(channel)
channel.xmltv_id = input.xmltv_id
break
case 'Skip':
channel.xmltv_id = '-'
break
default:
const [, xmltv_id] = selected.option
.replace(/ \[.*\]/, '')
.split('|')
.map((i: string) => i.trim().replace(newLabel, ''))
channel.xmltv_id = xmltv_id
break
}
const found = buffer.has(`${channel.xmltv_id}/${channel.lang}`)
if (found) {
const question: QuestionCollection = {
name: 'option',
message: `"${channel.xmltv_id}" already on the list. Choose an option:`,
type: 'list',
choices: ['Skip', 'Add', 'Delete'],
pageSize: 5
}
await inquirer.prompt(question).then(async selected => {
switch (selected.option) {
case 'Skip':
channel.xmltv_id = '-'
break
case 'Delete':
option.delete = true
break
default:
break
}
})
} else {
if (channel.xmltv_id !== '-') {
buffer.set(`${channel.xmltv_id}/${channel.lang}`, true)
}
}
})
})
}
main()
function save() {
const logger = new Logger()
const storage = new Storage()
if (!storage.existsSync(filepath)) return
const channels = options
.filter((option: { channel: Channel; delete: boolean }) => !option.delete)
.map((option: { channel: Channel; delete: boolean }) => option.channel)
const xml = new XML(channels, site)
storage.saveSync(filepath, xml.toString())
logger.info(`\nFile '${filepath}' successfully saved`)
}
nodeCleanup(() => {
save()
})
async function getInput(channel: Channel) {
const name = channel.name.trim()
const input = await inquirer.prompt([
{
name: 'xmltv_id',
message: ' ID:',
type: 'input',
default: generateCode(name, defaultCountry)
}
])
return { name, xmltv_id: input['xmltv_id'] }
}
function getOptions(channels: Collection, channel: Channel) {
const channelId = generateCode(channel.name, defaultCountry)
const similar = getSimilar(channels, channelId)
const variants = new Collection()
variants.add(`${channel.name.trim()} | ${channelId}${newLabel}`)
similar.forEach((_channel: ApiChannel) => {
const altNames = _channel.altNames.notEmpty() ? ` (${_channel.altNames.join(',')})` : ''
const closed = _channel.closed ? `[closed:${_channel.closed}]` : ``
const replacedBy = _channel.replacedBy ? `[replaced_by:${_channel.replacedBy}]` : ''
variants.add(`${_channel.name}${altNames} | ${_channel.id} ${closed}${replacedBy}[api]`)
})
variants.add(`Overwrite`)
variants.add(`Skip`)
return variants.all()
}
function getSimilar(channels: Collection, channelId: string) {
const normChannelId = channelId.split('.')[0].slice(0, 8).toLowerCase()
return channels.filter((channel: ApiChannel) =>
channel.id.split('.')[0].toLowerCase().startsWith(normChannelId)
)
}
function generateCode(name: string, country: string) {
const channelId: string = transliterate(name)
.replace(/\+/gi, 'Plus')
.replace(/^\&/gi, 'And')
.replace(/[^a-z\d]+/gi, '')
return `${channelId}.${country}`
}

View file

@ -1,18 +1,10 @@
const chalk = require('chalk')
const libxml = require('libxmljs2')
const { program } = require('commander')
const { logger, file } = require('../../core')
import chalk from 'chalk'
import libxml, { ValidationError } from 'libxmljs2'
import { program } from 'commander'
import { Logger, Storage, File } from '@freearhey/core'
const xsd = `<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:element name="site">
<xs:complexType>
<xs:sequence>
<xs:element ref="channels"/>
</xs:sequence>
<xs:attribute name="site" use="required" type="xs:string"/>
</xs:complexType>
</xs:element>
<xs:element name="channels">
<xs:complexType>
<xs:sequence>
@ -22,43 +14,53 @@ const xsd = `<?xml version="1.0" encoding="UTF-8"?>
</xs:element>
<xs:element name="channel">
<xs:complexType mixed="true">
<xs:attribute name="site" use="required" type="xs:string"/>
<xs:attribute name="lang" use="required" type="xs:string"/>
<xs:attribute name="site_id" use="required" type="xs:string"/>
<xs:attribute name="xmltv_id" use="required" type="xs:string"/>
<xs:attribute name="logo" type="xs:string"/>
</xs:complexType>
</xs:element>
</xs:schema>`
program.argument('<filepath>', 'Path to file to validate').parse(process.argv)
program
.option(
'-c, --channels <path>',
'Path to channels.xml file to validate',
'sites/**/*.channels.xml'
)
.parse(process.argv)
const options = program.opts()
async function main() {
if (!program.args.length) {
logger.error('required argument "filepath" not specified')
}
const logger = new Logger()
const storage = new Storage()
let errors = []
logger.info('options:')
logger.tree(options)
for (const filepath of program.args) {
if (!filepath.endsWith('.xml')) continue
let errors: ValidationError[] = []
const xml = await file.read(filepath)
let files: string[] = await storage.list(options.channels)
for (const filepath of files) {
const file = new File(filepath)
if (file.extension() !== 'xml') continue
let localErrors = []
const xml = await storage.load(filepath)
try {
const xsdDoc = libxml.parseXml(xsd)
const doc = libxml.parseXml(xml)
let localErrors: ValidationError[] = []
if (!doc.validate(xsdDoc)) {
localErrors = doc.validationErrors
}
} catch (error) {
localErrors.push(error)
const xsdDoc = libxml.parseXml(xsd)
const doc = libxml.parseXml(xml)
if (!doc.validate(xsdDoc)) {
localErrors = doc.validationErrors
}
if (localErrors.length) {
console.log(`\n${chalk.underline(filepath)}`)
localErrors.forEach(error => {
localErrors.forEach((error: ValidationError) => {
const position = `${error.line}:${error.column}`
console.log(` ${chalk.gray(position.padEnd(4, ' '))} ${error.message.trim()}`)
})

View file

@ -1,65 +0,0 @@
const { logger, file, xml, parser } = require('../../core')
const { Command } = require('commander')
const path = require('path')
const _ = require('lodash')
const program = new Command()
program
.requiredOption('-c, --config <config>', 'Config file')
.option('-s, --set [args...]', 'Set custom arguments', [])
.option('-o, --output <output>', 'Output file')
.option('--clean', 'Delete the previous *.channels.xml if exists')
.parse(process.argv)
const options = program.opts()
async function main() {
const config = require(path.resolve(options.config))
const dir = file.dirname(options.config)
const outputFilepath = options.output || `${dir}/${config.site}.channels.xml`
let channels = []
if (!options.clean && (await file.exists(outputFilepath))) {
let result = await parser.parseChannels(outputFilepath)
channels = result.channels
}
const args = {}
options.set.forEach(arg => {
const [key, value] = arg.split(':')
args[key] = value
})
let parsedChannels = config.channels(args)
if (isPromise(parsedChannels)) {
parsedChannels = await parsedChannels
}
parsedChannels = parsedChannels.map(c => {
c.lang = c.lang || 'en'
return c
})
channels = channels.concat(parsedChannels)
channels = _.uniqBy(channels, c => c.site_id + c.lang)
channels = _.sortBy(channels, [
'lang',
c => (c.xmltv_id ? c.xmltv_id.toLowerCase() : '_'),
'site_id'
])
const output = xml.create(channels, config.site)
await file.write(outputFilepath, output)
logger.info(`File '${outputFilepath}' successfully saved`)
}
main()
function isPromise(promise) {
return !!promise && typeof promise.then === 'function'
}

View file

@ -0,0 +1,76 @@
import { Logger, File, Collection, Storage } from '@freearhey/core'
import { ChannelsParser, XML } from '../../core'
import { Channel } from 'epg-grabber'
import { Command, OptionValues } from 'commander'
import path from 'path'
const program = new Command()
program
.requiredOption('-c, --config <config>', 'Config file')
.option('-s, --set [args...]', 'Set custom arguments')
.option('-o, --output <output>', 'Output file')
.option('--clean', 'Delete the previous *.channels.xml if exists')
.parse(process.argv)
type ParseOptions = {
config: string
set?: string
output?: string
clean?: boolean
}
const options: ParseOptions = program.opts()
async function main() {
const storage = new Storage()
const parser = new ChannelsParser({ storage })
const logger = new Logger()
const file = new File(options.config)
const dir = file.dirname()
const config = require(path.resolve(options.config))
const outputFilepath = options.output || `${dir}/${config.site}.channels.xml`
let channels = new Collection()
if (!options.clean && (await storage.exists(outputFilepath))) {
channels = await parser.parse(outputFilepath)
}
const args: {
[key: string]: any
} = {}
if (Array.isArray(options.set)) {
options.set.forEach((arg: string) => {
const [key, value] = arg.split(':')
args[key] = value
})
}
let parsedChannels = config.channels(args)
if (isPromise(parsedChannels)) {
parsedChannels = await parsedChannels
}
channels = channels
.mergeBy(
new Collection(parsedChannels),
(channel: Channel) => channel.site_id.toString() + channel.lang
)
.orderBy([
(channel: Channel) => channel.lang,
(channel: Channel) => (channel.xmltv_id ? channel.xmltv_id.toLowerCase() : '_'),
(channel: Channel) => channel.site_id
])
const xml = new XML(channels, config.site)
await storage.save(outputFilepath, xml.toString())
logger.info(`File '${outputFilepath}' successfully saved`)
}
main()
function isPromise(promise: any) {
return !!promise && typeof promise.then === 'function'
}

View file

@ -1,68 +0,0 @@
const { parser, logger, api } = require('../../core')
const { program } = require('commander')
const chalk = require('chalk')
const langs = require('langs')
program.argument('<filepath>', 'Path to file to validate').parse(process.argv)
async function main() {
await api.channels.load()
const stats = {
files: 0,
errors: 0
}
if (!program.args.length) {
logger.error('required argument "filepath" not specified')
}
for (const filepath of program.args) {
if (!filepath.endsWith('.xml')) continue
const { site, channels } = await parser.parseChannels(filepath)
const bufferById = {}
const bufferBySiteId = {}
const errors = []
for (const channel of channels) {
if (!bufferById[channel.xmltv_id + channel.lang]) {
bufferById[channel.xmltv_id + channel.lang] = channel
} else {
errors.push({ type: 'duplicate', ...channel })
stats.errors++
}
if (!bufferBySiteId[channel.site_id + channel.lang]) {
bufferBySiteId[channel.site_id + channel.lang] = channel
} else {
errors.push({ type: 'duplicate', ...channel })
stats.errors++
}
if (!api.channels.find({ id: channel.xmltv_id })) {
errors.push({ type: 'wrong_xmltv_id', ...channel })
stats.errors++
}
if (!langs.where('1', channel.lang)) {
errors.push({ type: 'wrong_lang', ...channel })
stats.errors++
}
}
if (errors.length) {
console.log(chalk.underline(filepath))
console.table(errors, ['type', 'lang', 'xmltv_id', 'site_id', 'name'])
console.log()
stats.files++
}
}
if (stats.errors > 0) {
console.log(chalk.red(`${stats.errors} error(s) in ${stats.files} file(s)`))
process.exit(1)
}
}
main()

View file

@ -0,0 +1,95 @@
import { Storage, Collection, Dictionary, File, Logger } from '@freearhey/core'
import { ChannelsParser, ApiChannel } from '../../core'
import { program } from 'commander'
import chalk from 'chalk'
import langs from 'langs'
import { DATA_DIR } from '../../constants'
import { Channel } from 'epg-grabber'
program
.option(
'-c, --channels <path>',
'Path to channels.xml file to validate',
'sites/**/*.channels.xml'
)
.parse(process.argv)
const options = program.opts()
type ValidationError = {
type: 'duplicate' | 'wrong_xmltv_id' | 'wrong_lang'
name: string
lang?: string
xmltv_id?: string
site_id?: string
logo?: string
}
async function main() {
const logger = new Logger()
logger.info('options:')
logger.tree(options)
const parser = new ChannelsParser({ storage: new Storage() })
const dataStorage = new Storage(DATA_DIR)
const channelsContent = await dataStorage.json('channels.json')
const channels = new Collection(channelsContent).map(data => new ApiChannel(data))
let totalFiles = 0
let totalErrors = 0
const storage = new Storage()
let files: string[] = await storage.list(options.channels)
for (const filepath of files) {
const file = new File(filepath)
if (file.extension() !== 'xml') continue
const parsedChannels = await parser.parse(filepath)
const bufferById = new Dictionary()
const bufferBySiteId = new Dictionary()
const errors: ValidationError[] = []
parsedChannels.forEach((channel: Channel) => {
const bufferId: string = `${channel.xmltv_id}:${channel.lang}`
if (bufferById.missing(bufferId)) {
bufferById.set(bufferId, true)
} else {
errors.push({ type: 'duplicate', ...channel })
totalErrors++
}
const bufferSiteId: string = `${channel.site_id}:${channel.lang}`
if (bufferBySiteId.missing(bufferSiteId)) {
bufferBySiteId.set(bufferSiteId, true)
} else {
errors.push({ type: 'duplicate', ...channel })
totalErrors++
}
if (channels.missing((_channel: ApiChannel) => _channel.id === channel.xmltv_id)) {
errors.push({ type: 'wrong_xmltv_id', ...channel })
totalErrors++
}
if (!langs.where('1', channel.lang)) {
errors.push({ type: 'wrong_lang', ...channel })
totalErrors++
}
})
if (errors.length) {
console.log(chalk.underline(filepath))
console.table(errors, ['type', 'lang', 'xmltv_id', 'site_id', 'name'])
console.log()
totalFiles++
}
}
if (totalErrors > 0) {
console.log(chalk.red(`${totalErrors} error(s) in ${totalFiles} file(s)`))
process.exit(1)
}
}
main()