Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion schemas/guided-setup-summary.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -86,14 +86,37 @@
"KeepWithoutGuide",
"OwnPlaceholder",
"BindTrueMatch",
"ShareOnPurpose"
"ShareOnPurpose",
"EventGuide"
]
}
}
}
},
"EventGuide": {
"type": "object",
"additionalProperties": false,
"required": ["Applied", "Fallback"],
"properties": {
"Applied": { "$ref": "#/$defs/eventGuideRows" },
"Fallback": { "$ref": "#/$defs/eventGuideRows" }
}
}
},
"$defs": {
"eventGuideRows": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"required": ["Key", "Name", "Reason"],
"properties": {
"Key": { "type": "string" },
"Name": { "type": "string" },
"Reason": { "type": "string" }
}
}
},
"eventPatternPreview": {
"type": "object",
"additionalProperties": false,
Expand Down
37 changes: 30 additions & 7 deletions scripts/Build-My-Lineup.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ function Write-WorkflowReport {
"Decisions file: $($Report.DecisionsFile)"
}
if ($Report.NoGuideCount -gt 0) { "$($Report.NoGuideCount) channels have no guide. Run again and choose OwnPlaceholder to give them a name-only guide." }
foreach ($eventRow in @($Report.EventGuide.Applied) + @($Report.EventGuide.Fallback)) { "Event channel '$($eventRow.Name)': $($eventRow.Reason)" }
if ($Report.EventPatternPreview.Enabled) {
"Event-pattern preview: $($Report.EventPatternPreview.Status)"
"Event-pattern inference ran: $($Report.EventPatternPreview.InferenceRan.ToString().ToLowerInvariant())"
Expand Down Expand Up @@ -729,15 +730,20 @@ try {
$decisions = @(Invoke-ChannelForgePrivate -Name 'Read-ChannelForgeChannelDecisions' -Arguments @{ Path = $decisionsPath })
$strict = $AmbiguousAction -eq 'Cancel'
$interactive = [string]::IsNullOrWhiteSpace($AmbiguousAction) -and -not ([Console]::IsInputRedirected -or -not [Environment]::UserInteractive)
$entryStreamKey = {
param($entry)
$slice = $entry.EntryOutputSlice
$entryLines = [Text.Encoding]::UTF8.GetString($candidateM3UBytes, [int]$slice.ByteOffset, [int]$slice.ByteLength) -split "`n"
$streamUrl = @($entryLines | Where-Object { $_ -and -not $_.StartsWith('#') }) | Select-Object -Last 1
[string](Invoke-ChannelForgePrivate -Name 'Get-ChannelForgeChannelKey' -Arguments @{ Url = [string]$streamUrl } | Select-Object -Last 1)
}
$held = @(foreach ($binding in @($m3uBindings | Where-Object { [string]$_.Status -eq 'ReviewNeeded' })) {
$entry = @($manifest.Entries | Where-Object { [string]$_.EntryId -ceq [string]$binding.EntryId }) | Select-Object -First 1
if ($null -eq $entry) { continue }
$slice = $entry.EntryOutputSlice
$entryLines = [Text.Encoding]::UTF8.GetString($candidateM3UBytes, [int]$slice.ByteOffset, [int]$slice.ByteLength) -split "`n"
$streamUrl = @($entryLines | Where-Object { $_ -and -not $_.StartsWith('#') }) | Select-Object -Last 1
$streamKey = & $entryStreamKey $entry
[pscustomobject]@{
EntryId = [string]$entry.EntryId
Key = [string](Invoke-ChannelForgePrivate -Name 'Get-ChannelForgeChannelKey' -Arguments @{ Url = [string]$streamUrl } | Select-Object -Last 1)
Key = $streamKey
Name = [string]$entry.DisplayName
GroupId = [string]$binding.M3URawId
}
Expand Down Expand Up @@ -774,6 +780,21 @@ try {
if ($outcome.Choice -ne 'ShareOnPurpose') { $tvgIdByEntry[$outcome.EntryId] = $outcome.Guide }
}
$ownChannels = @($choices.Outcomes | Where-Object { $_.Choice -eq 'OwnPlaceholder' } | ForEach-Object { [pscustomobject]@{ Id = $_.Guide; Name = $_.Name } })
# Event channels (event-channel/v2, slice 3): channels rated high get an event guide from their own provider
# guide. A saved user choice wins. Any problem leaves every channel on its normal guide.
$eventGuideByEntry = @{}; $eventApplied = @(); $eventFallback = @()
if ($null -ne $candidateXMLTVBytes) {
try {
$guideIdByEntry = @{}
foreach ($binding in @($m3uBindings | Where-Object { [string]$_.Status -in 'ExactBound', 'ReviewNeeded' })) { $guideIdByEntry[[string]$binding.EntryId] = [string]$binding.M3URawId }
$eventEntries = @($manifest.Entries | ForEach-Object { [pscustomobject]@{ EntryId = [string]$_.EntryId; Key = (& $entryStreamKey $_); Name = [string]$_.DisplayName; GuideId = [string]$guideIdByEntry[[string]$_.EntryId] } })
$eventPlan = Invoke-ChannelForgePrivate -Name 'Get-ChannelForgeEventGuidePlan' -Arguments @{ XmltvBytes = $candidateXMLTVBytes; Entry = $eventEntries; ExcludedKey = [string[]]@($decisions | ForEach-Object { [string]$_.key }) } | Select-Object -Last 1
$eventApplied = @($eventPlan.Applied); $eventFallback = @($eventPlan.Fallback)
$ownChannels = @($ownChannels) + @($eventPlan.Channel)
foreach ($eventChannel in @($eventPlan.Channel)) { foreach ($eventEntryId in @($eventChannel.EntryIds)) { $eventGuideByEntry[$eventEntryId] = $eventChannel.Id; $tvgIdByEntry[$eventEntryId] = $eventChannel.Id } }
}
catch { Write-Warning 'The event channel guide could not be built, so every channel keeps its normal guide.' }
}
if ($ownChannels.Count -gt 0) {
$candidateXMLTVBytes = [byte[]](Invoke-ChannelForgePrivate -Name 'Add-ChannelForgePlaceholderGuide' -Arguments @{
XmltvBytes = $candidateXMLTVBytes; Channel = $ownChannels; TimeZone = [System.TimeZoneInfo]::Local } | Select-Object -Last 1)
Expand All @@ -785,8 +806,8 @@ try {
$report.ChannelGuides = @($manifest.Entries | ForEach-Object {
$id = [string]$_.EntryId
$outcome = $outcomeByEntry[$id]
$guideValue = if ($null -ne $outcome) { $outcome.Guide } elseif ($null -ne $candidateXMLTVBytes -and $exactEntryIds.ContainsKey($id)) { $exactEntryIds[$id] } else { $null }
[ordered]@{ name = [string]$_.DisplayName; guide = $guideValue; choice = if ($null -ne $outcome) { $outcome.Choice } elseif ($null -ne $guideValue) { 'ExactMatch' } else { 'NoMatch' } }
$guideValue = if ($eventGuideByEntry.ContainsKey($id)) { $eventGuideByEntry[$id] } elseif ($null -ne $outcome) { $outcome.Guide } elseif ($null -ne $candidateXMLTVBytes -and $exactEntryIds.ContainsKey($id)) { $exactEntryIds[$id] } else { $null }
[ordered]@{ name = [string]$_.DisplayName; guide = $guideValue; choice = if ($eventGuideByEntry.ContainsKey($id)) { 'EventGuide' } elseif ($null -ne $outcome) { $outcome.Choice } elseif ($null -ne $guideValue) { 'ExactMatch' } else { 'NoMatch' } }
})
$report.CollisionGroups = @($choices.Outcomes | Group-Object -Property GroupId -CaseSensitive | ForEach-Object {
$actions = [ordered]@{}
Expand All @@ -798,7 +819,9 @@ try {
SameStreamChannels = @($_.Group | Group-Object -Property Key | Where-Object { $_.Count -gt 1 } | ForEach-Object { @($_.Group | ForEach-Object Name) -join ' = ' })
}
})
$report.NoGuideCount = @($choices.Outcomes | Where-Object { $_.Choice -eq 'KeepWithoutGuide' }).Count
$report.NoGuideCount = @($choices.Outcomes | Where-Object { $_.Choice -eq 'KeepWithoutGuide' -and -not $eventGuideByEntry.ContainsKey($_.EntryId) }).Count
$report.EventGuide = [ordered]@{ Applied = @($eventApplied); Fallback = @($eventFallback) }
foreach ($eventRow in @($eventApplied) + @($eventFallback)) { Write-Host "Event channel '$($eventRow.Name)': $($eventRow.Reason)" -ForegroundColor Yellow }
$report.DecisionsFile = 'state/channel-decisions.json'
if ($report.CollisionGroups.Count -gt 0) {
Write-Host "Guide collisions: $($report.CollisionGroups.Count) guide ID(s) are shared by several channels." -ForegroundColor Yellow
Expand Down
20 changes: 11 additions & 9 deletions src/ChannelForge/Private/Add-ChannelForgePlaceholderGuide.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,10 @@ function Add-ChannelForgePlaceholderGuide {

$utf8 = [System.Text.UTF8Encoding]::new($false, $true)
$text = $utf8.GetString($XmltvBytes)
$stamp = [regex]::Matches($text, '<programme start="(\d{14}) \+0000" stop="(\d{14}) \+0000"')
if ($stamp.Count -eq 0) { throw 'The guide has no programs, so a name-only guide cannot be built for it.' }
$first = ($stamp | ForEach-Object { $_.Groups[1].Value } | Sort-Object | Select-Object -First 1)
$last = ($stamp | ForEach-Object { $_.Groups[2].Value } | Sort-Object | Select-Object -Last 1)
$format = 'yyyyMMddHHmmss'
$window = Get-ChannelForgeGuideWindow -Text $text
$windowStart = $window.Start
$windowEnd = $window.End
$culture = [System.Globalization.CultureInfo]::InvariantCulture
$windowStart = [datetime]::SpecifyKind([datetime]::ParseExact($first, $format, $culture), [System.DateTimeKind]::Utc)
$windowEnd = [datetime]::SpecifyKind([datetime]::ParseExact($last, $format, $culture), [System.DateTimeKind]::Utc)

$toUtc = {
param([datetime]$localMidnight)
Expand All @@ -46,8 +42,14 @@ function Add-ChannelForgePlaceholderGuide {
$id = [System.Security.SecurityElement]::Escape([string]$item.Id)
$name = [System.Security.SecurityElement]::Escape([string]$item.Name)
[void]$channelXml.Append(" <channel id=`"$id`"><display-name>$name</display-name></channel>`n")
foreach ($block in $blocks) {
[void]$programmeXml.Append(" <programme start=`"$($block[0].ToString($stampFormat, $culture))`" stop=`"$($block[1].ToString($stampFormat, $culture))`" channel=`"$id`"><title>$name</title></programme>`n")
# A channel with its own Blocks (Start, Stop, Title as UTC datetime) gets those; the rest get the day blocks.
$source = $blocks
if ($item.PSObject.Properties['Blocks'] -and @($item.Blocks).Count -gt 0) {
$source = @($item.Blocks | ForEach-Object { , @($_.Start, $_.Stop, [System.Security.SecurityElement]::Escape([string]$_.Title)) })
}
foreach ($block in $source) {
$title = if ($block.Count -gt 2) { $block[2] } else { $name }
[void]$programmeXml.Append(" <programme start=`"$($block[0].ToString($stampFormat, $culture))`" stop=`"$($block[1].ToString($stampFormat, $culture))`" channel=`"$id`"><title>$title</title></programme>`n")
}
}

Expand Down
12 changes: 10 additions & 2 deletions src/ChannelForge/Private/Get-ChannelForgeEventChannelCandidate.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ function Get-ChannelForgeEventChannelCandidate {
[CmdletBinding()]
param([Parameter(Mandatory)][AllowEmptyCollection()][object[]]$Channel)

$fillers = Get-ChannelForgeEventFillerTitle
# Filler titles: Test-ChannelForgeEventFillerKey
$ppvWords = @([pscustomobject]@{ Key = 'ppv'; Aliases = @('ppv', 'pay per view') })
$eventWords = @([pscustomobject]@{ Key = 'event'; Aliases = @('ppv', 'pay per view', 'event', 'events', 'ufc', 'wwe', 'aew', 'boxing', 'fight', 'wrestling', 'live event') })
$sportsKeys = @(Get-ChannelForgeOneGuideCategoryRegistry | Where-Object { $_.Group -ceq 'sports' } | ForEach-Object { [string]$_.Key })
Expand All @@ -33,7 +33,7 @@ function Get-ChannelForgeEventChannelCandidate {
# A title that echoes the channel name (equal, or one starts with the other, shorter side 4+ chars) is a placeholder.
$short = [math]::Min($title.Length, $name.Length)
$echo = $short -ge 4 -and ($name.StartsWith($title, [StringComparison]::Ordinal) -or $title.StartsWith($name, [StringComparison]::Ordinal))
if ($fillers -contains $title -or $title -ceq $name -or $echo) { $placeholder += $hours }
if ((Test-ChannelForgeEventFillerKey -Key $title) -or $title -ceq $name -or $echo) { $placeholder += $hours }
else { $realTitles[$title] = $true; if ($hours -ge 6) { $long += $hours } }
}
$share = if ($total -gt 0) { $placeholder / $total } else { 0.0 }
Expand Down Expand Up @@ -76,6 +76,14 @@ function Get-ChannelForgeEventFillerTitle {
'pay per view', 'ppv', 'event', 'events')
}

function Test-ChannelForgeEventFillerKey {
# True when a title key (ConvertTo-ChannelForgeEventTitleKey) is provider filler: an exact entry of
# Get-ChannelForgeEventFillerTitle, or a title containing "to be advised/announced/determined".
[CmdletBinding()]
param([string]$Key)
((Get-ChannelForgeEventFillerTitle) -contains $Key) -or ($Key -match '\bto be (advised|announced|determined)\b')
}

function ConvertTo-ChannelForgeEventTitleKey {
# Lowercase, punctuation to single spaces. The one title comparison rule for event channels.
[CmdletBinding()]
Expand Down
45 changes: 45 additions & 0 deletions src/ChannelForge/Private/Get-ChannelForgeEventGuidePlan.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
function Get-ChannelForgeEventGuidePlan {
# event-channel/v2, slice 3: the automatic apply rule. Only channels the detector rates high get an
# event guide, built from their own provider guide programs. Everything else keeps its normal guide.
# Entry: EntryId, Key, Name, GuideId (provider guide id, may be empty). ExcludedKey: channels with a
# saved user choice, which wins. Returns Channel (for Add-ChannelForgePlaceholderGuide: Id, Name,
# Blocks, plus Key and EntryIds), Applied and Fallback rows (Key, Name, Reason). Pure; no channel dropped.
[CmdletBinding()]
param(
[Parameter(Mandatory)][byte[]]$XmltvBytes,
[Parameter(Mandatory)][AllowEmptyCollection()][object[]]$Entry,
[AllowEmptyCollection()][string[]]$ExcludedKey = @()
)

$text = [System.Text.UTF8Encoding]::new($false, $true).GetString($XmltvBytes)
$window = Get-ChannelForgeGuideWindow -Text $text
$programmes = Read-ChannelForgeEventGuideProgramme -Text $text -GuideId @($Entry | ForEach-Object { [string]$_.GuideId } | Where-Object { $_ })
$byKey = [ordered]@{}
foreach ($item in $Entry) { if (-not $byKey.Contains([string]$item.Key)) { $byKey[[string]$item.Key] = [System.Collections.Generic.List[object]]::new() }; $byKey[[string]$item.Key].Add($item) }

$detectorInput = foreach ($group in $byKey.Values) {
$rows = if ($group[0].GuideId -and $programmes.ContainsKey([string]$group[0].GuideId)) { @($programmes[[string]$group[0].GuideId] | Where-Object Valid) } else { @() }
[pscustomobject]@{
Key = [string]$group[0].Key; DisplayName = [string]$group[0].Name; GroupTitle = ''; Category = $null
Programmes = @($rows | ForEach-Object { [pscustomobject]@{ Title = $_.Title; Start = $_.Start; Stop = $(if ($null -ne $_.Stop) { $_.Stop } else { $_.Start }) } })
}
}
$channels = [System.Collections.Generic.List[object]]::new()
$applied = [System.Collections.Generic.List[object]]::new()
$fallback = [System.Collections.Generic.List[object]]::new()
foreach ($rated in @(Get-ChannelForgeEventChannelCandidate -Channel @($detectorInput) | Where-Object { $_.Confidence -ceq 'high' })) {
$group = $byKey[$rated.Key]
$reason = $null
if ($ExcludedKey -contains $rated.Key) { $reason = 'you saved a guide choice for this channel' }
else {
$guideRows = @()
if ($group[0].GuideId -and $programmes.ContainsKey([string]$group[0].GuideId)) { $guideRows = @($programmes[[string]$group[0].GuideId]) }
$built = Get-ChannelForgeEventProgrammeBlocks -Programme $guideRows -ChannelName $rated.DisplayName -WindowStart $window.Start -WindowEnd $window.End
$reason = $built.Reason
}
if ($reason) { [void]$fallback.Add([pscustomobject]@{ Key = $rated.Key; Name = $rated.DisplayName; Reason = "normal guide kept: $reason" }); continue }
[void]$channels.Add([pscustomobject]@{ Id = 'ChannelForge-' + $rated.Key.Substring(0, 32); Name = $rated.DisplayName; Blocks = $built.Blocks; Key = $rated.Key; EntryIds = @($group | ForEach-Object { [string]$_.EntryId }) })
[void]$applied.Add([pscustomobject]@{ Key = $rated.Key; Name = $rated.DisplayName; Reason = "event guide applied: $($rated.Reasons -join '; ')" })
}
[pscustomobject]@{ Channel = @($channels.ToArray()); Applied = @($applied.ToArray()); Fallback = @($fallback.ToArray()) }
}
44 changes: 44 additions & 0 deletions src/ChannelForge/Private/Get-ChannelForgeEventProgrammeBlocks.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
function Get-ChannelForgeEventProgrammeBlocks {
# event-channel/v2, slice 3. Turns one channel's provider programs into ordered guide blocks with
# no overlap and no hole across the window: real programs keep their title and times, every gap
# shows the channel name (not provider filler). A title and a start are the minimum. A missing
# stop runs to the next real program, or DefaultMinutes. Returns Blocks (Start, Stop, Title as UTC
# datetime) or, when the channel must keep its normal guide, Reason. Pure.
[CmdletBinding()]
param(
[Parameter(Mandatory)][AllowEmptyCollection()][object[]]$Programme,
[Parameter(Mandatory)][string]$ChannelName,
[Parameter(Mandatory)][datetime]$WindowStart,
[Parameter(Mandatory)][datetime]$WindowEnd,
[int]$DefaultMinutes = 180
)

if ($Programme.Count -eq 0) { return [pscustomobject]@{ Blocks = @(); Reason = 'the provider guide has no programs for this channel' } }
if (@($Programme | Where-Object { -not $_.Valid }).Count -gt 0) { return [pscustomobject]@{ Blocks = @(); Reason = 'a program time in the provider guide could not be read' } }

# Filler titles: Test-ChannelForgeEventFillerKey
$nameKey = ConvertTo-ChannelForgeEventTitleKey -Text $ChannelName
$real = @($Programme | Where-Object {
$key = ConvertTo-ChannelForgeEventTitleKey -Text ([string]$_.Title)
$key -and -not (Test-ChannelForgeEventFillerKey -Key $key) -and $key -cne $nameKey
} | Sort-Object { $_.Start.UtcDateTime } | Group-Object { $_.Start.UtcDateTime } | ForEach-Object { $_.Group[0] })

$name = ConvertTo-ChannelForgeGuideSafeText -Value $ChannelName -MaximumLength 200
$blocks = [System.Collections.Generic.List[object]]::new()
$cursor = $WindowStart
for ($i = 0; $i -lt $real.Count; $i++) {
$start = [datetime]$real[$i].Start.UtcDateTime
if ($start -lt $cursor) { $start = $cursor }
$next = if ($i + 1 -lt $real.Count) { [datetime]$real[$i + 1].Start.UtcDateTime } else { $WindowEnd }
$stop = if ($null -ne $real[$i].Stop) { [datetime]$real[$i].Stop.UtcDateTime } elseif ($i + 1 -lt $real.Count) { $next } else { $start.AddMinutes($DefaultMinutes) }
if ($stop -gt $next) { $stop = $next }
if ($stop -gt $WindowEnd) { $stop = $WindowEnd }
if ($stop -le $start) { continue }
if ($start -gt $cursor) { [void]$blocks.Add([pscustomobject]@{ Start = $cursor; Stop = $start; Title = $name }) }
$title = ConvertTo-ChannelForgeGuideSafeText -Value $real[$i].Title -MaximumLength 200
[void]$blocks.Add([pscustomobject]@{ Start = $start; Stop = $stop; Title = $(if ($title) { $title } else { $name }) })
$cursor = $stop
}
if ($WindowEnd -gt $cursor) { [void]$blocks.Add([pscustomobject]@{ Start = $cursor; Stop = $WindowEnd; Title = $name }) }
[pscustomobject]@{ Blocks = @($blocks.ToArray()); Reason = $null }
}
Loading
Loading