Renomeie os episódios do iTunes TV para incluir a temporada e o número do episódio no nome do arquivo


1

Estou mudando do iTunes para o servidor Emby para transmitir vídeos para o meu Apple TV. Emby se dá bem com filmes, mas para identificar episódios de séries de TV, ele precisa da temporada e do número do episódio no nome do arquivo.

Infelizmente, o iTunes nomeia arquivos de vídeo de episódios de TV usando apenas o nome do episódio. Ele tem os números dos episódios em suas tags e banco de dados, mas não os coloca no nome do arquivo. Portanto, um local típico de arquivo é:

TV Shows > Jeeves and Wooster > Season 1 > Jeeves Takes Charge.mp4

Mas o que eu quero é:

TV Shows > Jeeves and Wooster > Season 1 > Jeeves and Wooster S01E01.mp4

Apenas adicionar o número do episódio no começo seria ótimo:

01 Jeeves Takes Charge.mp4

Minha biblioteca é grande o suficiente para fazer com que isso seja um grande desperdício de tempo. O iTunes pode ser coagido a fazê-lo automaticamente? Caso contrário, existe uma ferramenta de terceiros ou outra solução pronta? Tenho certeza de que isso pode ser feito no Applescript com Exiftool, mas eu prefiro não reinventar a roda se alguém já o tiver feito.

Respostas:


1

Ainda não sei se existe uma maneira de obrigar o iTunes a fazê-lo automaticamente, mas o consegui com o Applescript e o ExifTool. Caso seja útil para mais alguém, abaixo está o script completo. Você precisará instalar o ExifTool primeiro. Você pode executar o script para escolher um arquivo de cada vez ou exportá-lo como um aplicativo para arrastar e soltar.

Renomeia episódios como:

Show Name S01E01 Nome do episódio.mp4

que é um formato reconhecido por Emby, Plex e outros gerentes de mídia.

Ele processa as pastas recursivamente, para que você possa arrastar toda a pasta de programas de TV para ela de uma só vez. Irá pular arquivos que não são de vídeo ou que não possuem os metadados esperados do programa de TV e, quando terminar, aparece uma caixa de diálogo para informar quantos de cada um deles foi encontrado.

(*
Rename TV Episode to include Season and Number

Drop or select files or folders.
This script will check each file for metadata tags for TV show name, season number, episode number, and episode name and rename each file in the format:
Show Name S01E01 Episode Name.mp4

It will ignore files that don't match one of the extensions in the extensionList below. By default, mp4, m4v, mkv.
It will skip files that don't have all four of the desired meta tags.
If the show name or episode name contains illegal characters (colon, forward-slash, back-slash) it will replace them with "_" for the filename.

ExifTool must be installed. You can find it here:
https://www.sno.phy.queensu.ca/~phil/exiftool/

Make sure the pathToExifTool matches your system. The included one is the default.
*)

property pathToExifTool : "/usr/local/bin/exiftool"

property whitelistTypes : false
property whitelistExtensions : true
property whitelistTypeIDs : false

property typeList : {} -- eg: {"PICT", "JPEG", "TIFF", "GIFf"} 
property extensionList : {"mp4", "m4v", "mkv", "avi", "wmv"} -- eg: {"txt", "text", "jpg", "jpeg"}, NOT: {".txt", ".text", ".jpg", ".jpeg"}
property typeIDsList : {} -- eg: {"public.jpeg", "public.tiff", "public.png"}

global numberOfItemsRenamed
global numberOfItemsIgnored
global numberOfItemsWithoutMetaData

-- If opened without a drop, choose a file and simulate a drop
on run
    open {} & (choose file "Select a file")
end run
-- process files dropped or selected
on open theseItems
    set numberOfItemsRenamed to 0
    set numberOfItemsIgnored to 0
    set numberOfItemsWithoutMetaData to 0

    processItems(theseItems)
    reportResults()
end open

on reportResults()
    -- build the output string
    set output to "Renamed " & numberOfItemsRenamed & " file(s)."
    if numberOfItemsIgnored > 0 then
        set output to output & "
Ignored " & numberOfItemsIgnored & " file(s) with unrecognized filetype."
    end if
    if numberOfItemsWithoutMetaData > 0 then
        set output to output & "
Skipped " & numberOfItemsWithoutMetaData & " file(s) with insufficient TV metadata."
    end if
    display alert output
end reportResults

-- processItems takes a list of items and passes them one at a time to processItem()
on processItems(theseItems)
    repeat with i from 1 to the count of theseItems
        set thisItem to item i of theseItems
        processItem(thisItem)
    end repeat
end processItems

-- processFolder takes a folder and passes the list of contents to processItems()
on processFolder(thisFolder)
    set theseItems to list folder thisFolder without invisibles
    -- processFolder has its own loop due to different syntax for fetching aliases from within a folder
    repeat with i from 1 to the count of theseItems
        set thisItem to alias ((thisFolder as Unicode text) & (item i of theseItems))
        processItem(thisItem)
    end repeat
end processFolder

-- processItem takes an item and passes it to the appropriate next level
-- (processFolder for folders, processFileAlias for approved files, or nothing for non-whitelisted files)
on processItem(thisItem)
    set the item_info to info for thisItem
    -- if a folder was passed, process it as a folder
    if folder of the item_info is true then
        processFolder(thisItem)
    else
        -- fetch the extension, filetype, and typeid to compare to whitelists
        try
            set this_extension to the name extension of item_info
        on error
            set this_extension to ""
        end try
        try
            set this_filetype to the file type of item_info
        on error
            set this_filetype to ""
        end try
        try
            set this_typeID to the type identifier of item_info
        on error
            set this_typeID to ""
        end try
        -- only operate on files, not folders or aliases
        if (folder of the item_info is false) and (alias of the item_info is false) then
            -- only operate on files that conform to whichever whitelists are in use
            set isTypeOk to ((not whitelistTypes) or (this_filetype is in the typeList))
            set isExtensionOk to ((not whitelistExtensions) or (this_extension is in the extensionList))
            set isTypeIDOk to ((not whitelistTypeIDs) or (this_typeID is in the typeIDsList))
            if (isTypeOk and isExtensionOk and isTypeIDOk) then
                -- everything's good so process the file
                processFileAlias(thisItem)
            else
                set numberOfItemsIgnored to numberOfItemsIgnored + 1
            end if
        end if
    end if
end processItem

-- processFileAlias takes a fileAlias and rename the file as a TV episode
on processFileAlias(fileAlias)
    set originalInfo to info for fileAlias
    -- get the file extension (to use when renaming, later)
    set originalName to stripExtension(the name of originalInfo)
    try
        set originalExtension to the name extension of originalInfo
    on error
        set originalExtension to ""
    end try
    -- prep slots for the desired metadata
    set seasonNumber to ""
    set episodeNumber to ""
    set showName to ""
    set episodeName to ""
    -- use exifTool to get the desired metadata
    set theLocation to POSIX path of (fileAlias as text)
    set exifToolOutput to (do shell script pathToExifTool & " -TVShow -TVSeason -TVEpisode -Title " & quoted form of theLocation)
    -- break exifTool output into lines
    set oldTID to AppleScript's text item delimiters
    set AppleScript's text item delimiters to return
    set exifToolOutputList to every text item of exifToolOutput
    -- now extract tags from each line
    set AppleScript's text item delimiters to ": "
    set tagList to {}
    repeat with eachItem in exifToolOutputList
        set itemName to trim(true, text item 1 of eachItem)
        -- use items 2-end in case there are :s in the value
        set itemValue to (text items 2 thru end of eachItem) as text
        if itemName = "TV Episode" then
            set episodeNumber to itemValue
        else if itemName = "TV Season" then
            set seasonNumber to itemValue
        else if itemName = "TV Show" then
            set showName to itemValue
        else if itemName = "Title" then
            set episodeName to itemValue
        end if
    end repeat
    set isAllDataPresent to (episodeNumber is not "" and seasonNumber is not "" and showName is not "")
    if isAllDataPresent then
        -- pad the numbers so they alphabetize nicely
        set seasonNumber to padNumberWithZeros(seasonNumber, 2)
        set episodeNumber to padNumberWithZeros(episodeNumber, 2)
        -- build the file name
        set newFileName to showName & " S" & seasonNumber & "E" & episodeNumber & " " & episodeName & "." & originalExtension
        -- remove illegal characters from name
        set newFileName to replaceChars(newFileName, ":", "_")
        set newFileName to replaceChars(newFileName, "/", "_")
        set newFileName to replaceChars(newFileName, "\\", "_")
        -- rename the file
        tell application "Finder"
            set name of fileAlias to newFileName
        end tell
        set numberOfItemsRenamed to numberOfItemsRenamed + 1
    else
        set numberOfItemsWithoutMetaData to numberOfItemsWithoutMetaData + 1
    end if
end processFileAlias






(*
Everything after this is utility extensions for dealing with text
*)

on stripExtension(this_name)
    if this_name contains "." then
        set this_name to ¬
            (the reverse of every character of this_name) as string
        set x to the offset of "." in this_name
        set this_name to (text (x + 1) thru -1 of this_name)
        set this_name to (the reverse of every character of this_name) as string
    end if
    return this_name
end stripExtension

on trim(theseCharacters, someText)
    -- Lazy default (AppleScript doesn't support default values)
    if theseCharacters is true then set theseCharacters to ¬
        {" ", tab, ASCII character 10, return, ASCII character 0}

    repeat until first character of someText is not in theseCharacters
        set someText to text 2 thru -1 of someText
    end repeat

    repeat until last character of someText is not in theseCharacters
        set someText to text 1 thru -2 of someText
    end repeat

    return someText
end trim

on replaceChars(this_text, search_string, replacement_string)
    set AppleScript's text item delimiters to the search_string
    set the item_list to every text item of this_text
    set AppleScript's text item delimiters to the replacement_string
    set this_text to the item_list as string
    set AppleScript's text item delimiters to ""
    return this_text
end replaceChars

on padNumberWithZeros(thisNumber, minLength)
    return text (minLength * -1) thru -1 of ("00000000000000000" & thisNumber)
end padNumberWithZeros
Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.