Update scripts

This commit is contained in:
freearhey 2025-04-02 07:13:39 +03:00
parent 37664b49b9
commit 5dd131e2d3
15 changed files with 274 additions and 204 deletions

View file

@ -1,12 +1,16 @@
import { Storage, Collection, Logger, Dictionary } from '@freearhey/core'
import { select, input } from '@inquirer/prompts'
import { ChannelsParser, XML } from '../../core'
import { Channel, Feed } from '../../models'
import { DATA_DIR } from '../../constants'
import { Storage, Collection, Logger } from '@freearhey/core'
import { ChannelsParser, XML, ApiChannel } from '../../core'
import { Channel } from 'epg-grabber'
import nodeCleanup from 'node-cleanup'
import { program } from 'commander'
import inquirer, { QuestionCollection } from 'inquirer'
import Fuse from 'fuse.js'
import epgGrabber from 'epg-grabber'
import { Command } from 'commander'
import readline from 'readline'
import Fuse from 'fuse.js'
type ChoiceValue = { type: string; value?: Feed | Channel }
type Choice = { name: string; short?: string; value: ChoiceValue }
if (process.platform === 'win32') {
readline
@ -19,105 +23,159 @@ if (process.platform === 'win32') {
})
}
const program = new Command()
program.argument('<filepath>', 'Path to *.channels.xml file to edit').parse(process.argv)
const filepath = program.args[0]
const logger = new Logger()
const storage = new Storage()
let channels = new Collection()
let parsedChannels = new Collection()
async function main() {
main(filepath)
nodeCleanup(() => {
save(filepath)
})
export default async function main(filepath: string) {
if (!(await storage.exists(filepath))) {
throw new Error(`File "${filepath}" does not exists`)
}
const parser = new ChannelsParser({ storage })
channels = await parser.parse(filepath)
parsedChannels = await parser.parse(filepath)
const dataStorage = new Storage(DATA_DIR)
const channelsContent = await dataStorage.json('channels.json')
const searchIndex = new Fuse(channelsContent, { keys: ['name', 'alt_names'], threshold: 0.4 })
const channelsData = await dataStorage.json('channels.json')
const channels = new Collection(channelsData).map(data => new Channel(data))
const feedsData = await dataStorage.json('feeds.json')
const feeds = new Collection(feedsData).map(data => new Feed(data))
const feedsGroupedByChannelId = feeds.groupBy((feed: Feed) => feed.channelId)
for (const channel of channels.all()) {
const searchIndex: Fuse<Channel> = new Fuse(channels.all(), {
keys: ['name', 'alt_names'],
threshold: 0.4
})
for (const channel of parsedChannels.all()) {
if (channel.xmltv_id) continue
const question: QuestionCollection = {
name: 'option',
message: `Select xmltv_id for "${channel.name}" (${channel.site_id}):`,
type: 'list',
choices: getOptions(searchIndex, channel),
pageSize: 10
try {
channel.xmltv_id = await selectChannel(channel, searchIndex, feedsGroupedByChannelId)
} catch {
break
}
await inquirer.prompt(question).then(async selected => {
switch (selected.option) {
case 'Type...':
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())
channel.xmltv_id = xmltv_id
break
}
})
}
channels.forEach((channel: Channel) => {
parsedChannels.forEach((channel: epgGrabber.Channel) => {
if (channel.xmltv_id === '-') {
channel.xmltv_id = ''
}
})
}
main()
async function selectChannel(
channel: epgGrabber.Channel,
searchIndex: Fuse<Channel>,
feedsGroupedByChannelId: Dictionary
): Promise<string> {
const similarChannels = searchIndex
.search(channel.name)
.map((result: { item: Channel }) => result.item)
function save() {
const selected: ChoiceValue = await select({
message: `Select channel ID for "${channel.name}" (${channel.site_id}):`,
choices: getChannelChoises(new Collection(similarChannels)),
pageSize: 10
})
switch (selected.type) {
case 'skip':
return '-'
case 'type': {
const typedChannelId = await input({ message: ' Channel ID:' })
const typedFeedId = await input({ message: ' Feed ID:', default: 'SD' })
return [typedChannelId, typedFeedId].join('@')
}
case 'channel': {
const selectedChannel = selected.value
if (!selectedChannel) return ''
const selectedFeedId = await selectFeed(selectedChannel.id, feedsGroupedByChannelId)
return [selectedChannel.id, selectedFeedId].join('@')
}
}
return ''
}
async function selectFeed(channelId: string, feedsGroupedByChannelId: Dictionary): Promise<string> {
const channelFeeds = feedsGroupedByChannelId.get(channelId) || []
if (channelFeeds.length <= 1) return ''
const selected: ChoiceValue = await select({
message: `Select feed ID for "${channelId}":`,
choices: getFeedChoises(channelFeeds),
pageSize: 10
})
switch (selected.type) {
case 'type':
return await input({ message: ' Feed ID:' })
case 'feed':
const selectedFeed = selected.value
if (!selectedFeed) return ''
return selectedFeed.id
}
return ''
}
function getChannelChoises(channels: Collection): Choice[] {
const choises: Choice[] = []
channels.forEach((channel: Channel) => {
const names = [channel.name, ...channel.altNames.all()].join(', ')
choises.push({
value: {
type: 'channel',
value: channel
},
name: `${channel.id} (${names})`,
short: `${channel.id}`
})
})
choises.push({ name: 'Type...', value: { type: 'type' } })
choises.push({ name: 'Skip', value: { type: 'skip' } })
return choises
}
function getFeedChoises(feeds: Collection): Choice[] {
const choises: Choice[] = []
feeds.forEach((feed: Feed) => {
let name = `${feed.id} (${feed.name})`
if (feed.isMain) name += ' [main]'
choises.push({
value: {
type: 'feed',
value: feed
},
name,
short: feed.id
})
})
choises.push({ name: 'Type...', value: { type: 'type' } })
return choises
}
function save(filepath: string) {
if (!storage.existsSync(filepath)) return
const xml = new XML(channels)
const xml = new XML(parsedChannels)
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: ' xmltv_id:',
type: 'input'
}
])
return { name, xmltv_id: input['xmltv_id'] }
}
function getOptions(index, channel: Channel) {
const similar = index.search(channel.name).map(result => new ApiChannel(result.item))
const variants = new Collection()
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}`)
})
variants.add('Type...')
variants.add('Skip')
return variants.all()
}