#!/usr/bin/env python
"""Biff for voice mail; plays a sound when voice mail arrives

$Id: mvmbiff,v 1.1 1998/05/07 06:20:15 dan Exp $

Copyright © 1998 by Dan Fandrich <dan@fch.wimsey.bc.ca>

mvmbiff is even quicker and dirtier than mvmmessage.  It sits in the
background, consuming valuable virtual memory, polling the voice mail
directory every few seconds or minutes looking for voice mail.  If a
voice message exists in the mailbox, then it plays a sound file to the
speaker and waits again.  This cycle stops when all voice messages are
removed, probably with mvm or mvmmessage.

Usage:
  mvmbiff mailbox# audiofile.au [delay]

for example:
  mvmbiff 0 /usr/local/audio/rooster.au 300
Announce the arrival of new mail with the sound of a rooster crowing once
every 5 minutes.

$Log: mvmbiff,v $
Revision 1.1  1998/05/07  06:20:15  dan
Initial revision

"""

# mvmbiff configuration options

# seconds between audio plays
REPEAT_DELAY = 20

# voice mail spool directory
VM_BOXES = '/var/spool/voice/mailboxes'

# Play a file directly to the audio device if 1, otherwise use PLAY_CMD
RAW_PLAY = 0
PLAY_CMD = 'play %s'	 # command to play audio file, only when RAW_PLAY is 0
AUDIO_DEV = '/dev/audio' # audio device, only used when RAW_PLAY is 1

# Start of program

import os
from sys import argv, exit
from time import sleep
from string import atoi

def spawnplayfile(file):
	"Play sound file via an external program"
	os.system(PLAY_CMD % file)

def rawplayfile(file):
	"Play .au file through the sound card without spawning an external program"
	f = open(file)
	try:
		a = open(AUDIO_DEV,'w')
	except IOError:
		# audio device is probably in use
		pass
	else:
		data = f.read(1024)
		while data:
			a.write(data)
			data = f.read(1024)
		a.close()
		f.close()

def playfile(file):
	"Choose one of the above functions to play an audio file"
	if RAW_PLAY:
		rawplayfile(file)
	else:
		spawnplayfile(file)

def checkforvmail(dir):
	"Returns TRUE if voice mail is waiting in the given directory"
	return filter(lambda x: x[0] == 'm', os.listdir(dir))

def mvmbiff(userid, audio, delay):
	vmaildir = os.path.join(VM_BOXES, userid)
	try:
		open(audio)
	except IOError:
		print "Can't open audio file ",audio
		exit(1)

	try:
		os.listdir(vmaildir)
	except:
		print "Can't access voice mail directory",vmaildir
		exit(1)

	while 1:
		if checkforvmail(vmaildir):
			playfile(audio)
		try:
			sleep(delay)
		except KeyboardInterrupt:
			return

if __name__=='__main__':
	if len(argv) < 3:
		print 'Usage: mvmbiff mailbox# audiofile.au [delay]'
		exit(2)

	if len(argv) >= 4:
		delay = atoi(argv[3])
	else:
		delay = REPEAT_DELAY
	mvmbiff(argv[1], argv[2], delay)
	exit(0)
