File: AFTTagger.cpp

package info (click to toggle)
amarok 2.8.0-2.1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 81,164 kB
  • ctags: 25,507
  • sloc: cpp: 211,252; ansic: 2,629; xml: 982; ruby: 62; python: 54; perl: 27; makefile: 19; sh: 9
file content (810 lines) | stat: -rw-r--r-- 29,890 bytes parent folder | download | duplicates (2)
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
/*
 *  Copyright (c) 2008-2009 Jeff Mitchell <mitchell@kde.org>
 *  Qt4QStringToTString and TStringToQString macros Copyright 2002-2008 by Scott Wheeler, wheeler@kde.org, licensed under LGPL 2.1
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include "AFTTagger.h"
#include "SafeFileSaver.h"

//Taglib
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wnon-virtual-dtor"
#include <apetag.h>
#include <fileref.h>
#include <flacfile.h>
#include <id3v2tag.h>
#include <mp4tag.h>
#include <mpegfile.h>
#include <oggfile.h>
#include <oggflacfile.h>
#include <speexfile.h>
#include <tstringlist.h>
#include <tfile.h>
#include <uniquefileidentifierframe.h>
#include <vorbisfile.h>
#include <xiphcomment.h>
#pragma GCC diagnostic pop

#include <QtDebug>
#include <QCryptographicHash>
#include <QDir>
#include <QFileInfo>
#include <QString>
#include <QTextStream>

#include <iostream>

//QT4-happy versions
#define Qt4QStringToTString(s) TagLib::String(s.toUtf8().data(), TagLib::String::UTF8)

static int s_currentVersion = 1;

int main( int argc, char *argv[] )
{
    AFTTagger tagger( argc, argv );
    return tagger.exec();
}

AFTTagger::AFTTagger( int &argc, char **argv )
    :QCoreApplication( argc, argv )
    , m_delete( false )
    , m_newid( false )
    , m_quiet( false )
    , m_recurse( false )
    , m_verbose( false )
    , m_fileFolderList()
    , m_time()
    , m_textStream( stderr )
{

    setObjectName( "amarok_afttagger" );

    readArgs();

    QString terms;
    if( !m_quiet )
    {
        m_textStream << qPrintable( tr( "TERMS OF USE:\n\n" 
                "This program has been extensively tested and errs on the side of safety wherever possible.\n\n"
                "With that being said, since this program can modify thousands or hundreds of thousands of files\n"
                "at a time, here is the obligatory warning text:\n\n"
                "This program makes use of multiple libraries not written by the author, and as such neither\n"
                "the author nor the Amarok project can or do take any responsibility for any damage that may\n"
                "occur to your files through the use of this program.\n\n"
                "If you want more information, please see http://community.kde.org/Amarok/Development/AFT\n\n"
                "If you agree to be bound by these terms of use, enter 'y' or 'Y', or anything else to exit:\n" ) );

        m_textStream.flush();
        std::string response;
        std::cin >> response;
        std::cin.get();

        if( response != "y" && response != "Y")
        {
            m_textStream << tr( "INFO: Terms not accepted; exiting..." ) << endl;
            ::exit( 1 );
        }
    }

    qsrand(QDateTime::currentDateTime().toTime_t());
    m_time.start();

    foreach( const QString &path, m_fileFolderList )
        processPath( path );

    m_textStream << tr( "INFO: All done, exiting..." ) << endl;
    ::exit( 0 );
}

void
AFTTagger::processPath( const QString &path )
{
    QFileInfo info( path );
    if( !info.isDir() && !info.isFile() )
    {
        if( m_verbose )
            m_textStream << tr( "INFO: Skipping %1 because it is neither a directory nor file." ).arg( path ) << endl;
        return;
    }
    if( info.isDir() )
    {
        if( !m_recurse )
        {
            if( m_verbose )
               m_textStream << tr( "INFO: Skipping %1 because it is a directory and recursion is not specified." ).arg( path ) << endl;
            return;
        }
        else
        {
            if( m_verbose )
                m_textStream << tr( "INFO: Processing directory %1" ).arg( path ) << endl;
            foreach( const QString &pathEntry, QDir( path ).entryList() )
            {
                if( pathEntry != "." && pathEntry != ".." )
                    processPath( QDir( path ).canonicalPath() + '/' +  pathEntry );
            }
        }
    }
    else //isFile()
    {
        QString filePath = info.absoluteFilePath();


#ifdef COMPLEX_TAGLIB_FILENAME
    const wchar_t *encodedName = reinterpret_cast< const wchar_t *>(filePath.utf16());
#else
    QByteArray fileName = QFile::encodeName( filePath );
    const char *encodedName = fileName.constData();
#endif

        TagLib::FileRef fileRef = TagLib::FileRef( encodedName, true, TagLib::AudioProperties::Fast );

        if( fileRef.isNull() )
        {
            if( m_verbose )
                m_textStream << tr( "INFO: file %1 not able to be opened by TagLib" ).arg( filePath ) << endl;
            return;
        }

        m_textStream << tr( "INFO: Processing file %1" ).arg( filePath ) << endl;

        SafeFileSaver sfs( filePath );
        sfs.setVerbose( false );
        sfs.setPrefix( "amarok-afttagger" );
        QString tempFilePath = sfs.prepareToSave();
        if( tempFilePath.isEmpty() )
        {
            m_textStream << tr( "Error: could not create temporary file when processing %1" ).arg( filePath ) << endl;
            return;
        }

        if( m_verbose )
            m_textStream << tr( "INFO: Temporary file is at %1").arg( tempFilePath ) << endl;

#ifdef COMPLEX_TAGLIB_FILENAME
    const wchar_t *encodedName = reinterpret_cast< const wchar_t * >(tempFilePath.utf16());
#else
    QByteArray tempFileName = QFile::encodeName( tempFilePath );
    const char *tempEncodedName = tempFileName.constData();
#endif

        bool saveNecessary = false;

        TagLib::FileRef tempFileRef = TagLib::FileRef( tempEncodedName, true, TagLib::AudioProperties::Fast );
        if( TagLib::MPEG::File *file = dynamic_cast<TagLib::MPEG::File *>( tempFileRef.file() ) )
            saveNecessary = handleMPEG( file );
        else if( TagLib::Ogg::File *file = dynamic_cast<TagLib::Ogg::File *>( tempFileRef.file() ) )
            saveNecessary = handleOgg( file );
        else if( TagLib::FLAC::File *file = dynamic_cast<TagLib::FLAC::File *>( tempFileRef.file() ) )
            saveNecessary = handleFLAC( file );
        else if( TagLib::MPC::File *file = dynamic_cast<TagLib::MPC::File *>( tempFileRef.file() ) )
            saveNecessary = handleMPC( file );
        else if( TagLib::MP4::File *file = dynamic_cast<TagLib::MP4::File *>( tempFileRef.file() ) )
            saveNecessary = handleMP4( file );
        else
        {
            if( m_verbose )
                m_textStream << tr( "INFO: File not able to be parsed by TagLib or wrong kind (currently this program only supports MPEG, Ogg MP4, MPC, and FLAC files), cleaning up temp file" ) << endl;
            if( !sfs.cleanupSave() )
                m_textStream << tr( "WARNING: file at %1 could not be cleaned up; check for strays" ).arg( filePath ) << endl;
            return;
        }
        if( saveNecessary )
        {
            if( m_verbose )
                m_textStream << tr( "INFO: Safe-saving file" ) << endl;
            if( !sfs.doSave() )
                m_textStream << tr( "WARNING: file at %1 could not be saved" ).arg( filePath ) << endl;
        }
        if( m_verbose )
            m_textStream << tr( "INFO: Cleaning up..." ) << endl;
        if( !sfs.cleanupSave() )
            m_textStream << tr( "WARNING: file at %1 could not be cleaned up; check for strays" ).arg( filePath ) << endl;
        return;
    }
}

bool
AFTTagger::handleMPEG( TagLib::MPEG::File *file )
{
    if( file->readOnly() )
    {
        m_textStream << tr( "ERROR: File is read-only or could not be opened" ) << endl;
        return false;
    }

    QString uid;
    bool newUid = false;
    bool nothingfound = true;
    if( m_verbose )
        m_textStream << tr( "INFO: File is a MPEG file, opening..." ) << endl;
    if ( file->ID3v2Tag( true ) )
    {
        if( file->ID3v2Tag()->frameListMap()["UFID"].isEmpty() )
        {
            if( m_verbose )
                m_textStream << tr( "INFO: No UFID frames found" ) << endl;

            if( m_delete )
                return false;

            newUid = true;
        }
        else
        {
            if( m_verbose )
                m_textStream << tr( "INFO: Found existing UFID frames, parsing" )  << endl;
            TagLib::ID3v2::FrameList frameList = file->ID3v2Tag()->frameListMap()["UFID"];
            TagLib::ID3v2::FrameList::Iterator iter;
            if( m_verbose )
                m_textStream << tr( "INFO: Frame list size is %1" ).arg( frameList.size() ) << endl;
            for( iter = frameList.begin(); iter != frameList.end(); ++iter )
            {
                TagLib::ID3v2::UniqueFileIdentifierFrame* currFrame = dynamic_cast<TagLib::ID3v2::UniqueFileIdentifierFrame*>(*iter);
                if( currFrame )
                {
                    QString owner = TStringToQString( currFrame->owner() ).toUpper();
                    if( owner.startsWith( "AMAROK - REDISCOVER YOUR MUSIC" ) )
                    {
                        nothingfound = false;
                        if( m_verbose )
                            m_textStream << tr( "INFO: Removing old-style ATF identifier" ) << endl;

                        iter = frameList.erase( iter );
                        file->ID3v2Tag()->removeFrame( currFrame );
                        file->save();
                        if( !m_delete )
                            newUid = true;
                        else
                            return true;
                    }
                    if( owner.startsWith( "AMAROK 2 AFT" ) )
                    {
                        nothingfound = false;
                        if( m_verbose )
                            m_textStream << tr( "INFO: Found an existing AFT identifier: %1" ).arg( TStringToQString( TagLib::String( currFrame->identifier() ) ) ) << endl;

                        if( m_delete )
                        {
                            iter = frameList.erase( iter );
                            if( m_verbose )
                                m_textStream << tr( "INFO: Removing current AFT frame" ) << endl;
                            file->ID3v2Tag()->removeFrame( currFrame );
                            file->save();
                            return true;
                        }

                        int version = owner.at( 13 ).digitValue();
                        if( version < s_currentVersion )
                        {
                            if( m_verbose )
                                m_textStream << tr( "INFO: Upgrading AFT identifier from version %1 to version %2" ).arg( version, s_currentVersion ) << endl;
                            uid = upgradeUID( version, TStringToQString( TagLib::String( currFrame->identifier() ) ) );
                            if( m_verbose )
                                m_textStream << tr( "INFO: Removing current AFT frame" ) << endl;
                            iter = frameList.erase( iter );
                            file->ID3v2Tag()->removeFrame( currFrame );
                            newUid = true;
                        }
                        else if( version == s_currentVersion && m_newid )
                        {
                            if( m_verbose )
                                m_textStream << tr( "INFO: New IDs specified to be generated, doing so" ) << endl;
                            iter = frameList.erase( iter );
                            file->ID3v2Tag()->removeFrame( currFrame );
                            newUid = true;
                        }
                        else
                        {
                            if( m_verbose )
                                m_textStream << tr( "INFO: ID is current" ) << endl;
                        }
                    }
                }
            }
        }
        if( newUid || ( nothingfound && !m_delete ) )
        {
            QString ourId = QString( "Amarok 2 AFTv" + QString::number( s_currentVersion ) + " - amarok.kde.org" );
            if( uid.isEmpty() )
                uid = createCurrentUID( file );
            if( m_verbose )
                m_textStream << tr( "INFO: Adding new frame and saving file with UID: %1" ).arg( uid ) << endl;
            file->ID3v2Tag()->addFrame( new TagLib::ID3v2::UniqueFileIdentifierFrame(
                Qt4QStringToTString( ourId ), Qt4QStringToTString( uid ).data( TagLib::String::Latin1 ) ) );
            file->save();
            return true;
        }
    }
    return false;
}

bool
AFTTagger::handleOgg( TagLib::Ogg::File *file )
{
    if( file->readOnly() )
    {
        m_textStream << tr( "ERROR: File is read-only or could not be opened" ) << endl;
        return false;
    }

    TagLib::Ogg::XiphComment *comment = dynamic_cast<TagLib::Ogg::XiphComment *>( file->tag() );

    if( !comment )
        return false;

    if( handleXiphComment( comment, file ) )
    {
        file->save();
        return true;
    }

    return false;
}

bool
AFTTagger::handleFLAC( TagLib::FLAC::File *file )
{
    if( file->readOnly() )
    {
        m_textStream << tr( "ERROR: File is read-only or could not be opened" ) << endl;
        return false;
    }

    TagLib::Ogg::XiphComment *comment = file->xiphComment( true );
    if( !comment )
        return false;

    if( handleXiphComment( comment, file ) )
    {
        file->save();
        return true;
    }

    return false;
}

bool
AFTTagger::handleXiphComment( TagLib::Ogg::XiphComment *comment, TagLib::File *file )
{
    QString uid;
    bool newUid = false;
    bool nothingfound = true;
    TagLib::StringList toRemove;
    if( m_verbose )
        m_textStream << tr( "INFO: File has a XiphComment, opening..." ) << endl;

    if( comment->fieldListMap().isEmpty() )
    {
        if( m_verbose )
            m_textStream << tr( "INFO: No fields found in XiphComment" ) << endl;

        if( m_delete )
            return false;
    }
    else
    {
        if( m_verbose )
            m_textStream << tr( "INFO: Found existing XiphComment frames, parsing" )  << endl;
        TagLib::Ogg::FieldListMap fieldListMap = comment->fieldListMap();

        if( m_verbose )
            m_textStream << tr( "INFO: fieldListMap size is %1" ).arg( fieldListMap.size() ) << endl;

        TagLib::Ogg::FieldListMap::Iterator iter;
        for( iter = fieldListMap.begin(); iter != fieldListMap.end(); ++iter )
        {
            TagLib::String key = iter->first;
            QString qkey = TStringToQString( key ).toUpper();
            if( qkey.startsWith( "AMAROK - REDISCOVER YOUR MUSIC" ) )
            {
                nothingfound = false;

                if( m_verbose )
                    m_textStream << tr( "INFO: Removing old-style ATF identifier %1" ).arg( qkey ) << endl;

                toRemove.append( key );
                if( !m_delete )
                    newUid = true;
            }
            else if( qkey.startsWith( "AMAROK 2 AFT" ) )
            {
                nothingfound = false;

                if( m_verbose )
                    m_textStream << tr( "INFO: Found an existing AFT identifier: %1" ).arg( qkey ) << endl;

                if( m_delete )
                {
                    toRemove.append( key );
                    if( m_verbose )
                        m_textStream << tr( "INFO: Removing current AFT frame" ) << endl;
                }
                else
                {
                    int version = qkey.at( 13 ).digitValue();
                    if( m_verbose )
                        m_textStream << tr( "INFO: AFT identifier is version %1" ).arg( version ) << endl;
                    if( version < s_currentVersion )
                    {
                        if( m_verbose )
                            m_textStream << tr( "INFO: Upgrading AFT identifier from version %1 to version %2" ).arg( version, s_currentVersion ) << endl;
                        uid = upgradeUID( version, TStringToQString( fieldListMap[key].front() ) );
                        if( m_verbose )
                            m_textStream << tr( "INFO: Removing current AFT frame" ) << endl;
                        toRemove.append( key );
                        newUid = true;
                    }
                    else if( version == s_currentVersion && m_newid )
                    {
                        if( m_verbose )
                            m_textStream << tr( "INFO: New IDs specified to be generated, doing so" ) << endl;
                        toRemove.append( key );
                        newUid = true;
                    }
                    else
                    {
                        if( m_verbose )
                            m_textStream << tr( "INFO: ID is current" ) << endl;
                        return false;
                    }
                }
            }
        }
        for( TagLib::StringList::ConstIterator iter = toRemove.begin(); iter != toRemove.end(); ++iter )
            comment->removeField( *iter );
    }
    if( newUid || ( nothingfound && !m_delete ) )
    {
        QString ourId = QString( "Amarok 2 AFTv" + QString::number( s_currentVersion ) + " - amarok.kde.org" );
        if( uid.isEmpty() )
            uid = createCurrentUID( file );
        if( m_verbose )
            m_textStream << tr( "INFO: Adding new field and saving file with UID: %1" ).arg( uid ) << endl;
        comment->addField( Qt4QStringToTString( ourId ), Qt4QStringToTString( uid ) );
        return true;
    }
    else if( toRemove.size() )
        return true;

    return false;
}

bool
AFTTagger::handleMPC( TagLib::MPC::File *file )
{
    if( file->readOnly() )
    {
        m_textStream << tr( "ERROR: File is read-only or could not be opened" ) << endl;
        return false;
    }

    QString uid;
    bool newUid = false;
    bool nothingfound = true;
    TagLib::StringList toRemove;
    if( m_verbose )
        m_textStream << tr( "INFO: File is a MPC file, opening..." ) << endl;

    if( file->APETag() )
    {
        const TagLib::APE::ItemListMap &itemsMap = file->APETag()->itemListMap();
        if( itemsMap.isEmpty() )
        {
          m_textStream << tr( "INFO: No fields found in APE tags." ) << endl;

          if( m_delete )
              return false;
        }

        for( TagLib::APE::ItemListMap::ConstIterator it = itemsMap.begin(); it != itemsMap.end(); ++it )
        {
            TagLib::String key = it->first;
            QString qkey = TStringToQString( key ).toUpper();
            if( qkey.startsWith( "AMAROK - REDISCOVER YOUR MUSIC" ) )
            {
                nothingfound = false;

                if( m_verbose )
                    m_textStream << tr( "INFO: Removing old-style ATF identifier %1" ).arg( qkey ) << endl;

                toRemove.append( key );
                if( !m_delete )
                    newUid = true;
            }
            else if( qkey.startsWith( "AMAROK 2 AFT" ) )
            {
                nothingfound = false;

                if( m_verbose )
                    m_textStream << tr( "INFO: Found an existing AFT identifier: %1" ).arg( qkey ) << endl;

                if( m_delete )
                {
                    toRemove.append( key );
                    if( m_verbose )
                        m_textStream << tr( "INFO: Removing current AFT frame" ) << endl;
                }
                else
                {
                    int version = qkey.at( 13 ).digitValue();
                    if( m_verbose )
                        m_textStream << tr( "INFO: AFT identifier is version %1" ).arg( version ) << endl;
                    if( version < s_currentVersion )
                    {
                        if( m_verbose )
                            m_textStream << tr( "INFO: Upgrading AFT identifier from version %1 to version %2" ).arg( version, s_currentVersion ) << endl;
                        uid = upgradeUID( version, TStringToQString( itemsMap[ key ].toString() ) );
                        if( m_verbose )
                            m_textStream << tr( "INFO: Removing current AFT frame" ) << endl;
                        toRemove.append( key );
                        newUid = true;
                    }
                    else if( version == s_currentVersion && m_newid )
                    {
                        if( m_verbose )
                            m_textStream << tr( "INFO: New IDs specified to be generated, doing so" ) << endl;
                        toRemove.append( key );
                        newUid = true;
                    }
                    else
                    {
                        if( m_verbose )
                            m_textStream << tr( "INFO: ID is current" ) << endl;
                        return false;
                    }
                }
            }
        }
        for( TagLib::StringList::ConstIterator it = toRemove.begin(); it != toRemove.end(); ++it )
            file->APETag()->removeItem( *it );
    }

    if( newUid || ( nothingfound && !m_delete ) )
    {
        QString ourId = QString( "Amarok 2 AFTv" + QString::number( s_currentVersion ) + " - amarok.kde.org" );
        if( uid.isEmpty() )
            uid = createCurrentUID( file );
        if( m_verbose )
            m_textStream << tr( "INFO: Adding new field and saving file with UID: %1" ).arg( uid ) << endl;
        file->APETag()->addValue( Qt4QStringToTString( ourId.toUpper() ), Qt4QStringToTString( uid ) );
        file->save();
        return true;
    }
    else if( toRemove.size() )
    {
        file->save();
        return true;
    }

    return false;
}

bool
AFTTagger::handleMP4( TagLib::MP4::File *file )
{
    if( file->readOnly() )
    {
        m_textStream << tr( "ERROR: File is read-only or could not be opened" ) << endl;
        return false;
    }

    QString uid;
    bool newUid = false;
    bool nothingfound = true;
    TagLib::StringList toRemove;
    if( m_verbose )
        m_textStream << tr( "INFO: File is a MP4 file, opening..." ) << endl;

    TagLib::MP4::ItemListMap &itemsMap = file->tag()->itemListMap();
    if( !itemsMap.isEmpty() )
    {
        for( TagLib::MP4::ItemListMap::Iterator it = itemsMap.begin(); it != itemsMap.end(); ++it )
        {
            TagLib::String key = it->first;
            TagLib::String ukey = key.upper();
            if( ukey.find( "AMAROK - REDISCOVER YOUR MUSIC" ) != -1 )
            {
                nothingfound = false;

                if( m_verbose )
                    m_textStream << tr( "INFO: Removing old-style ATF identifier %1" ).arg( key.toCString() ) << endl;

                toRemove.append( key );
                if( !m_delete )
                    newUid = true;
            }
            else if( ukey.find( "AMAROK 2 AFT" ) != -1 )
            {
                nothingfound = false;

                if( m_verbose )
                    m_textStream << tr( "INFO: Found an existing AFT identifier: %1" ).arg( key.toCString() ) << endl;

                if( m_delete )
                {
                    toRemove.append( key );
                    if( m_verbose )
                        m_textStream << tr( "INFO: Removing current AFT frame" ) << endl;
                }
                else
                {
                    int version = TStringToQString( ukey ).at( 13 ).digitValue();
                    if( m_verbose )
                        m_textStream << tr( "INFO: AFT identifier is version %1" ).arg( version ) << endl;
                    if( version < s_currentVersion )
                    {
                        if( m_verbose )
                            m_textStream << tr( "INFO: Upgrading AFT identifier from version %1 to version %2" ).arg( version, s_currentVersion ) << endl;
                        uid = upgradeUID( version, TStringToQString( itemsMap[ key ].toStringList().toString() ) );
                        if( m_verbose )
                            m_textStream << tr( "INFO: Removing current AFT frame" ) << endl;
                        toRemove.append( key );
                        newUid = true;
                    }
                    else if( version == s_currentVersion && m_newid )
                    {
                        if( m_verbose )
                            m_textStream << tr( "INFO: New IDs specified to be generated, doing so" ) << endl;
                        toRemove.append( key );
                        newUid = true;
                    }
                    else
                    {
                        if( m_verbose )
                            m_textStream << tr( "INFO: ID is current" ) << endl;
                        return false;
                    }
                }
            }
        }
        for( TagLib::StringList::ConstIterator it = toRemove.begin(); it != toRemove.end(); ++it )
            itemsMap.erase( *it );
    }

    if( newUid || ( nothingfound && !m_delete ) )
    {
        QString ourId = QString( "Amarok 2 AFTv" + QString::number( s_currentVersion ) + " - amarok.kde.org" );
        if( uid.isEmpty() )
            uid = createCurrentUID( file );
        if( m_verbose )
            m_textStream << tr( "INFO: Adding new field and saving file with UID: %1" ).arg( uid ) << endl;
        itemsMap.insert( Qt4QStringToTString( QString( "----:com.apple.iTunes:" + ourId ) ),
                         TagLib::StringList( Qt4QStringToTString( uid ) ) );
        file->save();
        return true;
    }
    else if( toRemove.size() )
    {
        file->save();
        return true;
    }

    return false;
}



QString
AFTTagger::createCurrentUID( TagLib::File *file )
{
    return createV1UID( file );
}

QString
AFTTagger::createV1UID( TagLib::File *file )
{
    QCryptographicHash md5( QCryptographicHash::Md5 );
    QByteArray size;
    md5.addData( size.setNum( (qulonglong)(file->length()) ) );
    md5.addData( QString::number( m_time.elapsed() ).toAscii() );
    md5.addData( QString::number( qrand() ).toAscii() );
    md5.addData( QString::number( qrand() ).toAscii() );
    md5.addData( QString::number( qrand() ).toAscii() );
    md5.addData( QString::number( qrand() ).toAscii() );
    md5.addData( QString::number( qrand() ).toAscii() );
    md5.addData( QString::number( m_time.elapsed() ).toAscii() );
    return QString( md5.result().toHex() );
}

QString
AFTTagger::upgradeUID( int version, QString currValue )
{
    Q_UNUSED(version)
    return currValue + "abcd";
}

void
AFTTagger::readArgs()
{
    QStringList argslist = arguments();
    if( argslist.size() < 2 )
        displayHelp();
    bool nomore = false;
    int argnum = 0;
    foreach( const QString &arg, argslist )
    {
        ++argnum;
        if( arg.isEmpty() || argnum == 1 )
            continue;
        if( nomore )
        {
            m_fileFolderList.append( arg );
        }
        else if( arg.startsWith( "--" ) )
        {
            QString myarg = QString( arg ).remove( 0, 2 );
            if ( myarg == "recurse" || myarg == "recursively" )
                m_recurse = true;
            else if( myarg == "verbose" )
                m_verbose = true;
            else if( myarg == "quiet" )
                m_quiet = true;
            else if( myarg == "newid" )
                m_newid = true;
            else if( myarg == "delete" )
                m_delete = true;
            else
                displayHelp();
        }
        else if( arg.startsWith( '-' ) )
        {
            QString myarg = QString( arg ).remove( 0, 1 );
            int pos = 0;
            while( pos < myarg.length() )
            {
                if( myarg[pos] == 'd' )
                    m_delete = true;
                else if( myarg[pos] == 'n' )
                    m_newid = true;
                else if( myarg[pos] == 'q' )
                    m_quiet = true;
                else if( myarg[pos] == 'r' )
                    m_recurse = true;
                else if( myarg[pos] == 'v' )
                    m_verbose = true;
                else
                    displayHelp();

                ++pos;
            }
        }
        else
        {
            nomore = true;
            m_fileFolderList.append( arg );
        }
    }
}

void
AFTTagger::displayHelp()
{
    m_textStream << tr( "Amarok AFT Tagger" ) << endl << endl;
    m_textStream << tr( "IRC:\nserver: irc.freenode.net / channels: #amarok, #amarok.de, #amarok.es, #amarok.fr\n\nFeedback:\namarok@kde.org" ) << endl << endl;
    m_textStream << tr( "Usage: amarok_afttagger [options] +File/Folder(s)" ) << endl << endl;
    m_textStream << tr( "User-modifiable Options:" ) << endl;
    m_textStream << tr( "+File/Folder(s)       : Files or folders to tag" ) << endl;
    m_textStream << tr( "-h, --help            : This help text" ) << endl;
    m_textStream << tr( "-r, --recursive       : Process files and folders recursively" ) << endl;
    m_textStream << tr( "-d, --delete          : Remove AFT tag" ) << endl;
    m_textStream << tr( "-n  --newid           : Replace any existing ID with a new one" ) << endl;
    m_textStream << tr( "-v, --verbose         : Verbose output" ) << endl;
    m_textStream << tr( "-q, --quiet           : Quiet output; Implies that you accept the terms of use" ) << endl;
    m_textStream.flush();
    ::exit( 0 );
}