-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplt.go
More file actions
319 lines (279 loc) · 9.22 KB
/
Copy pathplt.go
File metadata and controls
319 lines (279 loc) · 9.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
// Copyright © 2026 Kindly Ops, LLC <support@kindlyops.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import (
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"text/tabwriter"
"github.com/muesli/coral"
"github.com/rs/zerolog/log"
"github.com/spf13/viper"
)
var pltPrintJSON bool
var pltCmd = &coral.Command{
Use: "plt <command> <playlist-file>",
Short: "Work with purple playlists.",
Long: `Parse, build, and prepare media for purple playlist exports from the
source app for use in live meetings. Each subcommand takes the path to a
playlist export file.`,
Example: ` vbs plt print meeting.playlist
vbs plt build meeting.playlist`,
}
var pltPrintCmd = &coral.Command{
Use: "print <playlist-file>",
Short: "Parse and pretty-print a purple playlist.",
Long: `Parse a purple playlist export and print its cues. Works entirely
offline; no media is downloaded.`,
Example: " vbs plt print meeting.playlist",
Run: runPltPrint,
Args: coral.ExactArgs(1),
}
func runPltPrint(_ *coral.Command, args []string) {
arc := openPlaylist(args[0])
defer func() { _ = arc.Close() }()
if arc.schemaVersion != verifiedSchemaVersion {
log.Warn().Msgf("schema version %d differs from verified version %d; proceeding because required tables are present",
arc.schemaVersion, verifiedSchemaVersion)
}
pl, err := parsePlaylist(arc)
if err != nil {
log.Fatal().Err(err).Msg("Could not parse playlist")
}
view := buildPrintView(pl, viper.GetString("plt.mediaapi"))
if pltPrintJSON {
err = renderJSON(os.Stdout, view)
} else {
err = renderText(os.Stdout, view)
}
if err != nil {
log.Fatal().Err(err).Msg("Could not render playlist")
}
}
// resolveInputPath makes a user-supplied path usable regardless of how the
// binary was launched. Relative paths are resolved against the directory the
// command was invoked from; under `bazel run` that is reported via
// BUILD_WORKING_DIRECTORY, since the process itself starts in the runfiles tree.
func resolveInputPath(p string) string {
if p == "" || filepath.IsAbs(p) {
return p
}
if wd := os.Getenv("BUILD_WORKING_DIRECTORY"); wd != "" {
return filepath.Join(wd, p)
}
return p
}
// checkPlaylistFile reports a clear, path-focused error when the file is
// missing or unreadable, keeping it distinct from a format-validation failure.
func checkPlaylistFile(path string) error {
if _, err := os.Stat(path); err != nil {
if errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("no such file: %s", path)
}
return fmt.Errorf("could not access %s: %w", path, err)
}
return nil
}
// openPlaylist resolves the argument, fails fast with a distinct message when
// the file is missing, then sniffs and returns the validated archive. Shared
// by the print and build commands.
func openPlaylist(rawPath string) *archive {
path := resolveInputPath(rawPath)
if err := checkPlaylistFile(path); err != nil {
log.Fatal().Err(err).Msg("Could not open playlist file")
}
arc, err := sniffPlaylist(path)
if err != nil {
log.Fatal().Err(err).Msgf("Not a valid purple playlist: %s", path)
}
return arc
}
// printView is the offline summary rendered by plt print, shared by the text
// and JSON outputs so both show the same data.
type printView struct {
Name string `json:"name"`
Items []printItem `json:"items"`
}
type printItem struct {
Position int `json:"position"`
Label string `json:"label"`
Source string `json:"source"`
Kind string `json:"kind"`
DurationSec float64 `json:"durationSec"`
EndAction int `json:"endAction"`
MediaURL string `json:"mediaURL,omitempty"`
Markers []printMarker `json:"markers,omitempty"`
}
type printMarker struct {
Label string `json:"label"`
StartSec float64 `json:"startSec"`
DurationSec float64 `json:"durationSec"`
}
// buildPrintView projects the parsed playlist into the print summary. base is
// the configured media API endpoint (plt.mediaapi); when empty, media URLs are
// shown with a "<plt.mediaapi>" placeholder so the playlist-derived query is
// still visible offline.
func buildPrintView(pl *Playlist, base string) printView {
view := printView{Name: pl.Name, Items: make([]printItem, 0, len(pl.Items))}
for _, it := range pl.Items {
pi := printItem{
Position: it.Position,
Label: it.Label,
Source: describeSource(it),
Kind: itemKind(it),
DurationSec: itemDurationSec(it),
EndAction: it.EndAction,
MediaURL: itemMediaURL(it, base),
}
for _, m := range it.Markers {
pi.Markers = append(pi.Markers, printMarker{
Label: m.Label,
StartSec: ticksToSeconds(m.StartTimeTicks),
DurationSec: ticksToSeconds(m.DurationTicks),
})
}
view.Items = append(view.Items, pi)
}
return view
}
// itemMediaURL builds the media API query URL an item resolves to, derived from
// its catalog keys. Image cues and unsupported shapes have no URL. When base is
// empty the placeholder "<plt.mediaapi>" stands in for the configured endpoint.
func itemMediaURL(it Item, base string) string {
if it.Location == nil {
return ""
}
if base == "" {
base = "<plt.mediaapi>"
}
url, err := buildMediaURL(base, displayLangCode(it.Location.MepsLanguage), it.Location)
if err != nil {
return ""
}
return url
}
// displayLangCode returns the written-language code for a MepsLanguage ID, or
// the numeric ID when it is not mapped (best effort for display only).
func displayLangCode(id int) string {
if code, err := resolveLanguage(id, ""); err == nil {
return code
}
return strconv.Itoa(id)
}
// describeSource renders a one-line description of where an item's media comes
// from, following the catalog resolution rule (KeySymbol+Track, book/chapter, docid).
func describeSource(it Item) string {
if it.IsImage() {
return "embedded image"
}
loc := it.Location
if loc == nil {
return "unknown source"
}
shape, err := classifyLocation(loc)
if err != nil {
return fmt.Sprintf("unsupported location (type %d)", loc.Type)
}
switch shape {
case shapeBookChapter:
return fmt.Sprintf("book %d:%d", loc.BookNumber, loc.ChapterNumber)
case shapePub:
return fmt.Sprintf("pub %s track %d", loc.KeySymbol, loc.Track)
case shapeDocid:
return fmt.Sprintf("docid %d", loc.DocumentID)
default:
return fmt.Sprintf("unsupported location (type %d)", loc.Type)
}
}
// itemKind reports "image" or "video" for an item.
func itemKind(it Item) string {
if it.IsImage() {
return "image"
}
return "video"
}
// itemDurationSec returns the cue's nominal duration in seconds.
func itemDurationSec(it Item) float64 {
if it.IsImage() {
return ticksToSeconds(it.Image.DurationTicks)
}
if it.Location != nil {
return ticksToSeconds(it.Location.BaseDurationTicks)
}
return 0
}
// renderJSON writes the print view as indented JSON.
func renderJSON(w io.Writer, view printView) error {
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
if err := enc.Encode(view); err != nil {
return fmt.Errorf("could not encode JSON: %w", err)
}
return nil
}
// renderText writes the print view as an aligned table.
func renderText(w io.Writer, view printView) error {
if _, err := fmt.Fprintf(w, "Playlist: %s\n\n", view.Name); err != nil {
return fmt.Errorf("could not write header: %w", err)
}
tw := tabwriter.NewWriter(w, 0, 2, 2, ' ', 0)
if _, err := fmt.Fprintln(tw, "#\tLABEL\tSOURCE\tDURATION\tMARKERS\tAFTER"); err != nil {
return fmt.Errorf("could not write table header: %w", err)
}
for _, it := range view.Items {
markers := ""
if len(it.Markers) > 0 {
markers = fmt.Sprintf("%d", len(it.Markers))
}
if _, err := fmt.Fprintf(tw, "%d\t%s\t%s\t%.1fs\t%s\t%s\n",
it.Position, it.Label, it.Source, it.DurationSec, markers, endActionLabel(it.EndAction)); err != nil {
return fmt.Errorf("could not write table row: %w", err)
}
}
if err := tw.Flush(); err != nil {
return fmt.Errorf("could not flush table: %w", err)
}
return renderMediaURLs(w, view)
}
// renderMediaURLs prints the media API query URL each item resolves to, derived
// from the playlist's catalog keys.
func renderMediaURLs(w io.Writer, view printView) error {
var withURL []printItem
for _, it := range view.Items {
if it.MediaURL != "" {
withURL = append(withURL, it)
}
}
if len(withURL) == 0 {
return nil
}
if _, err := fmt.Fprint(w, "\nMedia URLs:\n"); err != nil {
return fmt.Errorf("could not write media URL header: %w", err)
}
for _, it := range withURL {
if _, err := fmt.Fprintf(w, " %d %s\n", it.Position, it.MediaURL); err != nil {
return fmt.Errorf("could not write media URL: %w", err)
}
}
return nil
}
func init() {
pltPrintCmd.Flags().BoolVar(&pltPrintJSON, "json", false, "emit the playlist as JSON instead of a table")
pltCmd.AddCommand(pltPrintCmd)
rootCmd.AddCommand(pltCmd)
}