def check_personalized_followup_to(caller, msg, sessionID,
                                   sayPersonNameFunc=None):
    """
    called by dsh_django2.check_personalized_messages().
    if the followup_to field of the personalized message points
    to caller himself, we want to play the original question
    that resulted in this personalized message.
    modeled after check_personalized_messages().
    sayPersonNameFunc is dsh_django2.say_message_from_name().
    """

    dsh_utils.db_print('check_personalized_followup_to: entered.', 151)
    if not msg or not caller or not msg.owner:
        dsh_utils.db_print('check_personalized_followup_to: nulls.', 151)
        return
    
    question = msg.followup_to
    if not question:
        dsh_utils.db_print('check_personalized_followup_to: no followup_to.',
                           151)
        return

    if question.owner.dsh_uid != caller.dsh_uid:
        #dsh_utils.db_print('check_personalized_followup_to: not same owner.',
        #                   151)
        #return
        pass

    if question.owner.ptype != 'USR':
        #
        # we will read the question back ONLY if the question
        # was left by a "user."
        #
        dsh_utils.db_print('check_personalized_followup_to: '+\
                           'question not by user type.', 151)
        return

    chopped = get_sln_path_for_asterisk(question)
    if not chopped:
        message = 'dsh_common_agi.check_personalized_followup_to: ' +\
                  'unable to find .sln file: ' + repr(question)
        dsh_agi.report_event(message, reportLevel='ERR', sessionID=sessionID)
        dsh_utils.give_bad_news(message, logging.error)
        return

    say_date(question)

    if sayPersonNameFunc:
        dsh_utils.db_print('check_personalized_followup_to: saying name.', 151)
        sayPersonNameFunc(question.owner)

    dsh_agi.say_it(chopped)
    dsh_agi.say_it('beep')
def main():
    prefix = dsh_config.lookup('log_file_dir')
    logName = dsh_config.lookup('log_file_name')
    
    dsh_utils.check_logging(prefix, logName)
    dsh_utils.db_print('dsh_test1: entered...', 93)
    
    dsh_agi.read_env()

    testOut1 = prefix + 'test_out1'
    testOut2 = prefix + 'test_tanuja'
    testIn1 = prefix + 'test_in1'
    dsh_agi.say_it(testOut1)
    #dsh_agi.say_it(testOut2)
    #dsh_agi.say_it('/var/lib/asterisk/sounds/demo-congrats')
    dsh_agi.record(testIn1)
    dsh_agi.say_it(testIn1)
    dsh_utils.give_news('dsh_test1: done.')
def demo_reply_prompt_confirm(recent, itemTable, keyWordTable, eventTable,
                              sessionID=''):
    """
    10/04/09: called by demo_reply().
    modeled after dsh_django2.handle_staff_caller().
    """

    funcName = 'dsh_common_agi.demo_reply_prompt_confirm:'
    count = 0
    promptDir = dsh_common_config.lookup('DSH_PROMPT_DIR')
    demoPress1 = dsh_common_config.lookup('DSH_PROMPT_DEMO_PRESS1_SEND')
    demoPress1 = os.path.join(promptDir, demoPress1)
    timeOut1 = dsh_config.lookup('DSH_PROMPT_WAIT1')
    maxRetries = dsh_common_config.lookup2('STAFF_RETRIES')
    demoSending = dsh_common_config.lookup('DSH_PROMPT_DEMO_SENDING_IN8')
    demoSending = os.path.join(promptDir, demoSending)

    while True:
        count += 1

        if count > maxRetries:
            say_goodbye()
            return True

        choice = dsh_agi.get_digits(demoPress1, 1, timeOut=timeOut1)
        dsh_utils.db_print('%s the choice is: %s.' % (funcName, repr(choice)),
                           168)

        if choice == None or choice == '' or choice == '*':
            say_goodbye()
            return True

        if choice == '1':
            dsh_common_db.attempt_demo_reply_now(
                recent, itemTable, keyWordTable, eventTable,
                sessionID=sessionID)
            dsh_agi.say_it(demoSending)
            say_goodbye()
            return True

        continue

    return True
