#! /usr/bin/python
#This script detects commercials in Spotify, and removes them :D
#Modify the list at line 11 to add more keywords that are filtered.
#This script has no requirements, all tools used are shipped with X.org
#It does, however, assume that you use ALSA to control your sound.
#Just run the script from the command line after you start Spotify.
#Stop the script with Ctrl-C.

#Importing stuff
import sys
import os
import time
from subprocess import Popen, PIPE

#List of commercial que-words:
list = ["Spotify - Spotify", "Coolpix", "Kims", "Centrebet", "Unibet", "Billettservice", "Betsson", "Viasat", "FIFA", "Chiquita", "Luftfart", "Sommerslagere", "Sony Music", "Red Bull", "Logitech", "EMI", "Ikea", "NKF", "Sony Ericsson", "Film&Kino", "McDonalds", "Warner Music"]
mute = False

#We run an endless loop:
while (True):
	cmd = "xwininfo -children -root | awk '/spotify/{print $1}'" #Get window ID of spotify
	p = Popen(cmd, shell=True, stdout=PIPE)
	p.wait()
	wid = p.communicate()[0] #We save the ID
	id = wid.split()
	pid = '' #Make sure pid survives
	for l in id: #Sometimes a 'ghost' spotify window exists. Then id is a list, and for each l in id,
		cmd = 'xprop -id ' + l + ' | grep -i "WM_NAME(COMPOUND_TEXT)"' #We check if this l is the correct one.
		p = Popen(cmd, shell=True, stdout=PIPE)
		p.wait()
		testname = p.communicate()[0]
		if testname != '': #If the title is not blank, the current element is the correct one. Then we set
			pid = l
			break
	if pid != '': #If spotify is running
		cmd = 'xprop -id ' + pid + ' | grep -i "WM_NAME(COMPOUND_TEXT)"' #We get the window title of spotify
		p = Popen(cmd, shell=True, stdout=PIPE)
		p.wait()
		name = p.communicate()[0]
		cumul = 0
		for i in list: #For all the commercial names we defined above
			f = name.find(i)
			cumul += f
		if mute == False and cumul != -1*len(list):#If commercial is playing and mute is off, turn mute on.
			mute = True
			cmd = 'amixer -c 0 sset Master toggle'
			p = Popen(cmd, shell=True, stdout=PIPE)
			p.wait()
		elif mute == True and cumul == -1*len(list): #Else if commercial is not playing and mute is on, turn mute off.
			mute = False
			cmd = 'amixer -c 0 sset Master toggle'
			p = Popen(cmd, shell=True)
			p.wait()

	time.sleep(1) #We check every second.

