summaryrefslogtreecommitdiff
path: root/omptagger
blob: c2063233089cb22af24b252e3d23a764ccc200db (plain) (blame)
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
#!/usr/bin/env ruby
#
# omptagger [version 0.4]
# http://dev.gentoo.org/~omp/omptagger/
#
# Copyright 2007 David Shakaryan <omp@gentoo.org>
# Distributed under the terms of the GNU General Public License v3.
# See http://www.gnu.org/licenses/gpl.txt for the full license text.
#
# Program for modifying and displaying tags for various formats of audio files.
# Behaviour changes between acting as a wrapper tool or using a library, based
# on the format of the file being worked with.
#
# Dependencies:
# * ruby [ http://www.ruby-lang.org/ ]
# * flac [ http://flac.sourceforge.net/ ]
# * id3lib-ruby [ http://id3lib-ruby.rubyforge.org/ ]
# * vorbis-tools [ http://www.vorbis.com/ ]

require 'getoptlong'
require 'id3lib'

# List of valid options and whether they accept arguments.
getopt = GetoptLong.new(
  ['--view',       '-v', GetoptLong::NO_ARGUMENT],
  ['--view-tag',   '-t', GetoptLong::REQUIRED_ARGUMENT],
  ['--set-tag',    '-s', GetoptLong::REQUIRED_ARGUMENT],
  ['--generate',   '-g', GetoptLong::NO_ARGUMENT],
  ['--preview',    '-p', GetoptLong::NO_ARGUMENT],
  ['--remove',     '-r', GetoptLong::NO_ARGUMENT],
  ['--remove-tag', '-d', GetoptLong::REQUIRED_ARGUMENT],
  ['--rename',     '-m', GetoptLong::NO_ARGUMENT],
  ['--no-colour',  '-c', GetoptLong::NO_ARGUMENT],
  ['--help',       '-h', GetoptLong::NO_ARGUMENT]
)

# Create a hash and and store in it any options set. Create an actions variable
# which defaults to false, in order to track whether an action has been set.
action = false
opts = Hash.new
getopt.each do |opt, arg|
  opt = opt.sub('--', '')

  case opt
  # Options which do not accept any arguments.
  when 'view', 'generate', 'preview', 'remove', 'rename', 'help'
    opts[opt] = ''
    action = true
  when 'no-colour'
    opts[opt] = ''

  # Options which accept arguments. Store arguments in an array rather than a
  # string as these options may be used more than once per command.
  when 'view-tag', 'set-tag', 'remove-tag'
    if opts.has_key?(opt)
      opts[opt].push(arg)
    else
      opts[opt] = [arg]
    end
    action = true
  end
end

# Define colours unless the no-colour option is set.
if opts.has_key?('no-colour')
  def colred(text); "#{text}"; end
  def colgrn(text); "#{text}"; end
  def colyel(text); "#{text}"; end
  def colcyn(text); "#{text}"; end
else
  def colred(text); "\e[31m#{text}\e[0m"; end
  def colgrn(text); "\e[32m#{text}\e[0m"; end
  def colyel(text); "\e[33m#{text}\e[0m"; end
  def colcyn(text); "\e[36m#{text}\e[0m"; end
end

# Methods for outputting warning and status messages.
def warn(message)
  puts '  ' + colred('ERROR:') + ' ' + message
end
def status(message)
  puts '  ' + colgrn(message)
end

# Method for escaping single quotes for use within single quotes in shell
# commands. Substitutes all instances of ' with '\''.
def esc(text)
  text.gsub("'", "'\\\\''")
end

# Method for outputting program help.
def help
  puts colyel('Usage:') + ' omptagger ' + colgrn('[options]') + ' ' +
    colgrn('[files]')
  puts
  puts colyel('Options:')
  puts '  ' + colgrn('--view') + '        ' + colgrn('-v') +
    '  Display all tags'
  puts '  ' + colgrn('--view-tag') + '    ' + colgrn('-t') +
    '  Display a tag ' + colcyn('[required argument: tag]')
  puts '  ' + colgrn('--set-tag') + '     ' + colgrn('-s') +
    '  Set a tag ' + colcyn('[required argument: tag=string]')
  puts '  ' + colgrn('--generate') + '    ' + colgrn('-g') +
    '  Generate tags based on filename'
  puts '  ' + colgrn('--preview') + '     ' + colgrn('-p') +
    '  Preview tags that will be set with generate option'
  puts '  ' + colgrn('--remove') + '      ' + colgrn('-r') +
    '  Remove all tags'
  puts '  ' + colgrn('--remove-tag') + '  ' + colgrn('-d') +
    '  Remove a tag ' + colcyn('[required argument: tag]')
  puts '  ' + colgrn('--rename') + '      ' + colgrn('-m') +
    '  Rename files based on tags'
  puts '  ' + colgrn('--no-colour') + '   ' + colgrn('-c') +
    '  Disable use of colour in program output'
  puts '  ' + colgrn('--help') + '        ' + colgrn('-h') +
    '  Display program help'
  puts
  puts colyel('Notes:')
  puts '  ' + colgrn('*') + ' When generating tags based on filename, the' +
    ' filename must be in one of the'
  puts '  ' + '  two following formats: ' + colcyn('01 - Artist - Title.ext') +
    ' or ' + colcyn('Artist - Title.ext') + '.'
    ' future release.'
  puts '  ' + colgrn('*') + ' Underscores in the filename are converted to' +
    ' spaces in the tags.'
  puts '  ' + colgrn('*') + ' FLAC, Vorbis and MP3 files are fully' +
    ' supported. File format is determined'
  puts '  ' + '  by the file\'s extension.'