def say_caller_name(caller, sayThisMessageIsForPath, sayFromPath,
                    endSentencePath=None):
    """called by dsh_django2.py.
    says the mp3 name of the caller if there is one.
    modeled after dsh_django2.say_person_name()
    """

    if not caller:
        return

    if not caller.spoken_name:
        return

    spokenName = field_to_sln_path(caller.spoken_name)
    if not spokenName:
        return

    #
    # "this message"
    #
    dsh_agi.say_it(sayThisMessageIsForPath)
    #
    # "Randy"
    #
    dsh_agi.say_it(spokenName)
    #
    # "is for"
    #
    dsh_agi.say_it(sayFromPath)

    if caller.organization and \
       caller.organization.spoken_name:
        placeSpokenName = field_to_sln_path(caller.organization.spoken_name)
    else:
        return

    dsh_agi.say_it(placeSpokenName)

    if endSentencePath:
        #
        # end of sentence thingie.
        #
        dsh_agi.say_it(endSentencePath)
def say_digits(number):
    """
    10/04/09: called by read_back_caller_number().
    says the phone numbers
    """

    dsh_common_db.init_log(quiet=True)
    funcName = 'dsh_common_agi.say_digits:'
    number = number.strip()

    soundDir = dsh_common_config.lookup('DSH_PROMPT_DIR')
    sorrySound = dsh_config.lookup('DSH_PROMPT_SORRY')
    sorrySound = os.path.join(soundDir, sorrySound)
    
    if not number:
        dsh_agi.say_it(sorrySound)
        return

    try:
        inumber = int(number)
    except:
        message = '%s not a number: %s.' % (funcName, number)
        dsh_agi.report_event(message, reportLevel='ERR')
        dsh_utils.give_bad_news(message, logging.error)
        dsh_agi.say_it(sorrySound)
        return

    datesDir = os.path.join(soundDir, 'dates')
    dateDir = os.path.join(datesDir, 'dates')

    for digit in number:
        digit = '0' + digit
        sound = os.path.join(dateDir, digit)
        dsh_agi.say_it(sound)
def say_doctor_name(msg, sessionID=None, doctor=None):
    """
    called by check_personalized_message().
    give the personalized message sent by a doctor.
    the difference here is that no extra before and after snippets.
    we'll play the doctor's self-introduction by itself.
    modeled after say_caller_name().
    doctor is not None when called by dsh_django2.welcome_doctor().
    """

    if doctor:
        owner = doctor
    else:
        owner = msg.owner
        
    if not owner:
        return
    if not owner.spoken_name:
        return
    spokenName = field_to_sln_path(owner.spoken_name, sessionID=sessionID)
    if not spokenName:
        return
    dsh_agi.say_it(spokenName)    
def read_back_caller_number(item, fromPhone=False, sessionID=''):
    """
    10/04/09: called by demo_reply().  read back the phone number of the
    most recent caller.
    """

    response = ''
    funcName = 'dsh_common_agi.read_back_caller_number:'
    
    caller = item.owner
    phoneNumber = caller.phone_number

    if not phoneNumber:
        message = '%s no phone number: %s.' % (funcName, caller.dsh_uid)
        response += dsh_utils.red_error_break_msg(message)
        dsh_agi.report_event(message, reportLevel='ERR', sessionID=sessionID)
        dsh_utils.give_bad_news(message, logging.error)
        return (False, response)

    message = 'Send an immediate reply to %s @ %s? ' %\
              (caller.__unicode__(), phoneNumber)
    message += '<a href="/senddemoreplyconfirmed/%s">Confirm</a>?' %\
               (item.dsh_uid,)
    response += dsh_utils.black_break_msg(message)

    if fromPhone:
        promptDir = dsh_common_config.lookup('DSH_PROMPT_DIR')
        last4 = dsh_common_config.lookup('DSH_PROMPT_DEMO_LAST4')
        dsh_agi.say_it(os.path.join(promptDir, last4))
        howManyDigits = dsh_config.lookup('HIDE_PHONE_DIGITS')
        lastDigits = phoneNumber[-howManyDigits:]
        dsh_utils.give_news(
            'demo to phone: %s, last 4 digits: %s.' %\
            (phoneNumber, lastDigits), logging.info)
        say_digits(lastDigits)

    return (True, response)
def main():
    global globals4signal

    globals4signal['start_time'] = datetime.datetime.now()

    #
    # check the voice data directories.
    #
    success,inDir,outDir,outFile = init_dirs()
    if not success:
        sys_exit(1)

    #
    # get the AGI environment variables.
    #
    env = dsh_agi.read_env()
    if env == {}:
        dsh_utils.give_bad_news('dsh_simple1: failed to read agi envs.',
                                logging.error)
        sys_exit(1)

    #
    # log the caller info.
    # and construct a recorded file name based on caller info.
    #
    phoneNumber,callerInfo = lookup_number(env)
    logStr = dsh_map.log_caller_info(phoneNumber, callerInfo)
    globals4signal['log_str'] = logStr
    callerInfoStr = dsh_map.info2str(phoneNumber, callerInfo)
    callerInfoStr = dsh_utils.date_time_rand2() + '_' + callerInfoStr

    #
    # looks like: 090702_200101_38_09935237793_DSH_Randy-Wang.gsm
    #
    dsh_utils.db_print('dsh_simple1: callerInfoStr: ' + callerInfoStr, 94)


    #
    # setting up signal handler for hangup.
    # the handler will attempt to do the file format conversion.
    #
    signal.signal(signal.SIGHUP, hangup_signal_handler)
    

    #
    # play the out file.
    #
    dsh_agi.say_it(outFile)

    #
    # record it.
    #
    inFile = os.path.join(inDir, callerInfoStr)
    globals4signal['in_file'] = inFile
    globals4signal['start_record'] = datetime.datetime.now()
    dsh_agi.record(inFile)

    #
    # say it back.
    #
    #dsh_agi.say_it(inFile)

    dsh_utils.give_news('dsh_simple1: recording done.')

    #
    # convert file format too with a proper hangup (pressing the # key).
    #
    hangup_signal_handler(0, None)
def main():
    global globals4signal

    globals4signal['start_time'] = datetime.datetime.now()

    init_log()

    #
    # find or create unknown org and unknown person.
    #
    try:
        unknownOrg,unknownPerson = init_unknown_org_person()
    except:
        message = 'dsh_django: init_unknown_org_person failed.'
        dsh_utils.give_bad_news(message, logging.critical)
        dsh_agi.report_event(message, reportLevel='CRT')
        sys_exit(1)

    #
    # get the outgoing voice from the database.
    #
    answer = get_outgoing_voice_from_db()
    if not answer:
        sys_exit(1)
    outVobj,outgoingVoice = answer

    #
    # get the AGI environment variables.
    #
    env = dsh_agi.read_env()
    if env == {}:
        dsh_utils.give_bad_news('dsh_django1: failed to read agi envs.',
                                logging.error)
        sys_exit(1)

    #
    # look up the phone number in the django database.
    # if not found in the database, we do something about unknown callers.
    # XXX
    #lookupResult = lookup_number_in_db(env, debugCheat=True)
    lookupResult = lookup_number_in_db(env)
    caller = determine_unknown_caller(unknownOrg, unknownPerson, lookupResult)
    dsh_utils.db_print('dsh_django1: the caller determined to be: ' +
                       repr(caller), 100)
    globals4signal['caller_dude'] = caller
    
    #
    # setting up signal handler for hangup.
    # the handler will attempt to do the file format conversion.
    # and then saving into the django database.
    #
    signal.signal(signal.SIGHUP, hangup_signal_handler)


    #
    # check whether there're any personalized messages for this caller.
    #
    check_personalized_messages(caller)
    
    
    #
    # play the outgoing file.
    #
    # XXX
    dsh_agi.say_it(outgoingVoice)
    time.sleep(1)
    dsh_agi.say_it('beep')
    dsh_agi.say_it('beep')


    #
    # determine the input file name and record it.
    #
    inVobj,incomingFullName=determine_recorded_file_name(caller, outVobj)
    if incomingFullName == None:
        dsh_utils.give_bad_news(
            'dsh_django1: determine_recorded_file_name failed: ',
            logging.critical)
        sys_exit(1)
    dsh_utils.db_print('dsh_django1: incomingFullName: ' + incomingFullName,
                       101)
    globals4signal['db_in_obj'] = inVobj
    globals4signal['start_record'] = datetime.datetime.now()
    globals4signal['in_file'] = incomingFullName
    dsh_agi.record(incomingFullName)
    dsh_utils.db_print('dsh_django1: record call ends.', 101)
    time.sleep(1)
    dsh_utils.give_news('dsh_django1: recording done.')
    dsh_agi.say_it('auth-thankyou')
    dsh_agi.say_it('vm-goodbye')

    #
    # convert file format too with a proper hangup (pressing the # key).
    #
    hangup_signal_handler(0, None)
def check_personalized_messages(caller):
    """does this caller have any unheard personalized messages?"""

    #
    # does this caller have any personal messages intended for him?
    #
    messages = caller.message_for_me.all()
    dsh_utils.db_print('dsh_django1.check_personalized_message: msg: ' +\
                       repr(messages), 108)
    if not messages:
        return
    
    for msg in messages:
        #
        # the message needs to be "personalized" and it needs to be "active."
        #
        maybe_deactivate_personal_message(msg)
        if not msg.active:
            dsh_utils.db_print('not active.', 108)
            continue
        if msg.itype != 'P':
            dsh_utils.db_print('not personalized: ' + msg.itype, 108)
            continue

        #
        # has this caller heard this before?
        #
        heardEvents = Event.objects.filter(
            action='HERD', owner=caller.id, dsh_uid_concerned=msg.dsh_uid)
        if heardEvents:
            dsh_utils.db_print('already heard, skipping: ' + msg.dsh_uid, 108)
            continue

        #
        # find out the .sln file path name.
        #
        chopped = get_sln_path_for_asterisk(msg)
        dsh_utils.db_print(
            'dsh_django1.check_personalized_message: sln path: ' +\
            repr(chopped), 108)

        if not chopped:
            message = 'dsh_django1.check_personalized_message: ' +\
                      'unable to find .sln file: ' + repr(msg)
            dsh_agi.report_event(message, reportLevel='ERR')
            dsh_utils.give_bad_news(message, logging.error)
            continue

        #
        # now play the personalized message and compute how long it lasted.
        #
        beginTime = datetime.datetime.now()
        dsh_agi.say_it(chopped)
        endTime = datetime.datetime.now()
        time.sleep(1)
        deltaSeconds = (endTime - beginTime).seconds

        #
        # remember the fact that this caller has heard this message.
        #
        dsh_agi.report_event(
            'personalized message heard.',
            item=msg,
            action='HERD',
            phone_number=caller.phone_number,
            owner=caller,
            call_duration=deltaSeconds)
        dsh_utils.give_news('dsh_django1.check_personalized_message: heard: '+\
                            msg.dsh_uid, logging.info)

        #
        # if everyone has heard this personalized message,
        # we should just deactivate it.
        #
        maybe_deactivate_personal_message(msg)

        #
        # beep twice at the end of each message.
        #
        dsh_agi.say_it('beep')
        dsh_agi.say_it('beep')
def say_goodbye():
    time.sleep(1)
    dsh_agi.say_it('auth-thankyou')
    dsh_agi.say_it('vm-goodbye')
    time.sleep(1)
def say_date(item):
    """called by dsh_django2.test_call_say_time(), and
    dsh_django2.say_person_name().
    """

    time = item.modify_datetime
    
    soundDir = dsh_common_config.lookup('DSH_PROMPT_DIR')
    datesDir = os.path.join(soundDir, 'dates')
    
    thisMessage = os.path.join(datesDir, 'this_message')
    wasRecorded = os.path.join(datesDir, 'was_recorded')
    
    dateDir = os.path.join(datesDir, 'dates')
    monthDir = os.path.join(datesDir, 'months')
    yearDir = os.path.join(datesDir, 'year')

    yStr = time.strftime('%#y')
    mStr = time.strftime('%#m')
    dStr = time.strftime('%#d')

    testDate = os.path.join(dateDir, dStr)
    testMonth = os.path.join(monthDir, mStr)
    testY2k = os.path.join(yearDir, '2000')
    testYear = os.path.join(dateDir, yStr)

    dsh_agi.say_it(thisMessage)
    dsh_agi.say_it(testDate)
    dsh_agi.say_it(testMonth)
    dsh_agi.say_it(testY2k)
    dsh_agi.say_it(testYear)
    dsh_agi.say_it(wasRecorded)