#!/usr/bin/env python
# -*- coding: iso-8859-15 -*-
#
# Pour mettre automatiquement en sourdine les pubs audio de Spotify
#
# . URL : http://nils.hamerlinck.fr/spotify_mute_audio_ads.py
# . Version : 20091027
# . Tags : spotify, mute, ads, pub
# . Dépendances : python-wnck, python-alsaaudio

import codecs, locale, os, sys
sys.stdout = codecs.getwriter('utf-8')(sys.stdout)

import gtk
import wnck
import re
import alsaaudio


RE_ADS = re.compile('Spotify - Spotify|Spotify - Sony Music|Spotify - Universal Music|Spotify - Unicef|Spotify - Numericable')

def test_regex():
    for l in codecs.open('titres.txt'):
        print '%s: %s' % (l[:-1], (RE_ADS.search(l) and 'AD' or 'SONG'))

mixer = alsaaudio.Mixer('Master')
volume = mixer.getvolume()[0]

def mute():
    global mixer
    volume = mixer.getvolume()[0]
    mixer.setvolume(30)
#    mixer.setmute(True)

def unmute():
    global mixer
    mixer.setvolume(volume)
#    mixer.setmute(False)

muted = False

def window_name_changed(window):
    global muted

    name = window.get_name()
    print name,
    sys.stdout.flush()

    if RE_ADS.search(name):
        print 'AD'

        if not muted:
            mute()
            muted = True
    else:
        print
        if muted:
            unmute()
            muted = False

def main():
    screen = wnck.screen_get_default()

    while gtk.events_pending():
        gtk.main_iteration()

    found = False
    for window in screen.get_windows():
        if window.has_name():
            name = window.get_name()
            if 'Spotify' in name:
                window.connect('name_changed', window_name_changed)
                found = True
                break

    if found:
        gtk.main()
    else:
        print 'Spotify not found.'

if __name__ == '__main__':
    main()
    #test_regex()
