DonkeyHotei

Rewrite 4 of XChat-MPlayer python script to use media info

May 18th, 2013
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # -*- coding: utf-8 -*-
  2. """
  3. xchat_mplayer by Csigaa, mostly rewritten by Pierre Collignon (03/2011)
  4. Edited by Daniel Gimpelevich to prevent failure on missing ID3 tags
  5. Prints a nice "now playing" message on the current irc chan
  6. /!\ You need mediainfo to run this script /!\
  7.  
  8. This rewrite breaks the first dev's wish of never using external cmds, but
  9. we need these infos!
  10.  
  11. NOTE FOR PASTEBIN: save the file as xchat_mplayer.py to your xchat directory
  12.  
  13.  
  14. License: Beer-ware (by phk) ;p
  15. ----------------------------------------------------------------------------
  16. "THE BEER-WARE LICENSE" (Revision 42):
  17. Csigaa wrote this file. As long as you retain this notice you
  18. can do whatever you want with this stuff. If we meet some day, and you think
  19. this stuff is worth it, you can buy me a beer in return
  20. ----------------------------------------------------------------------------
  21.  
  22. """
  23.  
  24. __module_name__ = "xchat_mplayer"
  25. __module_version__ = "1.05 Fork 1.3"
  26. __module_description__ = "XChat-MPlayer 'now playing' script by Csigaa and P.C, edited by DonkeyHotei"
  27.  
  28. import xchat
  29. import os
  30. import re
  31. import subprocess as sub
  32.  
  33. if os.name != 'posix':
  34.     raise NotImplementedError,'non-POSIX systems are not supported'
  35.  
  36. # Reads the mediainfo bits by actually calling the command
  37. def readMediaInfo(path):
  38.     rawData = sub.Popen('mediainfo ' + path.replace("(","\\(").replace(")","\\)").replace(" ","\\ "), shell = True, stdout = sub.PIPE).communicate()[0];
  39.     lines = rawData.split('\n');
  40.     hashTable = {};
  41.     currentCategory = '';
  42.     for line in lines:
  43.         keyValue = line.split(':');
  44.         value = '';
  45.         if len(keyValue) == 1:
  46.             if len(keyValue[0]) > 0:
  47.                 currentCategory = keyValue[0];
  48.                 hashTable[currentCategory] = {};
  49.         else:
  50.             hashTable[currentCategory][keyValue[0].strip()] = keyValue[1].strip();
  51.     return hashTable;
  52.  
  53. def getEntry(category,tag,hashTable):
  54.     try:
  55.         result = hashTable[category][tag]
  56.     except KeyError:
  57.         result = ''
  58.     return result;
  59.  
  60. def buildDescription(hashTable):
  61.     artist = getEntry('General','Performer',hashTable);
  62.     track = getEntry('General','Track name',hashTable);
  63.     duration = getEntry('General','Duration',hashTable);
  64.     bitrate = getEntry('General','Overall bit rate',hashTable);
  65.     frequency = getEntry('Audio','Sampling rate',hashTable);
  66.     album = getEntry('General','Album',hashTable);
  67.     albumDate = getEntry('General','Recorded date',hashTable);
  68.     fileSize = getEntry('General','File size',hashTable);
  69.     completeName = artist + ' - ' + track;
  70.     if completeName == ' - ':
  71.         completeName = os.readlink(getEntry('General','Complete name',hashTable))
  72.         completeName = completeName.split('/')
  73.         completeName = completeName.pop()
  74.     profile = '';
  75.     if 'Format profile' in hashTable['Audio']:
  76.         profile = ' ' + hashTable['Audio']['Format profile'] + ' ';
  77.     mode = '';
  78.     if 'Mode' in hashTable['Audio']:
  79.         mode = ' ' + hashTable['Audio']['Mode'] + ' ';
  80.     wholeFormat = hashTable['Audio']['Format'] + profile + mode;
  81.  
  82.     completeDesc = '♪♪♪ ' + completeName + ' : ' + duration + ' : ' + bitrate + ' : ' + wholeFormat + ' ♪♪♪ ' + frequency + ' ♪♪♪ ' + album + ' (' + albumDate + ')' + ' ♪♪♪ ';
  83.     return completeDesc;
  84.  
  85. def getFilename():
  86.     # Get the video file name (identified by naming pattern) from procfs
  87.    
  88.     # list&walk the directory contents
  89.     proclist = sorted(os.listdir('/proc'))
  90.     for proc in os.listdir('/proc'):
  91.     # if it is a directory with a name of digits only
  92.     if os.path.isdir('/proc/'+proc) and re.match('[0-9]+',proc):
  93.         try:
  94.         exe = os.readlink('/proc/'+proc+'/exe').split('/')
  95.         # if executable name is 'mplayer'
  96.         exe_name = exe.pop()
  97.         if exe_name == 'mplayer' or exe_name == 'mplayer2':
  98.             filelist = os.listdir('/proc/' + proc + '/fd')
  99.             # walk the list of open files
  100.             for file in filelist:
  101.             try:
  102.                 path = '/proc/' + proc + '/fd/' + file
  103.                 if re.match('.*(avi|mpg|mkv|mp4|nuv|ogg|ogm|wmv|iso|img|mp3|flac)$', os.readlink(path), re.I):
  104.                 # if filename found, return
  105.                 return path;
  106.             except:
  107.                 # if link not readable, skip
  108.                 continue
  109.         except:
  110.         # if process directory not readable, skip
  111.         continue
  112.     return None
  113.  
  114. def getVersion():
  115.     try:
  116.     import commands
  117.     try:
  118.         # release version, begins with number (incl. optional rc sign with maximum 2 digits); if no match, exception occurs (empty list - 0 index is out of range)
  119.         ver = re.findall('^MPlayer\s\d[.]\d+\w{0,4}',commands.getoutput('mplayer'))[0]
  120.     except:
  121.         # SVN version, begins with 'SVN' (revision number maximum 6 digits)
  122.         ver = re.findall('^MPlayer\sSVN-r\d{0,6}',commands.getoutput('mplayer'))[0]
  123.     return ver
  124.     except:
  125.     # if any error occured above, return only the player name
  126.     return 'MPlayer'
  127.  
  128. def mplayer_msg(world,world_eol,userdata):
  129.     fileName = getFilename();
  130.     if type(fileName).__name__ != 'NoneType':
  131.         irccmd = 'me is now playing ' +  buildDescription(readMediaInfo(getFilename())) + 'with ' + getVersion() + ' for Linux d[O_o]b';  
  132.         xchat.command(irccmd)
  133.     else:
  134.         print 'You are not playing anything !';
  135.     return xchat.EAT_ALL
  136.  
  137. xchat.hook_command('mplayer', mplayer_msg)
  138. xchat.prnt('XChat-MPlayer '+__module_version__+' loaded - use /mplayer to print now playing message')
Advertisement
Add Comment
Please, Sign In to add comment