๐Ÿ“ฆ flaviendelangle / mkv-editor

๐Ÿ“„ MkvFileEditor.ts ยท 488 lines
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488import { filenameParse } from '@ctrl/video-filename-parser'
import { exec } from 'child_process'
import { promises as fs } from 'fs'
import inquirer from 'inquirer'
import path from 'path'

import CacheManager from '../CacheManager'
import {
  CliConfig,
  MkvDetails,
  TrackTypes,
  MkvEditorScript,
  Track,
} from '../typings'
import { removeExtensionFromFileName } from '../utils'

import { DEFAULT_MKV_DETAILS, TRACK_TYPE_CONFIGS } from './MkvFileEditor.config'

type MkvFileEditorParams = {
  filePath: string
  config: CliConfig
  cache?: CacheManager
}

class MkvFileEditor {
  private static FILE_TITLE_REGEXP = /^([^(]+) \(([0-9]{4})\)$/

  private filePath: string
  private readonly config: CliConfig

  private mkvDetails: MkvDetails = DEFAULT_MKV_DETAILS

  private batchedActions: (() => Promise<void>)[] = []

  private readonly cache: CacheManager

  constructor(params: MkvFileEditorParams) {
    this.filePath = params.filePath
    this.config = params.config
    this.cache = params.cache ?? new CacheManager()
  }

  /**
   * Getters
   */
  get fileName() {
    return path.basename(this.filePath)
  }

  get fileNameWithoutExtension() {
    return removeExtensionFromFileName(this.fileName)
  }

  get fileDirectory() {
    return path.dirname(this.filePath)
  }

  get subtitleTracks() {
    return this.mkvDetails.tracks.filter(
      (track) => track.type === TrackTypes.subtitles
    )
  }

  get audioTracks() {
    return this.mkvDetails.tracks.filter(
      (track) => track.type === TrackTypes.audio
    )
  }

  /**
   * Utils
   */
  private log(message: string, forced: boolean = false) {
    if (this.config.verbose || forced) {
      const prefix = this.config.verbose
        ? ''
        : `${this.fileNameWithoutExtension} `
      console.log(`${prefix} ${message}`) // eslint-disable-line no-console
    }
  }

  private async fetchFileDetails() {
    const response = await this.execQuery(`mkvmerge -J "${this.filePath}"`)
    this.mkvDetails = JSON.parse(response)
  }

  private async execQuery(query: string) {
    this.log(`Exec query: ${query}`)

    return new Promise<any>((resolve, reject) =>
      exec(query, (error, stdout) => {
        if (error) {
          reject(error)
        } else {
          resolve(stdout)
        }
      })
    )
  }

  private async execAction(action: () => Promise<void>) {
    if (this.config.batch) {
      this.batchedActions.push(action)
    } else {
      return action()
    }
  }

  /**
   * Runners
   */
  public async run() {
    this.log(`\nProcess ${this.fileName}`)

    await this.fetchFileDetails()

    await this.cache.fetchConfig()

    if (this.config.debug) {
      await this.cache.upsertFile(
        `${this.fileName}.txt`,
        JSON.stringify(this.mkvDetails, null, 2)
      )
    }

    if (this.config.scripts[MkvEditorScript.addMissingLanguages]) {
      await this.addMissingLanguages(TrackTypes.audio)
      await this.addMissingLanguages(TrackTypes.subtitles)
    }

    if (this.config.scripts[MkvEditorScript.promptDefaultAudioLanguage]) {
      await this.promptDefaultAudioLanguage()
    }

    if (this.config.scripts[MkvEditorScript.setDefaultSubtitle]) {
      await this.setDefaultSubtitle()
    }

    if (this.config.scripts[MkvEditorScript.removeUselessAudioTracks]) {
      await this.removeUselessAudioTracks()
    }

    if (this.config.scripts[MkvEditorScript.sanitizeTitle]) {
      await this.sanitizeTitle()
    }

    if (this.config.scripts[MkvEditorScript.extractSubtitles]) {
      await this.extractSubtitles()
    }
  }

  public async runBatchedActions() {
    if (!this.batchedActions.length) {
      return
    }

    this.log(`\nRun batched actions for ${this.fileName}`)

    for (let i = 0; i < this.batchedActions.length; i++) {
      await this.batchedActions[i]()
    }

    this.batchedActions = []
  }

  /**
   * Scripts
   */

  private async addMissingLanguages(type: TrackTypes) {
    const tracks = this.mkvDetails.tracks.filter((track) => track.type === type)

    for (let i = 0; i < tracks.length; i++) {
      const { properties } = tracks[i]

      const amountOfSameType = tracks.length

      if (properties.language === 'und') {
        const { language } = await inquirer.prompt<{ language: string }>([
          {
            name: 'language',
            message: `New language for ${this.fileName} : ${type} ${
              i + 1
            } of ${amountOfSameType}`,
          },
        ])

        if (language) {
          await this.execQuery(
            `mkvpropedit "${this.filePath}" --edit track:@${properties.number} --set language=${language}`
          )
          this.log('Track updated', true)
        } else {
          this.log('Track ignored', true)
        }
      }
    }
  }

  private async promptDefaultAudioLanguage() {
    const audioTracks = this.audioTracks

    const currentDefaultAudioLanguage = audioTracks.find(
      (track) => track.properties.default_track
    )?.properties?.language

    if (audioTracks.length === 1 && !currentDefaultAudioLanguage) {
      await this.setDefaultTrack(audioTracks, audioTracks[0])
    }

    if (
      new Set(audioTracks.map((track) => track.properties.language)).size > 1
    ) {
      const { language } = await inquirer.prompt<{ language: string }>([
        {
          name: 'language',
          message: `New language for ${this.fileName} : ${audioTracks
            .map((track) => track.properties.language)
            .join(', ')}`,
          default:
            currentDefaultAudioLanguage ?? audioTracks[0].properties.language,
        },
      ])

      const newDefaultAudioTrack = audioTracks.find(
        (track) => track.properties.language === language
      )

      if (!newDefaultAudioTrack) {
        this.log('The language you gave does not exist', true)
        await this.promptDefaultAudioLanguage()
      } else {
        await this.setDefaultTrack(audioTracks, newDefaultAudioTrack)
      }
    }
  }

  private async setDefaultSubtitle() {
    const audioLanguage = this.mkvDetails.tracks.find(
      (track) =>
        track.type === TrackTypes.audio && track.properties.default_track
    )?.properties?.language

    const subtitleTracks = this.subtitleTracks

    const currentDefaultSubtitleLanguage = subtitleTracks.find(
      (track) => track.properties.default_track
    )?.properties?.language

    let defaultSubtitleTrack: Track | null = null

    if (audioLanguage && subtitleTracks.length) {
      if (audioLanguage === 'fre') {
        defaultSubtitleTrack = null
      } else if (audioLanguage === 'eng') {
        defaultSubtitleTrack =
          subtitleTracks.find((track) => track.properties.language === 'eng') ??
          null

        if (!defaultSubtitleTrack) {
          defaultSubtitleTrack =
            subtitleTracks.find(
              (track) => track.properties.language === 'fr'
            ) ?? null
        }
      } else {
        defaultSubtitleTrack =
          subtitleTracks.find((track) => track.properties.language === 'fr') ??
          null

        if (!defaultSubtitleTrack) {
          defaultSubtitleTrack =
            subtitleTracks.find(
              (track) => track.properties.language === 'eng'
            ) ?? null
        }
      }
    }

    if (defaultSubtitleTrack) {
      if (
        currentDefaultSubtitleLanguage !==
        defaultSubtitleTrack.properties.language
      ) {
        await this.setDefaultTrack(subtitleTracks, defaultSubtitleTrack)
      }
    } else if (subtitleTracks.length) {
      this.log('No default subtitle found')
    }
  }

  private async removeUselessAudioTracks() {
    const defaultAudioLanguage = this.audioTracks.find(
      (track) => track.properties.default_track
    )?.properties?.language

    if (!defaultAudioLanguage) {
      return
    }

    const uselessAudioTracks = this.audioTracks.filter(
      (track) =>
        track.properties.language !== defaultAudioLanguage &&
        track.properties.language !== 'fre'
    )

    if (uselessAudioTracks.length) {
      await this.removeTracks(uselessAudioTracks)
    }
  }

  private async sanitizeTitle() {
    const titleMatch = MkvFileEditor.FILE_TITLE_REGEXP.exec(
      this.fileNameWithoutExtension
    )

    if (!titleMatch) {
      const fileInfo = filenameParse(this.fileName)

      const { title, year } = await inquirer.prompt<{
        year: string
        title: string
      }>([
        {
          name: 'title',
          message: `Title of ${this.fileName}`,
          default: fileInfo.title
            ? removeExtensionFromFileName(fileInfo.title).trim()
            : '',
        },
        {
          name: 'year',
          message: `Release year of ${this.fileName} :`,
          year: fileInfo.year,
        },
      ])

      if (!year || !title) {
        this.log('Missing informations', true)
        await this.sanitizeTitle()
      } else {
        const newFileName = `${title} (${year}).mkv`

        const newFilePath = path.join(this.fileDirectory, newFileName)

        await fs.rename(this.filePath, newFilePath)
        this.filePath = newFilePath
        this.log(`File renamed: ${this.fileName} => ${newFileName}`, true)
      }
    }

    const newTitleMatch = MkvFileEditor.FILE_TITLE_REGEXP.exec(
      this.fileNameWithoutExtension
    )

    if (!newTitleMatch) {
      this.log('Something went wrong', true)
    } else {
      const containerTitle = this.mkvDetails.container.properties.title
      const newTitle = newTitleMatch[1]

      if (newTitle !== containerTitle) {
        await this.execQuery(
          `mkvpropedit "${this.filePath}" --edit info --set "title=${newTitle}"`
        )
        this.log(
          `Container title updated: ${containerTitle} => ${newTitle}`,
          true
        )
      }
    }

    await this.fetchFileDetails()
  }

  private async extractSubtitles() {
    /*
    const subtitleTracks = this.subtitleTracks

    if (!subtitleTracks.length) {
      return
    }

    const { index } = await inquirer.prompt<{ index: number }>([
      {
        name: 'index',
        message: `Subtitle of ${this.fileName} to extract ${subtitleTracks.map(
          (track, trackIndex) => `${trackIndex} (${track.properties.language})`
        )})`,
        type: 'number',
        default: 0,
      },
    ])

    const trackToExtract = subtitleTracks[index]

    if (trackToExtract) {
      const trackPath = path.join(
        this.fileDirectory,
        `${this.fileNameWithoutExtension}.${trackToExtract.properties.language}.sub`
      )

      await this.execAction(async () => {
        await this.execQuery(
          `mkvextract "${this.filePath}" tracks ${trackToExtract.id}:"${trackPath}"`
        )
      })
    } else {
      this.log('Invalid track index', true)
      await this.extractSubtitles()
    }
    */
  }

  /**
   * Mutations
   */
  private async setDefaultTrack(tracks: Track[], defaultTrack: Track) {
    const tracksCommand = tracks
      .map(
        (track) =>
          `--edit track:@${track.properties.number} --set flag-default=${
            track.id === defaultTrack.id
          }`
      )
      .join(' ')

    await this.execQuery(`mkvpropedit "${this.filePath}" ${tracksCommand}`)
    await this.fetchFileDetails()

    this.log(
      `New default ${defaultTrack.type} : ${defaultTrack.properties.language}`,
      true
    )
  }

  private async removeTracks(tracksToRemove: Track[]) {
    if (
      tracksToRemove.length === 0 ||
      new Set(tracksToRemove.map((track) => track.type)).size > 1
    ) {
      this.log('Invalid track list', true)
      return
    }

    const tracksType = tracksToRemove[0].type
    const tracksToKeepIds = this.mkvDetails.tracks
      .filter(
        (track) =>
          track.type === tracksType &&
          tracksToRemove.every((trackBis) => trackBis.id !== track.id)
      )
      .map((track) => track.id)

    const noTrackFlag =
      TRACK_TYPE_CONFIGS[tracksType].mkvmerge.stripFromFileFlag

    const tempFilePath = `${this.filePath}.temp`

    const { isConfirmed } = await inquirer.prompt<{ isConfirmed: string }>([
      {
        name: 'isConfirmed',
        message: `Tracks of type ${tracksType} to remove : ${tracksToRemove.map(
          (track) => track.properties.language
        )}`,
        default: 'yes',
      },
    ])

    if (['y', 'yes'].includes(`${isConfirmed}`.toLowerCase())) {
      await this.execAction(async () => {
        await this.execQuery(
          `mkvmerge -o "${tempFilePath}" -${noTrackFlag} ${tracksToKeepIds.join(
            ','
          )} "${this.filePath}"`
        )
        await fs.unlink(this.filePath)
        await fs.rename(tempFilePath, this.filePath)
        await this.fetchFileDetails()
      })
    } else {
      this.log('Modification ignored')
    }
  }
}

export default MkvFileEditor