end

# Class for Vorbis comments; used by FLAC and Vorbis files.
class VorbisComments
  attr_reader :hash, :file

  # Create constant array containing possible tag names.
  TAGS = ['TITLE', 'VERSION', 'ALBUM', 'TRACKNUMBER', 'ARTIST', 'PERFORMER',
          'COPYRIGHT', 'LICENSE', 'ORGANIZATION', 'DESCRIPTION', 'GENRE',
          'DATE', 'LOCATION', 'CONTACT', 'ISRC']

  # Method for outputting tags and their corresponding values. Uses dynamic
  # spacing based on the longest tag in the constant.
  def output(tag, value)
    spacing = ' ' *
      (TAGS.map { |e| e.to_s.size }.max + 2 - tag.length)

    puts '  ' + colcyn(tag) + spacing + colcyn(value)
  end

  # Method for initialising a new object.
  def initialize(file)
    @file = file
    @tags = Hash.new

    TAGS.each do |tag|
      # Obtain value of tag and skip to the next tag field if it is empty.
      value = read_tag(tag)
      next if value.empty?

      # Split value into an array if there is more than one field of the same
      # type.
      if value.include? "\n"
        value = value.split("\n")
        (0 .. (value.length - 1)).each do |i|
          value[i].sub!(tag + '=', '')
        end
      else
        value.sub!(tag + '=', '')
      end

      @tags[tag] = value
    end
  end

  # Method for writing tags.
  def hash_write
    # Clear file of existing tags.
    clear_tags

    # Write tags to file.
    @tags.each do |tag, value|
      value = [value] if value.kind_of?(String)
      value.each do |value|
        write_tag(tag, value)
      end
    end
  end

  # Method for displaying all tags.
  def view
    raise 'No tags are set.' if @tags.empty?

    @tags.each do |tag, value|
      value = [value] if value.kind_of?(String)
      value.each do |value|
        output(tag, value)
      end
    end
  end

  # Method for displaying certain tags.
  def view_tag(arg)
    arg.each do |arg|
      # Process exceptions within the argument loop, as using the exception in
      # the file loop may end the argument loop prematurely.
      begin
        tag = arg.upcase
        raise tag + ' is not a valid tag.' unless TAGS.include?(tag)

        value = @tags[tag]
        raise tag + ' tag is not set.' if value.nil?

        value = [value] if value.kind_of?(String)
        value.each do |value|
          output(tag, value)
        end
      rescue RuntimeError => message
        warn(message)
      end
    end
  end

  # Method for setting tags.
  def set_tag(arg)
    status('Setting tags...')

    arg.each do |arg|
      # Process exceptions within the argument loop, as using the exception in
      # the file loop may end the argument loop prematurely.
      begin
        arg = arg.split('=', 2)
        tag = arg.first.upcase
        raise tag + ' is not a valid tag.' unless TAGS.include?(tag)

        if arg.length == 1
          value = ''
        else
          value = arg.last
        end

        @tags[tag] = value
        view_tag(tag)
      rescue RuntimeError => message
        warn(message)
      end
    end
  end

  # Method for generating new tags based on filename.
  def generate
    # Use only the basename of the file.
    value = File.basename(@file)
    # Substitute all underscores with a space and remove the file extension.
    value = value.gsub('_', ' ').sub(/\.(flac|ogg)$/, '')
    # Split the filename into an array with a maximum length of three elements.
    value = value.split(' - ', 3)

    # Determine which naming format the file uses.
    if value.length == 2
      tag = ['ARTIST', 'TITLE']
    elsif value.length == 3
      tag = ['TRACKNUMBER', 'ARTIST', 'TITLE']
    else
      raise 'Filename is not in a valid format.'
    end

    status('Generating tags...')

    (0 .. (value.length - 1)).each do |i|
      @tags[tag[i]] = value[i]
      view_tag(tag[i])
    end
  end

  # Method for removing all tags.
  def remove
    raise 'No tags are set.' if @tags.empty?
    status('Removing tags...')

    @tags.clear
  end

  # Method for removing certain tags.
  def remove_tag(arg)
    status('Removing tags...')

    arg.each do |arg|
      # Process exceptions within the argument loop, as using the exception in
      # the file loop may end the argument loop prematurely.
      begin
        tag = arg.upcase
        raise tag + ' is not a valid tag.' unless TAGS.include?(tag)
        raise tag + ' tag is not set.' unless @tags.include?(tag)

        @tags.delete(tag)
      rescue RuntimeError => message
        warn(message)
      end
    end
  end

  # Method for renaming files based on tags.
  def rename
    unless @tags.has_key?('ARTIST')
      raise 'Missing ARTIST tag.'
    end
    unless @tags.has_key?('TITLE')
      raise 'Missing TITLE tag.'
    end

    # Determine what the new filename should be.
    ext = file.split('.').last.downcase
    file = File.dirname(@file) + '/'
    if @tags.has_key?('TRACKNUMBER')
      file = file + @tags['TRACKNUMBER'] + ' - '
    end
    file = file + @tags['ARTIST'] + ' - ' +
      @tags['TITLE'] + '.' + ext

    # Raise an error if the new and old filenames are identical.
    if File.basename(@file) == File.basename(file)
      raise 'Generated filename and current filename are identical.'
    end

    status('Renaming to ' + file.sub(/^\.\//, '') + '...')
    File.rename(@file, file)
  end
end

# Subclass of VorbisComments containing methods unique to FLAC files.
class FLAC < VorbisComments
  def read_tag(tag)
    %x(metaflac --show-tag=#{tag} -- '#{esc(@file)}').chomp
  end

  def clear_tags
    %x{metaflac --remove-all-tags -- '#{esc(@file)}'}
  end

  def write_tag(tag, value)
    %x{metaflac --set-tag=#{tag}='#{esc(value)}' -- '#{esc(@file)}'}
  end
end

# Subclass of VorbisComments containing methods unique to Vorbis files.
class Vorbis < VorbisComments
  def read_tag(tag)
    %x(vorbiscomment -l -- '#{esc(@file)}' | grep '#{tag}').chomp
  end

  def clear_tags
    %x{vorbiscomment -w -t '' -- '#{esc(@file)}' 2>/dev/null}
  end

  def write_tag(tag, value)
    %x{vorbiscomment -a -t #{tag}='#{esc(value)}' -- '#{esc(@file)}'}
  end
end

# Class for ID3 tags; used by MP3 files.
class ID3
  attr_reader :file, :tags

  # Create constant hash containing possible tag names, and mapping them to
  # their corresponding frame names.
  TAGS = {
    'TITLE'   => :TIT2,
    'ALBUM'   => :TALB,
    'TRACK'   => :TRCK,
    'ARTIST'  => :TPE1,
    'YEAR'    => :TYER,
    'COMMENT' => :COMM
  }

  # Method for outputting tags and their corresponding values. Uses dynamic
  # spacing based on the longest tag in the constant.
  def output(tag, value)
    spacing = ' ' *
      (TAGS.map { |e| e.to_s.size }.max + 2 - tag.length)

    puts '  ' + colcyn(tag) + spacing + colcyn(value)
  end

  # Method for initialising a new object.
  def initialize(file)
    @file = file
    @tags = ID3Lib::Tag.new(@file)
  end

  # Method for writing tags.
  def hash_write
    if @tags.empty? or (@tags.length == 1 and @tags.frame_text(:TLEN))
      @tags.strip!
    else
      @tags.update!
    end
  end

  # Method for displaying all tags.
  def view
    raise 'No tags are set.' if @tags.empty?

    TAGS.each { |tag, frame|
      value = @tags.frame_text(frame)
      output(tag, value) unless value.nil?
    }
  end

  # Method for displaying certain tags.
  def view_tag(arg)
    arg.each do |arg|
      # Process exceptions within the argument loop, as using the exception in
      # the file loop may end the argument loop prematurely.
      begin
        tag = arg.upcase
        raise tag + ' is not a valid tag.' unless TAGS.has_key?(tag)

        value = @tags.frame_text(TAGS[tag])
        raise tag + ' tag is not set.' if value.nil?

        output(tag, value)
      rescue RuntimeError => message
        warn(message)
      end
    end
  end

  # Method for setting tags.
  def set_tag(arg)
    status('Setting tags...')

    arg.each do |arg|
      # Process exceptions within the argument loop, as using the exception in
      # the file loop may end the argument loop prematurely.
      begin
        arg = arg.split('=', 2)
        tag = arg.first.upcase
        raise tag + ' is not a valid tag.' unless TAGS.has_key?(tag)

        if arg.length == 1
          value = ''
        else
          value = arg.last
        end

        @tags.set_frame_text(TAGS[tag], value)
        view_tag(tag)
      rescue RuntimeError => message
        warn(message)
      end
    end
  end

  # Method for generating new tags based on filename.
  def generate
    # Use only the basename of the file.
    value = File.basename(@file)
    # Substitute all underscores with a space and remove the file extension.
    value = value.gsub('_', ' ').sub(/\.mp3$/, '')
    # Split the filename into an array with a maximum length of three elements.
    value = value.split(' - ', 3)

    # Determine which naming format the file uses.
    if value.length == 2
      tag = ['ARTIST', 'TITLE']
    elsif value.length == 3
      tag = ['TRACK', 'ARTIST', 'TITLE']
    else
      raise 'Filename is not in a valid format.'
    end

    status('Generating tags...')

    (0 .. (value.length - 1)).each do |i|
      @tags.set_frame_text(TAGS[tag[i]], value[i])
      view_tag(tag[i])
    end
  end

  # Method for removing all tags.
  def remove
    raise 'No tags are set.' if @tags.empty?
    status('Removing tags...')

    @tags.clear
  end

  # Method for removing certain tags.
  def remove_tag(arg)
    status('Removing tags...')

    arg.each do |arg|
      # Process exceptions within the argument loop, as using the exception in
      # the file loop may end the argument loop prematurely.
      begin
        tag = arg.upcase
        raise tag + ' is not a valid tag.' unless TAGS.has_key?(tag)
        raise tag + ' tag is not set.' if @tags.frame_text(TAGS[tag]).nil?

        @tags.remove_frame(TAGS[tag])
      rescue RuntimeError => message
        warn(message)
      end
    end
  end

  # Method for renaming files based on tags.
  def rename
    if @tags.frame_text(TAGS['ARTIST']).nil?
      raise 'Missing ARTIST tag.'
    end
    if @tags.frame_text(TAGS['TITLE']).nil?
      raise 'Missing TITLE tag.'
    end

    # Determine what the new filename should be.
    ext = file.split('.').last.downcase
    file = File.dirname(@file) + '/'
    unless @tags.frame_text(TAGS['TRACK']).nil?
      file = file + @tags.frame_text(TAGS['TRACK']) + ' - '
    end
    file = file + @tags.frame_text(TAGS['ARTIST']) + ' - ' +
      @tags.frame_text(TAGS['TITLE']) + '.' + ext

    # Raise an error if the new and old filenames are identical.
    if File.basename(@file) == File.basename(file)
      raise 'Generated filename and current filename are identical.'
    end

    status('Renaming to ' + file.sub(/^\.\//, '') + '...')
    File.rename(@file, file)
  end
end

# Display program help if help action is set, or if no actions are set.
if opts.has_key?('help') or !action
  help
  exit 0
end

# Treat all remaining arguments as files.
warn('No files specified.') if ARGV.length.zero?
ARGV.each do |file|
  # Process exceptions in order to produce error messages in a custom format
  # without an excessive number of nested if statements.
  begin
    # Output name of the current file.
    puts colyel(file)

    # Verify that the file exists.
    raise 'File does not exist.' unless File.exist?(file)

    # Determine whether or not the file is supported.
    raise 'File has no extension.' if file.split('.').length == 1
    ext = file.split('.').last.downcase
    raise 'Not a supported file format.' unless ext =~ /flac|ogg|mp3/

    # Create track variable based on the file format.
    if ext == 'flac'
      track = FLAC.new(file)
    elsif ext == 'ogg'
      track = Vorbis.new(file)
    elsif ext == 'mp3'
      track = ID3.new(file)
    end

    # Call methods based on the actions set.
    if opts.has_key?('set-tag')
      track.set_tag(opts['set-tag'])
      track.hash_write
    end

    if opts.has_key?('remove')
      track.remove
      track.hash_write
    elsif opts.has_key?('remove-tag')
      track.remove_tag(opts['remove-tag'])
      track.hash_write
    end

    if opts.has_key?('preview')
      track.generate
    elsif opts.has_key?('generate')
      track.generate
      track.hash_write
    elsif opts.has_key?('rename')
      track.rename
    end

    if opts.has_key?('view')
      track.view
    elsif opts.has_key?('view-tag')
      track.view_tag(opts['view-tag'])
    end
  rescue RuntimeError => message
    warn(message)
  end
end