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 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
|
/*i----------------------------------------------------------------------------
libtunepimp -- The MusicBrainz tagging library.
Let a thousand taggers bloom!
Copyright (C) Robert Kaye 2003
This file is part of libtunepimp.
libtunepimp 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.
libtunepimp 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 libtunepimp; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
$Id: write.cpp 8421 2006-08-14 20:47:24Z luks $
----------------------------------------------------------------------------*/
#ifdef WIN32
# if _MSC_VER == 1200
# pragma warning(disable:4786)
# endif
# include <io.h>
# include <direct.h>
#else
# include <unistd.h>
# include <sys/stat.h>
# include <sys/types.h>
# include <fcntl.h>
# if defined(__APPLE__) || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
# include <sys/param.h>
# include <sys/mount.h>
# if (defined(__NetBSD__) && __NetBSD_Version__ >= 299000900)
# define HAVE_STATVFS 1
# endif
# else
# include <sys/vfs.h>
# endif
#endif
#include <ctype.h>
#include <errno.h>
#include <algorithm>
#include "../config.h"
#include "write.h"
#include "tunepimp.h"
#include "fileio.h"
#include "utf8/utf8util.h"
#if defined(HAVE_STATVFS)
# define statfs statvfs
# define f_bsize f_frsize
#endif
#ifdef WIN32
const char *dirSep = "\\";
const char dirSepChar = '\\';
const char *disallowedFileNameChars = "\"*/:<>?|";
#else
const char *dirSep = "/";
const char dirSepChar = '/';
const char *disallowedFileNameChars = "\"*:<>?|";
#endif
#define DB printf("%s:%d\n", __FILE__, __LINE__);
const int numRepVars = 21;
const char *repVars[numRepVars] = {"%abc3", "%artist", "%country", "%day",
"%format", "%l", "%month", "%0num", "%num",
"%sortname", "%status", "%track", "%type", "%u", "%year", "%abc2", "%abc",
"%albumartistsortname", "%albumartist", "%albumtracks", "%album"};
/* This set of variables removes the %abc2 and %abc3 that are made redundant by the %#%abc notation.
* Removing these will break backward compatibility with the older tagger.
const int numRepVars = 16;
const char *repVars[numRepVars] = {"%abc", "%album", "%artist", "%country", "%day",
"%format", "%l", "%month", "%0num", "%num",
"%sortname", "%status", "%track", "%type", "%u", "%year"};
*/
//---------------------------------------------------------------------------
void FileNameMaker::toLower(string &text)
{
transform(text.begin(), text.end(), text.begin(), (int(*)(int)) tolower);
}
void FileNameMaker::toUpper(string &text)
{
transform(text.begin(), text.end(), text.begin(), (int(*)(int)) toupper);
}
void FileNameMaker::makeNewFileName(const Metadata &dataArg,
string &fileName,
int index)
{
Metadata data = dataArg;
string name, origPath, origFile, ext, allowedFileChars, rep;
string::size_type i;
int numCharsLeft, varCount = 0, varLen;
origPath = extractFilePath(fileName);
origFile = extractFileName(fileName);
ext = extractFileExt(fileName);
if (data.variousArtist)
name = context->getVariousFileMask();
else if (data.nonAlbum)
name = context->getNonAlbumFileMask();
else
name = context->getFileMask();
allowedFileChars = context->getAllowedFileCharacters();
if (data.sortName.empty())
data.sortName = data.artist;
if (data.albumArtist.empty())
data.albumArtist = data.album;
if (data.albumArtistSortName.empty())
data.albumArtistSortName = data.sortName;
numCharsLeft = context->getMaxFileNameLen() - ext.length();
if (numCharsLeft > 0)
{
if (context->getMoveFiles())
numCharsLeft -= context->getDestDir().length() + 1;
else
numCharsLeft -= origPath.length() + 1;
int varLength = 0;
// Preparse the file spec and see how to allocate space to ensure everything
// fits into the space we have for a filename.
for(i = 0; i < name.length(); i++)
{
if (name[i] != '%')
{
numCharsLeft--;
continue;
}
bool varFound = false;
for(int j = 0; j != numRepVars && !varFound; j++)
{
char num[10];
if (strncmp(name.c_str() + i, repVars[j], strlen(repVars[j])) == 0)
{
switch(j)
{
case 0: // abc3
numCharsLeft -= 3;
varFound = true;
varLength = 0;
break;
/* this one should replace the one above in the future
case 0: // abc
if (varLength > 0)
numCharsLeft -= varLength;
else
varCount++;
varFound = true;
varLength = 0;
break;
*/
case 19: // albumtracks
sprintf(num, "%d", data.totalInSet);
numCharsLeft -= strlen(num);
varFound = true;
varLength = 0;
break;
case 20: // album
if (varLength > 0)
numCharsLeft -= varLength;
else
varCount++;
varFound = true;
varLength = 0;
break;
case 1: // artist
if (varLength > 0)
numCharsLeft -= varLength;
else
varCount++;
varFound = true;
varLength = 0;
break;
case 2: // country
numCharsLeft -= 2;
varFound = true;
varLength = 0;
break;
case 3: // day
numCharsLeft -= 2;
varFound = true;
varLength = 0;
break;
case 4: // format
numCharsLeft -= data.fileFormat.length();
varFound = true;
varLength = 0;
break;
case 5: // l (lowercase)
varFound = true;
break;
case 6: // month
numCharsLeft -= 2;
varFound = true;
varLength = 0;
break;
case 7: // 0num
numCharsLeft -= 2;
varFound = true;
varLength = 0;
break;
case 8: // num
sprintf(num, "%d", data.trackNum);
numCharsLeft -= strlen(num);
varFound = true;
varLength = 0;
break;
case 9: // sortname
if (varLength > 0)
numCharsLeft -= varLength;
else
varCount++;
varFound = true;
varLength = 0;
break;
case 10: // status
{
if (varLength > 0)
numCharsLeft -= varLength;
else
{
string status;
convertFromAlbumStatus(data.albumStatus, status);
numCharsLeft -= status.length();
}
varFound = true;
varLength = 0;
break;
}
case 11: // track
if (varLength > 0)
numCharsLeft -= varLength;
else
varCount++;
varFound = true;
varLength = 0;
break;
case 12: // type
{
if (varLength > 0)
numCharsLeft -= varLength;
else
{
string type;
convertFromAlbumType(data.albumType, type);
numCharsLeft -= type.length();
}
varFound = true;
varLength = 0;
break;
}
case 13: // u (uppercase)
varFound = true;
break;
case 14: // year
numCharsLeft -= 4;
varFound = true;
varLength = 0;
break;
/* the next two should be removed in the future */
case 15: // abc2
numCharsLeft -= 2;
varFound = true;
varLength = 0;
break;
case 16: // abc
numCharsLeft -= 1;
varFound = true;
varLength = 0;
break;
case 18: // albumartist
case 17: // albumartistsortname
if (varLength > 0)
numCharsLeft -= varLength;
else
varCount++;
varFound = true;
varLength = 0;
break;
}
i += strlen(repVars[j]);
}
}
if (!varFound)
{
printf("Found modifier\n");
/* variable not found, yet we have a "%"
* let's see if the user wants to "limit" the amount of chars
* in the next variable */
if (atoi(name.substr(i + 1, 1).c_str()) > 0 && atoi(name.substr(i + 1, 1).c_str()) <= 9)
{
/* seems like the user wants a limited amount of chars
* in next variable */
varLength = atoi(name.substr(i + 1, 1).c_str());
i++;
}
}
}
}
else
{
numCharsLeft = 999999999;
varCount = 100;
}
bool lowercase = false;
bool uppercase = false;
int varLength = 0;
for(i = 0; i < name.length(); i++)
{
if (name[i] != '%')
{
numCharsLeft--;
lowercase = false;
uppercase = false;
continue;
}
bool varFound = false;
for(int j = 0; j != numRepVars && !varFound; j++)
{
char num[10];
if (strncmp(name.c_str() + i, repVars[j], strlen(repVars[j])) == 0)
{
switch(j)
{
case 0: // abc3
if (data.variousArtist)
rep = data.album.substr(0, 3);
else
rep = data.sortName.substr(0, 3);
varFound = true;
varLength = 0;
break;
/* this one should replace the one above in the future
case 0: // abc
if (varLength > 0)
if (data.variousArtist)
rep = data.album.substr(0, varLength);
else
rep = data.sortName.substr(0, varLength);
else
{
varLen = numCharsLeft / varCount;
varCount--;
if (data.variousArtist)
rep = data.album;
else
rep = data.sortName;
numCharsLeft -= varLen;
}
varFound = true;
varLength = 0;
break;
*/
case 19: // albumtracks
sprintf(num, "%d", data.totalInSet);
rep = string(num);
varFound = true;
varLength = 0;
break;
case 20: // album
if (varLength > 0)
rep = data.album.substr(0, varLength);
else
{
varLen = numCharsLeft / varCount;
varCount--;
rep = data.album;
}
varFound = true;
varLength = 0;
break;
case 1: // artist
if (varLength > 0)
rep = data.artist.substr(0, varLength);
else
{
varLen = numCharsLeft / varCount;
varCount--;
rep = data.artist;
}
varFound = true;
varLength = 0;
break;
case 2: // country
rep = data.releaseCountry;
if (rep.length() == 0)
rep = "__";
varFound = true;
varLength = 0;
break;
case 3: // day
sprintf(num, "%02d", data.releaseDay);
rep = string(num);
varFound = true;
varLength = 0;
break;
case 4: // format
rep = data.fileFormat;
varFound = true;
varLength = 0;
break;
case 5: // l (lowercase)
rep = "";
lowercase = true;
uppercase = false;
/* don't set "varFound = true" as that will cause
* lowercase to be "false" too soon*/
break;
case 6: // month
sprintf(num, "%02d", data.releaseMonth);
rep = string(num);
varFound = true;
varLength = 0;
break;
case 7: // 0num
sprintf(num, "%02d", data.trackNum);
rep = string(num);
varFound = true;
varLength = 0;
break;
case 8: // num
sprintf(num, "%d", data.trackNum);
rep = string(num);
varFound = true;
varLength = 0;
break;
case 9: // sortname
if (varLength > 0)
rep = data.sortName.substr(0, varLength);
else
{
varLen = numCharsLeft / varCount;
varCount--;
rep = data.sortName;
}
varFound = true;
varLength = 0;
break;
case 10: // status
{
string status;
convertFromAlbumStatus(data.albumStatus, status);
if (varLength > 0)
rep = status.substr(0, varLength);
else
{
varLen = numCharsLeft / varCount;
varCount--;
rep = status;
}
varFound = true;
varLength = 0;
break;
}
case 11: // track
if (varLength > 0)
rep = data.track.substr(0, varLength);
else
{
varLen = numCharsLeft / varCount;
varCount--;
rep = data.track;
}
varFound = true;
varLength = 0;
break;
case 12: // type
{
string type;
convertFromAlbumType(data.albumType, type);
if (varLength > 0)
rep = type.substr(0, varLength);
else
{
varLen = numCharsLeft / varCount;
varCount--;
rep = type;
}
varFound = true;
varLength = 0;
break;
}
case 13: // u (uppercase)
rep = "";
lowercase = false;
uppercase = true;
/* don't set "varFound = true" as that will cause
* uppercase to be "false" too soon */
break;
case 14: // year
sprintf(num, "%04d", data.releaseYear);
rep = string(num);
varFound = true;
varLength = 0;
break;
/* the next two should be removed in the future */
case 15: // abc2
if (data.variousArtist)
rep = data.album.substr(0, 2);
else
rep = data.sortName.substr(0, 2);
varFound = true;
varLength = 0;
break;
case 16: // abc
if (data.variousArtist)
rep = data.album.substr(0, 1);
else
rep = data.sortName.substr(0, 1);
varFound = true;
varLength = 0;
break;
case 18: // albumartist
if (varLength > 0)
rep = data.albumArtist.substr(0, varLength);
else
{
varLen = numCharsLeft / varCount;
varCount--;
rep = data.albumArtist;
}
varFound = true;
varLength = 0;
break;
case 17: // albumartistsortname
if (varLength > 0)
rep = data.albumArtistSortName.substr(0, varLength);
else
{
varLen = numCharsLeft / varCount;
varCount--;
rep = data.albumArtistSortName;
}
varFound = true;
varLength = 0;
break;
}
rep = sanitize(rep);
if (lowercase && varFound)
toLower(rep);
if (uppercase && varFound)
toUpper(rep);
name.erase(i, strlen(repVars[j]));
name.insert(i, rep);
i += rep.length() - 1;
rep = "";
}
}
if (!varFound)
{
/* variable not found, yet we have a "%"
* let's see if the user wants to "limit" the amount of chars
* in the next variable */
if (atoi(name.substr(i + 1, 1).c_str()) > 0 && atoi(name.substr(i + 1, 1).c_str()) <= 9)
{
/* seems like the user wants a limited amount of chars
* in next variable */
varLength = atoi(name.substr(i + 1, 1).c_str());
/* erase those two chars... */
name.erase(i, 2);
/* and make sure it checks the same spot once more */
i--;
}
}
if (varFound)
{
lowercase = false;
uppercase = false;
}
}
#ifdef WIN32
bool winSafeFileNames = true;
#else
bool winSafeFileNames = context->getWinSafeFileNames();
#endif
if (winSafeFileNames) {
string::size_type pos = 0;
// Some windows systems can't handle three periods in a row. Fucking lame!
for(;;)
{
pos = name.find(" ...");
if (pos != string::npos)
name.erase(pos, 4);
else
{
pos = name.find("...");
if (pos != string::npos)
name.erase(pos, 3);
else
break;
}
}
// Now remove any characters that the filesystem might bitch about
for(unsigned i = 0; i < name.size(); i++)
{
if (strchr(disallowedFileNameChars, name[i]))
{
name.erase(i, 1);
i--;
}
}
for(;;)
{
pos = name.find("...");
if (pos != string::npos)
name.erase(pos, 3);
else
break;
}
for(;;)
{
pos = name.find("..");
if (pos != string::npos)
name.erase(pos, 2);
else
break;
}
for(;;)
{
pos = name.find(" ");
if (pos != string::npos)
name.erase(pos, 1);
else
break;
}
for(;;)
{
pos = name.find(" " + string(dirSep));
if (pos != string::npos)
name.erase(pos, 1);
else
break;
}
// remove trailing dot
for(;;)
{
pos = name.find("." + string(dirSep));
if (pos != string::npos)
name.erase(pos, 1);
else
break;
}
}
// Rewrite spaces to underscores if allowedFileNameChars doesn't contain
// a space character.
if (!allowedFileChars.empty() &&
strchr(allowedFileChars.c_str(), ' ') == NULL )
{
for (unsigned i = 0; name[i] != '\0'; i++)
{
if ( name[i] == ' ' )
name[i] = '_';
}
}
if (context->getMoveFiles())
{
string destDir = context->getDestDir();
if (destDir.size() && destDir[destDir.size() - 1] == dirSepChar)
destDir.erase(destDir.size() - 1, 1);
if (context->getRenameFiles())
name = destDir + string(dirSep) + name;
else
name = destDir + string(dirSep) + extractFilePath(name) +
string(dirSep) + extractFileBase(origFile);
}
else
{
if (context->getRenameFiles())
name = string(origPath) + string(dirSep) + extractFileName(name);
else
name = string(origPath) + string(dirSep) + extractFileBase(origFile);
}
// Fix empty directory names (// -> /, \\ -> \)
for(;;)
{
string::size_type pos = name.find(string(dirSep) + string(dirSep));
if (pos != string::npos)
name.erase(pos, 1);
else
break;
}
// Remove leading dots
for(;;)
{
string::size_type pos = name.find(string(dirSep) + ".");
if (pos != string::npos)
name.erase(pos + 1, 1);
else
break;
}
// Remove everything from name that isn't in allowedFileChars.
// However, never remove the directory separator char and also ':' on Windows
if (!allowedFileChars.empty())
for(unsigned i = 0; i < name.size(); i++)
{
if (name[i] != dirSepChar &&
#ifdef WIN32
name[i] != ':' &&
#endif
!strchr(allowedFileChars.c_str(), name[i]))
{
name.erase(i, 1);
i--;
}
}
if (index > 0)
{
char temp[10];
sprintf(temp, " (%d)", index);
fileName = name + string(temp) + string(ext);
}
else
fileName = name + string(ext);
}
//---------------------------------------------------------------------------
string FileNameMaker::extractFilePath(const string &file)
{
string::size_type pos;
pos = file.rfind(dirSep, file.size() - 1);
if (pos == string::npos)
return string(".");
return file.substr(0, pos);
}
//---------------------------------------------------------------------------
string FileNameMaker::extractFileName(const string &file)
{
string::size_type pos;
pos = file.rfind(dirSep, file.size() - 1);
if (pos == string::npos)
return file;
return file.substr(pos + 1, file.size());
}
//---------------------------------------------------------------------------
string FileNameMaker::extractFileBase(const string &fileArg)
{
string file = fileArg;
string::size_type pos;
file = extractFileName(file);
pos = file.rfind(".", file.size() - 1);
if (pos == string::npos)
return file;
return file.substr(0, pos);
}
//---------------------------------------------------------------------------
string FileNameMaker::extractFileExt(const string &file)
{
string::size_type pos;
pos = file.rfind(".", file.size() - 1);
if (pos == string::npos)
return file;
return file.substr(pos, file.size());
}
//---------------------------------------------------------------------------
string FileNameMaker::extractVolume(const string &file)
{
#ifdef WIN32
string::size_type pos;
if (file.size() > 2 && file[0] == '\\' && file[1] == '\\')
{
pos = file.find("\\", 2);
if (pos == string::npos)
return "";
return file.substr(0, pos);
}
if (file.size() > 2 && isalpha(file[0]) && file[1] == ':')
{
pos = file.find("\\", 1);
if (pos == string::npos)
return "";
return file.substr(0, pos + 1);
}
#endif
return "";
}
//---------------------------------------------------------------------------
const string FileNameMaker::sanitize(const string &str)
{
string data;
data = str;
for(int i = str.size() - 1; i >= 0; i--)
if (str[i] == dirSepChar)
data.erase(i, 1);
return data;
}
//---------------------------------------------------------------------------
WriteThread::WriteThread(TunePimp *tunePimpArg, FileCache *cacheArg, Plugins *pluginsArg)
:Thread(), FileNameMaker(&tunePimpArg->context)
{
tunePimp = tunePimpArg;
cache = cacheArg;
plugins = pluginsArg;
exitThread = false;
sem = new Semaphore();
}
//---------------------------------------------------------------------------
WriteThread::~WriteThread(void)
{
exitThread = true;
sem->signal();
join();
delete sem;
}
//---------------------------------------------------------------------------
void WriteThread::wake(void)
{
sem->signal();
}
//---------------------------------------------------------------------------
void WriteThread::threadMain(void)
{
Metadata server;
string fileName, status, puid, trackId;
Track *track;
bool checkedTrack = false, writeError = false;
for(; !exitThread;)
{
track = cache->getNextItem(eVerified);
if (track == NULL)
{
if (checkedTrack)
{
checkedTrack = false;
tunePimp->writeTagsComplete(!writeError);
writeError = false;
}
sem->wait();
continue;
}
checkedTrack = true;
track->lock();
track->getServerMetadata(server);
track->getPUID(server.filePUID);
if (track->hasChanged())
{
track->unlock();
if (writeTrack(track, server))
{
track->lock();
if (track->getStatus() == eVerified)
{
if (context->getAutoRemoveSavedFiles())
track->setStatus(eDeleted);
else
{
track->setLocalMetadata(server);
track->setServerMetadata(server);
track->setStatus(eSaved);
}
track->setError("Track saved.");
}
}
else
{
track->lock();
track->setStatus(eError);
writeError = true;
}
tunePimp->wake(track);
}
else
{
track->getFileName(fileName);
if (context->getAutoRemoveSavedFiles())
track->setStatus(eDeleted);
else
track->setStatus(eSaved);
}
track->unlock();
tunePimp->wake(track);
cache->release(track);
}
}
//---------------------------------------------------------------------------
bool WriteThread::writeTrack(Track *track, const Metadata &server)
{
string ext, fileName;
unsigned long fileSize;
Plugin *plugin;
metadata_t mdata;
track->lock();
track->getFileName(fileName);
ext = extractFileExt(fileName);
track->unlock();
fileSize = fileOpenTest(fileName);
track->lock();
if (fileSize == 0)
{
track->setError("Cannot remove existing file -- file cannot be opened for exclusive access.");
track->unlock();
return false;
}
track->unlock();
if (!diskSpaceTest(fileName, fileSize))
{
track->lock();
track->setError("Not enough available diskspace for writing tags to the existing file.");
track->unlock();
return false;
}
plugin = plugins->get(ext, TP_PLUGIN_FUNCTION_METADATA);
if (plugin)
{
bool ret;
string err, encoding;
int flags = 0;
if (strcasecmp(ext.c_str(), ".mp3") == 0)
{
if (tunePimp->context.getWriteID3v1())
flags |= TP_PLUGIN_FLAGS_WRITE_ID3V1;
if (tunePimp->context.getWriteID3v2_3())
flags |= TP_PLUGIN_FLAGS_MP3_USE_ID3V23;
switch(tunePimp->context.getID3Encoding())
{
case eLatin1:
flags |= TP_PLUGIN_FLAGS_MP3_WRITE_LATIN1;
break;
case eEncodingError:
case eUTF8:
// Do nothing -- UTF8 is the default
break;
case eUTF16:
flags |= TP_PLUGIN_FLAGS_MP3_WRITE_UTF16;
break;
}
}
if (tunePimp->context.getClearTags())
flags |= TP_PLUGIN_FLAGS_GENERAL_CLEAR_TAGS;
encoding = tunePimp->context.getFileNameEncoding();
server.writeToC(&mdata);
try
{
ret = plugin->writeMetadata(&mdata, fileName.c_str(), flags, encoding.c_str());
}
catch(...)
{
ret = false;
}
if (!ret)
{
err = string(plugin->getError());
track->lock();
track->setError(string("Could not write metadata to track: ") + string(err));
track->unlock();
return false;
}
}
if (tunePimp->context.getRenameFiles() || tunePimp->context.getMoveFiles())
{
string newName, err;
int ret;
for(int j = 0;; j++)
{
newName = fileName;
makeNewFileName(server, newName, j);
if (!tunePimp->context.getMoveFiles() || createPath(newName))
{
#ifdef WIN32
if (strcasecmp(newName.c_str(), fileName.c_str()) == 0)
#else
if (strcmp(newName.c_str(), fileName.c_str()) == 0)
#endif
break;
string encoding = tunePimp->context.getFileNameEncoding();
if (taccess(newName.c_str(), 0, encoding.c_str()) == 0)
continue;
fileSize = fileOpenTest(fileName);
if (fileSize == 0)
{
track->lock();
track->setError("Cannot write to new file -- access denied.");
track->unlock();
return false;
}
if (!diskSpaceTest(newName, fileSize))
{
track->lock();
track->setError("Not enough available diskspace for writing a new file.");
track->unlock();
return false;
}
ret = trename(fileName.c_str(), newName.c_str(), encoding.c_str());
if (ret != 0 && errno == EEXIST)
continue;
if (ret != 0)
{
track->lock();
track->setError("Could not rename file.");
track->unlock();
return false;
}
if (tunePimp->context.getMoveFiles())
cleanPath(fileName);
}
else
{
string path = extractFilePath(newName);
err = string("Could not create destination directory: ") + path;
track->lock();
track->setError(err);
track->unlock();
return false;
}
break;
}
track->lock();
track->setFileName(newName);
track->unlock();
}
return true;
}
//---------------------------------------------------------------------------
#ifdef WIN32
unsigned long WriteThread::fileOpenTest(const string &fileName)
{
HANDLE openTest = INVALID_HANDLE_VALUE;
unsigned long fileSize;
if (GetVersion() < 0x80000000)
{
string newFileName = string("\\\\?\\") + fileName;
LPWSTR wFileName = new WCHAR[newFileName.size() + 1];
MultiByteToWideChar(CP_UTF8, 0, newFileName.c_str(), -1, wFileName, newFileName.size() + 1);
openTest = CreateFileW(wFileName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
delete [] wFileName;
}
else {
LPSTR aFileName = NULL;
if (!utf8_decode(fileName.c_str(), &aFileName))
{
openTest = CreateFileA(aFileName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
free(aFileName);
}
}
if (openTest == INVALID_HANDLE_VALUE)
return 0;
fileSize = SetFilePointer(openTest, 0, NULL, FILE_END);
CloseHandle(openTest);
return fileSize;
}
#else
//---------------------------------------------------------------------------
unsigned long WriteThread::fileOpenTest(const string &fileName)
{
int openTest;
unsigned long fileSize;
string encoding;
encoding = tunePimp->context.getFileNameEncoding();
openTest = open(utf8ToEncoding(fileName, encoding).c_str(), O_EXCL | O_RDWR);
if (openTest < 0)
return 0;
fileSize = lseek(openTest, 0, SEEK_END);
close(openTest);
return fileSize;
}
#endif
//---------------------------------------------------------------------------
#ifdef WIN32
bool WriteThread::diskSpaceTest(const string &fileName, unsigned long fileSize)
{
ULARGE_INTEGER temp;
__int64 diskSpace;
bool ret = false;
string newFileName;
LPWSTR wFileName;
string path = extractFilePath(fileName);
// GetDiskFreeSpaceEx says that if a path is a UNC then it needs
// to end with a backslash.
if (path.size() >= 2 && path[0] == '\\' && path[1] == '\\')
path += "\\";
if (GetVersion() < 0x80000000)
{
newFileName = string("\\\\?\\") + path;
wFileName = new WCHAR[newFileName.size() + 1];
MultiByteToWideChar(CP_UTF8, 0, newFileName.c_str(), -1, wFileName, newFileName.size() + 1);
ret = GetDiskFreeSpaceExW(wFileName, &temp, NULL, NULL);
delete [] wFileName;
if (!ret && GetLastError() == ERROR_INVALID_NAME)
{
path.erase(3, path.size());
newFileName = string("\\\\?\\") + path;
wFileName = new WCHAR[newFileName.size() + 1];
MultiByteToWideChar(CP_UTF8, 0, newFileName.c_str(), -1, wFileName, newFileName.size() + 1);
ret = GetDiskFreeSpaceExW(wFileName, &temp, NULL, NULL);
delete [] wFileName;
}
}
else {
LPSTR aFileName = NULL;
if (!utf8_decode(fileName.c_str(), &aFileName))
{
ret = GetDiskFreeSpaceExA(aFileName, &temp, NULL, NULL);
free(aFileName);
}
}
if (ret)
{
diskSpace = *(__int64 *)&temp;
// Increase the size a bit in case the file grows and what not.
fileSize += fileSize / 10;
return diskSpace > (__int64)fileSize;
}
// If we can't determine if the diskspace is ok, just assume it is. There is
// probably some bigger bug causing havoc...
return true;
}
#else
//---------------------------------------------------------------------------
bool WriteThread::diskSpaceTest(const string &fileName, unsigned long fileSize)
{
struct statfs stat;
string encoding;
encoding = tunePimp->context.getFileNameEncoding();
string path = extractFilePath(fileName);
if (statfs(utf8ToEncoding(path, encoding).c_str(), &stat) == 0)
{
if (stat.f_bsize == 0)
return true;
fileSize += fileSize / 10;
fileSize /= stat.f_bsize;
return fileSize < (unsigned long)stat.f_bavail;
}
else
return false;
}
#endif
bool WriteThread::createPath(const string &pathArg)
{
string path = string(extractFilePath(pathArg).c_str());
string volume = string(extractVolume(pathArg).c_str());
string partial, encoding;
string::size_type pos;
encoding = tunePimp->context.getFileNameEncoding();
if (volume.size() > 0)
path.erase(0, volume.size());
if (path[path.size() - 1] != dirSepChar)
path += dirSep;
for(pos = 1;;)
{
pos = path.find(dirSep, pos);
if (pos == string::npos)
break;
partial = volume + path.substr(0, pos);
if (taccess(partial.c_str(), 0, encoding.c_str()))
{
if (tmkdir(partial.c_str(), encoding.c_str()) < 0)
return false;
}
pos++;
}
return true;
}
void WriteThread::cleanPath(const string &pathArg)
{
string path = string(extractFilePath(pathArg).c_str());
string volume = string(extractVolume(pathArg).c_str());
string srcDir, complete, encoding;
unsigned pos;
int ret;
encoding = tunePimp->context.getFileNameEncoding();
srcDir = tunePimp->context.getTopSrcDir();
if (volume.size() > 0)
path.erase(0, volume.size());
if (path[path.size() - 1] == dirSepChar)
path.erase(path.size() - 1);
if (srcDir[srcDir.size() - 1] == dirSepChar)
srcDir.erase(srcDir.size() - 1);
for(;;)
{
complete = volume + path;
if (strcasecmp(srcDir.c_str(), complete.c_str()) == 0)
{
break;
}
ret = trmdir(complete.c_str(), encoding.c_str());
if (ret < 0)
break;
pos = path.rfind(dirSep);
if (pos == string::npos)
break;
path.erase(pos);
}
}
|