Advertisement
filebot

amc-extract-delete

Oct 15th, 2013
882
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Groovy 14.18 KB | None | 0 0
  1. // filebot -script "fn:amc" --output "X:/media" --action copy --conflict override --def subtitles=en music=y artwork=y "ut_dir=%D" "ut_file=%F" "ut_kind=%K" "ut_title=%N" "ut_label=%L" "ut_state=%S"
  2. def input = []
  3. def failOnError = _args.conflict == 'fail'
  4.  
  5. // print input parameters
  6. _args.bindings?.each{ _log.fine("Parameter: $it.key = $it.value") }
  7. args.each{ _log.fine("Argument: $it") }
  8. args.findAll{ !it.exists() }.each{ throw new Exception("File not found: $it") }
  9.  
  10. // check user-defined pre-condition
  11. if (tryQuietly{ !(ut_state ==~ ut_state_allow) }) {
  12.     throw new Exception("Invalid state: ut_state = $ut_state (expected $ut_state_allow)")
  13. }
  14.  
  15. // check ut mode vs standalone mode
  16. if ((args.size() > 0 && (tryQuietly{ ut_dir }?.size() > 0 || tryQuietly{ ut_file }?.size() > 0)) || (args.size() == 0 && (tryQuietly{ ut_dir } == null && tryQuietly{ ut_file } == null))) {
  17.     throw new Exception("Conflicting arguments: pass in either file arguments or ut_dir/ut_file parameters but not both")
  18. }
  19.  
  20. // enable/disable features as specified via --def parameters
  21. def music     = tryQuietly{ music.toBoolean() }
  22. def subtitles = tryQuietly{ subtitles.toBoolean() ? ['en'] : subtitles.split(/[ ,|]+/).findAll{ it.length() >= 2 } }
  23. def artwork   = tryQuietly{ artwork.toBoolean() }
  24. def backdrops = tryQuietly{ backdrops.toBoolean() }
  25. def clean     = tryQuietly{ clean.toBoolean() }
  26. def exec      = tryQuietly{ exec.toString() }
  27.  
  28. // array of xbmc/plex hosts
  29. def xbmc = tryQuietly{ xbmc.split(/[ ,|]+/) }
  30. def plex = tryQuietly{ plex.split(/[ ,|]+/) }
  31.  
  32. // myepisodes updates and email notifications
  33. def myepisodes = tryQuietly { myepisodes.split(':', 2) }
  34. def gmail = tryQuietly{ gmail.split(':', 2) }
  35. def pushover = tryQuietly{ pushover.toString() }
  36.  
  37. // user-defined filters
  38. def minFileSize = tryQuietly{ minFileSize.toLong() }; if (minFileSize == null) { minFileSize = 0 };
  39.  
  40. // series/anime/movie format expressions
  41. def format = [
  42.     tvs:   tryQuietly{ seriesFormat } ?: '''TV Shows/{n}/{episode.special ? "Special" : "Season "+s.pad(2)}/{n} - {episode.special ? "S00E"+special.pad(2) : s00e00} - {t.replaceAll(/[`´‘’ʻ]/, "'").replaceAll(/[!?.]+$/).replacePart(', Part $1')}{".$lang"}''',
  43.     anime: tryQuietly{ animeFormat  } ?: '''Anime/{n}/{n} - {sxe} - {t.replaceAll(/[!?.]+$/).replaceAll(/[`´‘’ʻ]/, "'").replacePart(', Part $1')}''',
  44.     mov:   tryQuietly{ movieFormat  } ?: '''Movies/{n} ({y})/{n} ({y}){" CD$pi"}{".$lang"}''',
  45.     music: tryQuietly{ musicFormat  } ?: '''Music/{n}/{album+'/'}{pi.pad(2)+'. '}{artist} - {t}'''
  46. ]
  47.  
  48.  
  49. // force movie/series/anime logic
  50. def forceMovie(f) {
  51.     tryQuietly{ ut_label } =~ /^(?i:Movie|Couch.Potato)/ || f.path =~ /(?<=tt)\\d{7}/ || tryQuietly{ f.metadata?.object?.class.name =~ /Movie/ }
  52. }
  53.  
  54. def forceSeries(f) {
  55.     tryQuietly{ ut_label } =~ /^(?i:TV|Kids.Shows)/ || parseEpisodeNumber(f.path) || parseDate(f.path) || f.path =~ /(?i:Season)\D?[0-9]{1,2}\D/ || tryQuietly{ f.metadata?.object?.class.name =~ /Episode/ }
  56. }
  57.  
  58. def forceAnime(f) {
  59.     tryQuietly{ ut_label } =~ /^(?i:Anime)/ || (f.isVideo() && (f.name =~ "[\\(\\[]\\p{XDigit}{8}[\\]\\)]" || getMediaInfo(file:f, format:'''{media.AudioLanguageList} {media.TextCodecList}''').tokenize().containsAll(['Japanese', 'ASS'])))
  60. }
  61.  
  62. def forceIgnore(f) {
  63.     tryQuietly{ ut_label } =~ /^(?i:ebook|other|ignore)/ || f.path =~ tryQuietly{ ignore }
  64. }
  65.  
  66.  
  67. // specify how to resolve input folders, e.g. grab files from all folders except disk folders
  68. def resolveInput(f) {
  69.     if (f.isDirectory() && !f.isDisk())
  70.         return f.listFiles().toList().findResults{ resolveInput(it) }
  71.     else
  72.         return f
  73. }
  74.  
  75. // collect input fileset as specified by the given --def parameters
  76. if (args.empty) {
  77.     // assume we're called with utorrent parameters (account for older and newer versions of uTorrents)
  78.     if (ut_kind == 'single' || (ut_kind != 'multi' && ut_dir && ut_file)) {
  79.         input += new File(ut_dir, ut_file) // single-file torrent
  80.     } else {
  81.         input += resolveInput(ut_dir as File) // multi-file torrent
  82.     }
  83. } else {
  84.     // assume we're called normally with arguments
  85.     input += args.findResults{ resolveInput(it) }
  86. }
  87.  
  88.  
  89. // flatten nested file structure
  90. input = input.flatten()
  91.  
  92. // extract archives (zip, rar, etc) that contain at least one video file
  93. def tempFiles = []
  94. input = input.flatten{ f ->
  95.     if (f.isArchive() || f.hasExtension('001')) {
  96.         def extractDir = new File(f.dir, f.nameWithoutExtension)
  97.         def extractFiles = extract(file: f, output: new File(extractDir, f.dir.name), conflict: 'override', filter: { it.isArchive() || it.isVideo() || it.isSubtitle() || (music && it.isAudio()) }, forceExtractAll: true) ?: []
  98.         tempFiles += extractDir
  99.         tempFiles += extractFiles
  100.        
  101.         println "Mark archive for deletion: $f"
  102.         f.deleteOnExit()
  103.         f.dir.listFiles().toList().findAll{ v -> v.extension ==~ /r\d+/ && v.name.startsWith(f.nameWithoutExtension) }.each{ v ->
  104.             println "Mark volume for deletion: $v"
  105.             v.deleteOnExit()
  106.         }
  107.        
  108.         return extractFiles
  109.     }
  110.     return f
  111. }
  112.  
  113. // sanitize input
  114. input = input.findAll{ it?.exists() }.collect{ it.canonicalFile }.unique()
  115.  
  116. // process only media files
  117. input = input.findAll{ f -> (f.isVideo() && !tryQuietly{ f.hasExtension('iso') && !f.isDisk() }) || f.isSubtitle() || (f.isDirectory() && f.isDisk()) || (music && f.isAudio()) }
  118.  
  119. // ignore clutter files
  120. input = input.findAll{ f -> !(f.path =~ /\b(?i:sample|trailer|extras|deleted.scenes|music.video|scrapbook|behind.the.scenes)\b/ || (f.isFile() && f.length() < minFileSize)) }
  121.  
  122. // print input fileset
  123. input.each{ f -> _log.finest("Input: $f") }
  124.  
  125. // artwork/nfo utility
  126. if (artwork || xbmc) { include('lib/htpc') }
  127.  
  128. // group episodes/movies and rename according to XBMC standards
  129. def groups = input.groupBy{ f ->
  130.     // skip auto-detection if possible
  131.     if (forceIgnore(f))
  132.         return []
  133.     if (f.isAudio() && !f.isVideo()) // PROCESS MUSIC FOLDER BY FOLDER
  134.         return [music: f.dir.name]
  135.     if (forceMovie(f))
  136.         return [mov:   detectMovie(f, false)]
  137.     if (forceSeries(f))
  138.         return [tvs:   detectSeriesName(f) ?: detectSeriesName(f.dir.listFiles{ it.isVideo() })]
  139.     if (forceAnime(f))
  140.         return [anime: detectSeriesName(f) ?: detectSeriesName(f.dir.listFiles{ it.isVideo() })]
  141.    
  142.    
  143.     def tvs = detectSeriesName(f)
  144.     def mov = detectMovie(f, false)
  145.     _log.fine("$f.name [series: $tvs, movie: $mov]")
  146.    
  147.     // DECIDE EPISODE VS MOVIE (IF NOT CLEAR)
  148.     if (tvs && mov) {
  149.         def norm = { s -> s.ascii().normalizePunctuation().lower().space(' ') }
  150.         def dn = norm(guessMovieFolder(f)?.name ?: '')
  151.         def fn = norm(f.nameWithoutExtension)
  152.         def sn = norm(tvs)
  153.         def mn = norm(mov.name)
  154.        
  155.         /**
  156.         println '--- EPISODE FILTER (POS) ---'
  157.         println parseEpisodeNumber(fn, true) || parseDate(fn)
  158.         println ([dn, fn].find{ it =~ sn && matchMovie(it, true) == null } && (parseEpisodeNumber(stripReleaseInfo(fn.after(sn), false), false) || fn.after(sn) =~ /\D\d{1,2}\D{1,3}\d{1,2}\D/) && matchMovie(fn, true) == null)
  159.         println (fn.after(sn) ==~ /.{0,3} - .+/ && matchMovie(fn, true) == null)
  160.         println f.dir.listFiles{ it.isVideo() && (dn =~ sn || norm(it.name) =~ sn) && it.name =~ /\d{1,3}/}.findResults{ it.name.matchAll(/\d{1,3}/) as Set }.unique().size() >= 10
  161.         println '--- EPISODE FILTER (NEG) ---'
  162.         println (mov.year >= 1950 && f.listPath().reverse().take(3).find{ it.name =~ mov.year })
  163.         println (mn =~ sn && [dn, fn].find{ it =~ /(19|20)\d{2}/ })
  164.         **/
  165.        
  166.         // S00E00 | 2012.07.21 | One Piece 217 | Firefly - Serenity | [Taken 1, Taken 2, Taken 3, Taken 4, ..., Taken 10]
  167.         if ((parseEpisodeNumber(fn, true) || parseDate(fn) || ([dn, fn].find{ it =~ sn && matchMovie(it, true) == null } && (parseEpisodeNumber(stripReleaseInfo(fn.after(sn), false), false) || fn.after(sn) =~ /\D\d{1,2}\D{1,3}\d{1,2}\D/) && matchMovie(fn, true) == null) || (fn.after(sn) ==~ /.{0,3} - .+/ && matchMovie(fn, true) == null) || f.dir.listFiles{ it.isVideo() && (dn =~ sn || norm(it.name) =~ sn) && it.name =~ /\d{1,3}/}.findResults{ it.name.matchAll(/\d{1,3}/) as Set }.unique().size() >= 10 || mov.year < 1900) && !( (mov.year >= 1950 && f.listPath().reverse().take(3).find{ it.name =~ mov.year }) || (mn =~ sn && [dn, fn].find{ it =~ /(19|20)\d{2}/ }) ) ) {
  168.             _log.fine("Exclude Movie: $mov")
  169.             mov = null
  170.         } else if (similarity(mn, fn) >= 0.8 || [dn, fn].find{ it =~ /\b/+mov.year+/\b/ } || [dn, fn].find{ it =~ mn && !(it.after(mn) =~ /\b\d{1,3}\b/) && !(it.before(mn).contains(sn)) } || (detectMovie(f, true) && [dn, fn].find{ it =~ /(19|20)\d{2}/ })) {
  171.             _log.fine("Exclude Series: $tvs")
  172.             tvs = null
  173.         }
  174.     }
  175.    
  176.     // CHECK CONFLICT
  177.     if (((mov && tvs) || (!mov && !tvs))) {
  178.         if (failOnError) {
  179.             throw new Exception("Media detection failed")
  180.         } else {
  181.             _log.fine("Unable to differentiate: [$f.name] => [$tvs] VS [$mov]")
  182.             return [tvs: null, mov: null, anime: null]
  183.         }
  184.     }
  185.    
  186.     return [tvs: tvs, mov: mov, anime: null]
  187. }
  188.  
  189. // log movie/series/anime detection results
  190. groups.each{ group, files -> _log.finest("Group: $group => ${files*.name}") }
  191.  
  192. // process each batch
  193. groups.each{ group, files ->
  194.     // fetch subtitles (but not for anime)
  195.     if (subtitles && !group.anime) {
  196.         subtitles.each{ languageCode ->
  197.             def subtitleFiles = getMissingSubtitles(file:files, output:'srt', encoding:'UTF-8', lang:languageCode, strict:true) ?: []
  198.             files += subtitleFiles
  199.             tempFiles += subtitleFiles // if downloaded for temporarily extraced files delete later
  200.         }
  201.     }
  202.    
  203.     // EPISODE MODE
  204.     if ((group.tvs || group.anime) && !group.mov) {
  205.         // choose series / anime config
  206.         def config = group.tvs ? [name:group.tvs,   format:format.tvs,   db:'TheTVDB', seasonFolder:true ]
  207.                                : [name:group.anime, format:format.anime, db:'AniDB',   seasonFolder:false]
  208.         def dest = rename(file: files, format: config.format, db: config.db)
  209.         if (dest && artwork) {
  210.             dest.mapByFolder().each{ dir, fs ->
  211.                 _log.finest "Fetching artwork for $dir from TheTVDB"
  212.                 def sxe = fs.findResult{ eps -> parseEpisodeNumber(eps) }
  213.                 def options = TheTVDB.search(config.name, _args.locale)
  214.                 if (options.isEmpty()) {
  215.                     _log.warning "TV Series not found: $config.name"
  216.                     return
  217.                 }
  218.                 options = options.sortBySimilarity(config.name, { s -> s.name })
  219.                 fetchSeriesArtworkAndNfo(config.seasonFolder ? dir.dir : dir, dir, options[0], sxe && sxe.season > 0 ? sxe.season : 1)
  220.             }
  221.         }
  222.         if (dest == null && failOnError) {
  223.             throw new Exception("Failed to rename series: $config.name")
  224.         }
  225.     }
  226.    
  227.     // MOVIE MODE
  228.     if (group.mov && !group.tvs && !group.anime) {
  229.         def dest = rename(file:files, format:format.mov, db:'TheMovieDB')
  230.         if (dest && artwork) {
  231.             dest.mapByFolder().each{ dir, fs ->
  232.                 _log.finest "Fetching artwork for $dir from TheMovieDB"
  233.                 fetchMovieArtworkAndNfo(dir, group.mov, fs.findAll{ it.isVideo() }.sort{ it.length() }.reverse().findResult{ it }, backdrops)
  234.             }
  235.         }
  236.         if (dest == null && failOnError) {
  237.             throw new Exception("Failed to rename movie: $group.mov")
  238.         }
  239.     }
  240.    
  241.     // MUSIC MODE
  242.     if (group.music) {
  243.         def dest = rename(file:files, format:format.music, db:'AcoustID')
  244.         if (dest == null && failOnError) {
  245.             throw new Exception("Failed to rename music: $group.music")
  246.         }
  247.     }
  248. }
  249.  
  250. // skip notifications if nothing was renamed anyway
  251. if (getRenameLog().isEmpty()) {
  252.     return
  253. }
  254.  
  255. // run program on newly processed files
  256. if (exec) {
  257.     getRenameLog().each{ from, to ->
  258.         def command = getMediaInfo(format: exec, file: to)
  259.         _log.finest("Execute: $command")
  260.         execute(command)
  261.     }
  262. }
  263.  
  264. // make XMBC scan for new content and display notification message
  265. if (xbmc) {
  266.     xbmc.each{ host ->
  267.         _log.info "Notify XBMC: $host"
  268.         _guarded{
  269.             showNotification(host, 9090, 'FileBot', "Finished processing ${tryQuietly { ut_title } ?: input*.dir.name.unique()} (${getRenameLog().size()} files).", 'http://www.filebot.net/images/icon.png')
  270.             scanVideoLibrary(host, 9090)
  271.         }
  272.     }
  273. }
  274.  
  275. // make Plex scan for new content
  276. if (plex) {
  277.     plex.each{
  278.         _log.info "Notify Plex: $it"
  279.         refreshPlexLibrary(it)
  280.     }
  281. }
  282.  
  283. // mark episodes as 'acquired'
  284. if (myepisodes) {
  285.     _log.info 'Update MyEpisodes'
  286.     executeScript('update-mes', [login:myepisodes.join(':'), addshows:true], getRenameLog().values())
  287. }
  288.  
  289. if (pushover) {
  290.     // include webservice utility
  291.     include('lib/ws')
  292.    
  293.     _log.info 'Sending Pushover notification'
  294.     Pushover(pushover).send("Finished processing ${tryQuietly { ut_title } ?: input*.dir.name.unique()} (${getRenameLog().size()} files).")
  295. }
  296.  
  297. // send status email
  298. if (gmail) {
  299.     // ant/mail utility
  300.     include('lib/ant')
  301.    
  302.     // send html mail
  303.     def renameLog = getRenameLog()
  304.     def emailTitle = tryQuietly { ut_title } ?: input*.dir.name.unique()
  305.    
  306.     sendGmail(
  307.         subject: "[FileBot] ${emailTitle}",
  308.         message: XML {
  309.             html {
  310.                 body {
  311.                     p("FileBot finished processing ${emailTitle} (${renameLog.size()} files).");
  312.                     hr(); table {
  313.                         th("Parameter"); th("Value")
  314.                         _args.bindings.findAll{ param -> param.key =~ /^ut_/ }.each{ param ->
  315.                             tr { [param.key, param.value].each{ td(it)} }
  316.                         }
  317.                     }
  318.                     hr(); table {
  319.                         th("Original Name"); th("New Name"); th("New Location")
  320.                         renameLog.each{ from, to ->
  321.                             tr { [from.name, to.name, to.parent].each{ cell -> td{ nobr{ code(cell) } } } }
  322.                         }
  323.                     }
  324.                     hr(); small("// Generated by ${net.sourceforge.filebot.Settings.applicationIdentifier} on ${new Date().dateString} at ${new Date().timeString}")
  325.                 }
  326.             }
  327.         },
  328.         messagemimetype: 'text/html',
  329.         to: tryQuietly{ mailto } ?: gmail[0] + '@gmail.com', // mail to self by default
  330.         user: gmail[0], password: gmail[1]
  331.     )
  332. }
  333.  
  334. // clean empty folders, clutter files, etc after move
  335. if (clean) {
  336.     if (['COPY', 'HARDLINK'].find{ it.equalsIgnoreCase(_args.action) } && tempFiles.size() > 0) {
  337.         _log.info 'Clean temporary extracted files'
  338.         // delete extracted files
  339.         tempFiles.findAll{ it.isFile() }.sort().each{
  340.             _log.finest "Delete $it"
  341.             it.delete()
  342.         }
  343.         // delete remaining empty folders
  344.         tempFiles.findAll{ it.isDirectory() }.sort().reverse().each{
  345.             _log.finest "Delete $it"
  346.             if (it.getFiles().isEmpty()) it.deleteDir()
  347.         }
  348.     }
  349.    
  350.     // deleting remaining files only makes sense after moving files
  351.     if ('MOVE'.equalsIgnoreCase(_args.action)) {
  352.         _log.info 'Clean clutter files and empty folders'
  353.         executeScript('cleaner', args.empty ? [root:true] : [root:false], !args.empty ? args : ut_kind == 'multi' && ut_dir ? [ut_dir as File] : [])
  354.     }
  355. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement