All pastes #928029 Raw Edit

consolel_log()

public text v1 · immutable
·published 2008-03-04 19:16 UTC
rendered paste body
No console_log

WIKIPBX ----------------------------------------------------------------------
<action application="set" data="call_timeout=5"/>
<action application="set" data="continue_on_fail=true"/>
<action application="set" data="hangup_after_bridge=true"/>
<action application="bridge" data="sofia/Local/102%192.168.1.95"/>
<action application="set" data="mailbox=stevey@win-ent.com"/>
<action application="set" data="vmaction=record"/>
<action application="python" data="wikipbx.ivr.voicemail"/>

FREESWITCH CONSOLE -----------------------------------------------

2008-03-04 19:12:47 [NOTICE] mod_sofia.c:1047 sofia_receive_message() Pre-Answer sofia/Local/100@192.168.1.95:5060!
2008-03-04 19:12:47 [NOTICE] mod_python.c:86 eval_some_python() Invoking py module: wikipbx.ivr.voicemail
-------------> cepstral voice playes here  <-----------------
2008-03-04 19:12:47 [NOTICE] switch_core_session.c:732 switch_core_session_thread() Session 7 (sofia/Local/102) Ended
2008-03-04 19:12:47 [NOTICE] switch_core_session.c:734 switch_core_session_thread() Close Channel sofia/Local/102 [CS_HANGUP]                                                                            


VOICEMAIL.PY--------------------------------------------------------------------------
"""
WikiPBX web GUI front-end for FreeSWITCH <www.freeswitch.org>
Copyright (C) 2007, Branch Cut <www.branchcut.com>
License Version: MPL 1.1
"""

import os
os.environ['DJANGO_SETTINGS_MODULE']='wikipbx.settings'


from freeswitch import *
from wikipbx.wikipbxweb.models import *
from wikipbx import mailutil
reload(mailutil)
import wikipbx.ivr.baseivr
reload(wikipbx.ivr.baseivr)
from wikipbx.ivr.baseivr import BaseIvr
from pytz import timezone
import datetime
import md5

class VoicemailIvr(BaseIvr):

    def __init__(self, session):
        super(VoicemailIvr, self).__init__(session)
        self.mailbox_name = self.session.getVariable("mailbox")
        self.userprofile = None
        if self.mailbox_name and self.mailbox_name != "None":
            mbn = self.mailbox_name
            userprofs = UserProfile.objects.filter(account=self.account,
                                                   user__email=mbn)
            if userprofs:
                self.userprofile = userprofs[0]
        self.uuid = self.session.getVariable("uuid")

        # the number dialed, we can use this to match it with an
        # existing endpoint, and then from there figure out what
        # userprofile to use for storing voicemail
        self.dest_num = self.session.getVariable("destination_number")
        if not self.dest_num or self.dest_num == "None":
            self.dest_num = None


class VoicemailPlayerIvr(VoicemailIvr):

    def __init__(self, session):
        super(VoicemailPlayerIvr, self).__init__(session)
        self.login_attempts = 0

    def main(self):

        logged_in = self.login()
        if not logged_in:
            return
        self.browse_voicemails()

    def browse_voicemails(self):
        if self.userprof:
            voicemails = Voicemail.objects.filter(account=self.account,
                                                  userprofile=self.userprof)
            voicemails = voicemails.order_by("id")
        else:
            # account wide login
            voicemails = Voicemail.objects.filter(account=self.account,
                                                  userprofile__isnull=True)
        if not voicemails:
            self.speak("Sorry, there are no voicemail messages")
            return

        self.speak("There are %s voicemail messages" % len(voicemails))
        for voicemail in voicemails:
            self.play_voicemail(voicemail)

        self.speak("There are no more voicemail messages.  Goodbye")


    def play_voicemail(self, voicemail):
        self.speak("Going to play voicemail %s" % voicemail.id)
        self.session.streamFile(voicemail.get_path())
        self.post_play_options(voicemail)

    def post_play_options(self, voicemail):
        thing2say = "Press 1 to replay voicemail. "
        thing2say += "Press 2 to delete voicemail. "

        tempfile = self.make_tts_file(thing2say)
        in_rslt = self.session.playAndGetDigits(1,1,3,6000,
                                                "*#",tempfile,
                                                "", "","")[1]
        console_log("INFO","user input: %s\n" % str(in_rslt))
        if not in_rslt:
            self.speak("Sorry, no input detected")
        else:
            if int(in_rslt) == 1:
                self.play_voicemail(voicemail)
            elif int(in_rslt) == 2:
                vmid = voicemail.id
                voicemail.delete()
                self.speak("Voicemail %s has been deleted" % str(vmid))
            else:
                self.speak("%s is an invalid option.  Goodbye" %
                           in_rslt)



    def login(self):

        if self.login_attempts > 5:
            self.speak("Sorry, maximum number of login attempts exceeded")
            return False

        self.login_attempts += 1


        # TODO: only prompt if ${sip_authorized} is not "true")
        # prompt them to enter mailbox id
        thing2say = "Welcome to voicemail player.  Please enter mailbox i d followed by the pound sign"
        tempfile = self.make_tts_file(thing2say)
        in_rslt = self.session.playAndGetDigits(1,10,3,4000,
                                                "*#",tempfile,
                                                "", "","")[1]
        console_log("INFO","user input: %s\n" % str(in_rslt))
        if not in_rslt:
            self.speak("You did not enter anything.  Goodbye")
            return False

        # check if an user exists in the current account
        # with the mailbox id the person entered
        self.userprof = None
        userprofs = UserProfile.objects.filter(account=self.account,
                                               mailbox=in_rslt)
        if not userprofs:
            speakable = " ".join(in_rslt)
            self.speak("Sorry, no mailbox with i d: %s" %
                       speakable, stream=False)
            return False
        else:
            self.userprof = userprofs[0]

        # prompt them to enter password
        thing2say = "Please enter mailbox password followed by the pound sign"
        tempfile = self.make_tts_file(thing2say)
        in_rslt = self.session.playAndGetDigits(1,10,3,4000,
                                                "*#",tempfile,
                                                "", "","")[1]
        console_log("INFO","user input: %s\n" % str(in_rslt))
        if not in_rslt:
            self.speak("You did not enter anything.  Goodbye", stream=False)
            return False

        if not self.userprof.get_vm_password() == in_rslt:
            speakable = " ".join(in_rslt)
            self.speak("Sorry %s is not the correct password" % speakable,
                       stream=False)
            return self.login()

        return True

