« get me outta code hell

duration-graph.js « src - http-music - Command-line music player + utils (not a server!)
about summary refs log tree commit diff
path: root/src/duration-graph.js
blob: ee6113cf2bcd8c3dc9f16b4b830cf2ec14ac9216 (plain)
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
'use strict'

const fs = require('fs')
const util = require('util')
const processArgv = require('./process-argv')

const {
  updatePlaylistFormat,
  isGroup, isItem,
  getItemPathString,
  flattenGrouplike
} = require('./playlist-utils')

const { makePlaylistOptions } = require('./general-util')

const readFile = util.promisify(fs.readFile)

const metrics = {}
metrics.duration = Symbol('Duration')
metrics.length = metrics.duration
metrics.time = metrics.duration
metrics.tracks = Symbol('# of tracks')
metrics.items = metrics.tracks

function getUncachedDurationOfItem(item) {
  if (isGroup(item)) {
    return item.items.reduce((a, b) => a + getDurationOfItem(b), 0)
  } else {
    if (item && item.metadata && item.metadata.duration) {
      return item.metadata.duration
    } else {
      console.warn('Item missing metadata:', getItemPathString(item))
      return 0
    }
  }
}

// This is mostly just to avoid logging out "item missing metadata" warnings
// multiple times.
function getDurationOfItem(item) {
  if (metrics.duration in item === false) {
    item[metrics.duration] = getUncachedDurationOfItem(item)
  }

  return item[metrics.duration]
}

function getTrackCount(item) {
  if (metrics.tracks in item === false) {
    if (isGroup(item)) {
      item[metrics.tracks] = flattenGrouplike(item).items.length
    } else {
      item[metrics.tracks] = 1
    }
  }

  return item[metrics.tracks]
}

const getHours = n => Math.floor(n / 3600)
const getMinutes = n => Math.floor((n % 3600) / 60)
const getSeconds = n => n % 60

function wordFormatDuration(durationNumber) {
  if (typeof durationNumber !== 'number') {
    throw new Error('Non-number passed')
  }

  // oh yeah
  const hours = getHours(durationNumber),
        minutes = getMinutes(durationNumber),
        seconds = getSeconds(durationNumber)

  return [
    hours ? `${hours} hours` : false,
    minutes ? `${minutes} minutes` : false,
    seconds ? `${seconds} seconds` : false
  ].filter(Boolean).join(', ') || '(No length.)'
}

function digitalFormatDuration(durationNumber) {
  if (typeof durationNumber !== 'number') {
    throw new Error('Non-number passed')
  }

  const hours = getHours(durationNumber),
        minutes = getMinutes(durationNumber),
        seconds = getSeconds(durationNumber)

  return [hours, minutes, seconds].filter(Boolean).length ? [
    hours ? `${hours}` : false,
    minutes ? `${minutes}`.padStart(2, '0') : '00',
    seconds ? `${seconds}`.padStart(2, '0') : '00'
  ].filter(Boolean).join(':') : '(No length.)'
}

function padStartList(strings) {
  const len = strings.reduce((a, b) => Math.max(a, b.length), 0)
  return strings.map(s => s.padStart(len, ' '))
}

function measureItem(item, metric) {
  if (metric === metrics.duration) {
    return getDurationOfItem(item)
  } else if (metric === metrics.tracks) {
    return getTrackCount(item)
  } else {
    throw new Error('Invalid metric: ' + metric)
  }
}

function makePlaylistGraph(playlist, {
  graphWidth = 60,
  onlyFirst = 20,
  metric = metrics.duration
} = {}) {
  const output = []

  const wholePlaylistLength = measureItem(playlist, metric)

  const briefFormatDuration = duration => {
    if (metric === metrics.duration) {
      return digitalFormatDuration(duration)
    } else {
      return duration.toString()
    }
  }

  const longFormatDuration = duration => {
    if (metric === metrics.duration) {
      return wordFormatDuration(duration)
    } else if (metric === metrics.tracks) {
      return `${duration} tracks`
    } else {
      return duration.toString()
    }
  }

  let topThings = playlist.items.map((item, i) => {
    const duration = measureItem(item, metric)
    const briefDuration = briefFormatDuration(duration)
    return {item, duration, briefDuration}
  })

  topThings.sort((a, b) => b.duration - a.duration)

  const ignoredThings = topThings.slice(onlyFirst)

  topThings = topThings.slice(0, onlyFirst)

  const displayLength = topThings.reduce((a, b) => a + b.duration, 0)

  // Left-pad the brief durations so they're all the same length.
  {
    const len = topThings.reduce((a, b) => Math.max(a, b.briefDuration.length), 0)
    for (const obj of topThings) {
      obj.padDuration = obj.briefDuration.padStart(len, ' ')
    }
  }

  let totalWidth = 0
  for (let i = 0; i < topThings.length; i++) {
    // Add a color to each item.
    const colorCode = (i % 6) + 1
    topThings[i].fgColor = `\x1b[3${colorCode}m`
    topThings[i].bgColor = `\x1b[4${colorCode}m`

    topThings[i].partOfWhole = 1 / displayLength * topThings[i].duration

    let w = Math.floor(topThings[i].partOfWhole * graphWidth)
    if (totalWidth < graphWidth) {
      w = Math.max(1, w)
    }
    totalWidth += w
    topThings[i].visualWidth = w
  }

  output.push('    Whole length: ' + longFormatDuration(wholePlaylistLength), '')

  output.push('    ' + topThings.map(({ bgColor, fgColor, visualWidth }) => {
    return bgColor + fgColor + '-'.repeat(visualWidth)
  }).join('') + '\x1b[0m' + (ignoredThings.length ? ' *' : ''), '')

  output.push('    Length by item:')

  output.push(...topThings.map(({ item, padDuration, visualWidth, fgColor }) =>
    `    ${fgColor}${
      // Dim the row if it doesn't show up in the graph.
      visualWidth === 0 ? '\x1b[2m- ' : '  '
    }${padDuration}  ${item.name}\x1b[0m`
  ))

  if (ignoredThings.length) {
    const totalDuration = ignoredThings.reduce((a, b) => a + b.duration, 0)
    const dur = longFormatDuration(totalDuration)
    output.push(
      `    \x1b[2m(* Plus ${ignoredThings.length} skipped items, accounting `,
      `       for ${dur}.)\x1b[0m`
    )
  }

  if (topThings.some(x => x.visualWidth === 0)) {
    output.push('',
      '    (Items that are too short to show up on the',
      '     visual graph are dimmed and marked with a -.)'
    )
  }

  return output
}

async function main(args) {
  if (args.length === 0) {
    console.log("Usage: http-music duration-graph /path/to/processed-playlist.json")
    return
  }

  let graphWidth = 60
  let onlyFirst = 20
  let metric = metrics.duration

  const { optionFunctions, getStuff } = makePlaylistOptions()

  Object.assign(optionFunctions, {
    '-metric': util => {
      const arg = util.nextArg()
      if (Object.keys(metrics).includes(arg)) {
        metric = metrics[arg]
      } else {
        console.warn('Didn\'t set metric because it isn\'t recognized:', arg)
      }
    },

    '-measure': util => util.alias('-metric'),
    'm': util => util.alias('-metric'),

    '-graph-width': util => {
      const arg = util.nextArg()
      const newVal = parseInt(arg)
      if (newVal > 0) {
        graphWidth = newVal
      } else {
        console.warn('Didn\'t set graph width because it\'s not greater than 0:', arg)
      }
    },

    '-width': util => util.alias('-graph-width'),
    'w': util => util.alias('-graph-width'),

    '-only-first': util => {
      const arg = util.nextArg()
      const newVal = parseInt(arg)
      if (newVal > 0) {
        onlyFirst = newVal
      } else {
        console.warn('You can\'t use the first *zero* tracks! -', arg)
      }
    },

    '-first': util => util.alias('-only-first'),

    '-all': util => {
      onlyFirst = Infinity
    }
  })

  await processArgv(args, optionFunctions)

  const playlist = getStuff.activePlaylist

  for (const line of makePlaylistGraph(playlist, {
    graphWidth, onlyFirst, metric
  })) {
    console.log(line)
  }
}

module.exports = main