class VoicemailRecorderIvr(VoicemailIvr):

    def __init__(self, session):
        super(VoicemailRecorderIvr, self).__init__(session)

    def main(self):
        #self.speak("Welcome to voicemail recorder.")
        #self.speak("Please start speaking after the beep. "
        #                   "Press any key when finished. ")
        if os.path.isfile("/usr/local/freeswitch/sounds/en/us/callie/voicemail/8000/vm-record_message.wav") == true:
            console_log("debug","/usr/local/freeswitch/sounds/en/us/callie/voicemail/8000/vm-record_message.wav")
            self.session.streamFile("/usr/local/freeswitch/sounds/en/us/callie/voicemail/8000/vm-record_message.wav")
        self.playbeep()

        # if there is no userprofile specified, we are going to
        # drop the voicemail into _each_ account admin's vm box
        self.admin = None
        if not self.userprofile:
            # choose the first account admin
            self.admin = self.account.admins.all()[0]
            voicemail = Voicemail(uuid=self.uuid,
                                  account=self.account,
                                  userprofile=self.admin)
            voicemail.save()
        else:
            voicemail = Voicemail(uuid=self.uuid,
                                  account=self.account,
                                  userprofile=self.userprofile)
            voicemail.save()

        vm_path = voicemail.get_path()

        max_len = 600 # 10 mins
        silence_threshold = 500
        silence_secs = 5
        self.session.recordFile(vm_path,
                                max_len,
                                silence_threshold,
                                silence_secs)


        # TODO: allow them to listen, re-record
        # check asterisk vmail features
        self.speak("Thank You.  Your voicemail has been "
                           "recorded.  Goodbye")

        # make sure its non empty, if so, just delete it and
        # skip the email notifications
        if voicemail.get_audio_length() == 0:
            console_log("debug", "voicemail audio is empty, deleting\n")
            voicemail.delete()
            return

        # If account-wide, copy it to all _other_ admins mailboxes
        if not self.userprofile:
            admins = self.account.admins.all()
            for otheradmin in admins:
                if otheradmin == self.admin:
                    # skip the 1st admin we used earlier, already has vm
                    continue
                voicemail_copy = Voicemail(uuid=self.uuid,
                                           account=self.account,
                                           userprofile=otheradmin)
                voicemail_copy.save()
                # copy actual file
                voicemail.copy_audio(voicemail_copy.get_path())

        # TODO: add a direct link back to the webserver which displays all
        # details on the voicemail.  currently links back to homepage.

        # use this approach until hangup hook works ...  but will this code
        # get called if user hangs up abruptly?  so far in testing, seems
        # to work.
        console_log("INFO","sending email, session: %s\n" % str(self.session))
        caller_id_number = self.session.getVariable("caller_id_number")
        caller_id_name = self.session.getVariable("caller_id_name")
        login_link = ('<a href="http://%s:%s">login</a>' %
                      (self.account.server.fqdn,
                       self.account.server.http_port))
        msg_body = ("You have received a new voicemail (id=%s) "
                    "from %s (%s).  Please %s to listen to your message." %
                    (voicemail.id, caller_id_number,
                     caller_id_name, login_link))

        # if a mailbox (web user) was explicitly specified, use email
        # associated with that web user.  otherwise, send a notice
        # to all account admins
        if self.userprofile:
            recipients = [self.userprofile.user.email]
        else:
            admins = self.account.admins.all()
            recipients = [x.user.email for x in admins]
        mailutil.acct_send(recipients=recipients,
                           subject="New voicemail: %s" % voicemail.id,
                           msg_body=msg_body,
                           account=self.account)
        console_log("INFO","sent email, session: %s\n" % str(self.session))

        # TODO: run other voicemail triggers (listen to events)


def handler(uuid):
    if not uuid:
        console_log("info", "\nNo uuid given\n")
        return
    session = PySession(uuid)
    try:
        vmaction = session.getVariable("vmaction")
        console_log("info", "\nvmaction: %s\n" % str(self.vmaction))
        if vmaction == "play":
            vmplayer = VoicemailPlayerIvr(session)
            vmplayer.main()
        elif vmaction == "record":
            vmrecorder = VoicemailRecorderIvr(session)
            vmrecorder.main()
        else:
            console_log("error", "Invalid voicemail action: %s\n" % vmaction)
            session.set_tts_parms("cepstral", "william")
            session.speak("Sorry, the voicemail system had an error. "
                          "Error code 101")
    except Exception, e:
        console_log("error", "Error running voicemail IVR: %s\n" % e)
        session.set_tts_parms("cepstral", "william")
        session.speak("Sorry, the voicemail system had an error. "
                      "Error code 102")
-----------------------------------------------------------------------------------
thanks
thaper