예제 #1
0
def dump_one(obj, define, tarPath):
    """called by dump_selected() below, dumps one django object into a
    dump file.
    obj is an object retrieved from django db.
    each dumped object is a dictionary.  of the form:
    FieldName: [FieldType, FieldValue],
    'define' is the object definition coming from dsh_dump_models.py.
    it's a dictionary, of the form:
    FieldName: [FieldType],
    """

    errorMsg = ''
    ans = '{\n'
    for fieldName,specs in define.iteritems():
        fieldType = specs[0]

        errorMsg += dsh_utils.black_break_msg_debug(
            'loop iteration: ' + fieldName + ' - ' + fieldType, 124)
        
        try:
            value = getattr(obj, fieldName)
        except:
            message = 'dsh_dump.dump_one: exception: ' + fieldName + '.  '
            dsh_django_utils.error_event(message, errorLevel='CRT')
            errorMsg += dsh_utils.red_error_break_msg(message)
            continue

        if fieldType == 'StrType':
            if not value:
                continue
            #
            # escape the double quote character.
            #
            value = value.replace('"', '\\"')
            oneField = "    '%s': ['%s', \"\"\"%s\"\"\"],\n" % \
                       (fieldName, fieldType, value)
            ans += oneField
            continue
            
        if fieldType == 'BoolType':
            oneField = "    '%s': ['%s', %s],\n" % \
                       (fieldName, fieldType, repr(value))
            ans += oneField
            continue

        if fieldType == 'IntType':
            oneField = "    '%s': ['%s', %s],\n" % \
                       (fieldName, fieldType, str(value))
            ans += oneField
            continue

        if fieldType == 'DateType':
            if not value:
                continue
            oneField = "    '%s': ['%s', %s],\n" % \
                       (fieldName, fieldType, repr(value))
            ans += oneField
            continue

        if fieldType == 'FileType':
            if not value:
                continue
            dumpFileName = dsh_agi.abs_url_to_relative(value.url)
            dsh_django_utils.debug_event(
                'dsh_dump.dump_one: url: ' + dumpFileName, 8)
            dsh_django_utils.debug_event(
                'dsh_dump.dump_one: tarPath: ' + tarPath, 8)

            success,tarMsg = add_to_tar(dumpFileName, tarPath)
            errorMsg += tarMsg
            if success:
                errorMsg += dsh_utils.black_break_msg(
                    'tar: ' + tarPath + \
                    '   «   ' + \
                    dumpFileName)
            else:
                errorMsg += dsh_utils.red_error_break_msg(
                    'tar command failed on: ' + dumpFileName)
                continue
            
            oneField = "    '%s': ['%s', \"\"\"%s\"\"\"],\n" % \
                       (fieldName, fieldType, dumpFileName)
            ans += oneField
            continue

        if fieldType == 'RequiredForeignOrgType' or \
               fieldType == 'RequiredForeignPersonType':
            if not value:
                errorMsg += dsh_utils.red_error_break_msg(
                    'missing required foreign org. or person.')
                continue
            foreignDshUid = value.dsh_uid

            oneField = "    '%s': ['%s', \"\"\"%s\"\"\"],\n" % \
                       (fieldName, fieldType, foreignDshUid)
            ans += oneField
            continue

        if fieldType == 'OptionalFollowUpsType' or \
               fieldType == 'OptionalOwnerType':
            #
            # like the above, except it's optional.
            # so if it's blank, we don't freak out.
            #
            if not value:
                continue
            foreignDshUid = value.dsh_uid

            oneField = "    '%s': ['%s', \"\"\"%s\"\"\"],\n" % \
                       (fieldName, fieldType, foreignDshUid)
            ans += oneField
            continue

        if fieldType == 'OptionalKeyWordsType' or \
           fieldType == 'OptionalPersonsType':
            #
            # the intended_audience field can be dealt with like this too.
            #
            if not value:
                continue
            dshUidList = get_dsh_uid_list(value)
            if not dshUidList:
                continue
            oneField = "    '%s': ['%s', %s],\n" % \
                       (fieldName, fieldType, repr(dshUidList))
            ans += oneField
            continue

        errorMsg += dsh_utils.red_error_break_msg(
            'unknown field type: ' + fieldType)
        

    ans += '}'
    return (ans, errorMsg)
예제 #2
0
def hangup_signal_handler(signum, frame):
    """attempt to do file format conversion upon a hangup.
    from .wav to .mp3.
    after conversion, we put it in the django database."""
    
    dsh_utils.db_print2('dsh_django1.signal_handler: entered...', 101)


    #
    # get the name of the file that was just recorded.
    #
    if not globals4signal.has_key('in_file'):
        dsh_utils.give_news('dsh_django1.hangup_signal_handler: ' +
                            'hangup before recording.', logging.info)
        sys_exit(0)

    inputFile = globals4signal['in_file']


    #
    # the recorded format is wav? if not, we don't convert.
    #
    fileFormat = dsh_config.lookup('record_file_format')
    if fileFormat != 'wav':
        message = 'dsh_django1.hangup_signal_handler: ' + \
                  "can't convert non-wav file: " + inputFile
        dsh_utils.give_bad_news(message, logging.error)
        dsh_agi.report_event(message, reportLevel='ERR')
        sys_exit(1)


    #
    # does the .wav file exist and is it non-zero sized?
    #
    inputWav = inputFile + '.wav'
    success,bytes = dsh_utils.get_file_size(inputWav)
    if not success:
        message = 'dsh_django1.hangup_signal_handler: ' + \
                  'no input file to convert: ' + \
                  inputWav
        dsh_utils.give_news(message, logging.info)
        #
        # looks like we could get this far even if there's
        # a hangup before record.  that's because the
        # signal doesn't seem to be delivered fast enough.
        # so globals4signal['in_file'] gets set anyhow.
        #
        #dsh_agi.report_event(message, reportLevel='ERR')
        sys_exit(1)
    if bytes == 0:
        message = 'dsh_django1.hangup_signal_handler: ' + \
                  'inputfile size 0: ' + inputWav
        dsh_utils.give_news(message, logging.info)
        dsh_agi.report_event(message, reportLevel='WRN')
        sys_exit(1)

    dsh_utils.db_print2('dsh_django1.signal_handler: ready to convert: ' +
                        inputWav, 101)


    #
    # where's the lame binary?
    #
    lamePath = dsh_config.lookup('lame_location')
    if not dsh_utils.is_valid_file(lamePath,
                                   msg='dsh_django1.hangup_signal_handler:'):
        message = 'dsh_django1.hangup_signal_handler: ' + \
                  'need to install lame.'
        dsh_utils.give_bad_news(message, logging.error)
        dsh_agi.report_event(message, reportLevel='CRT')
        sys_exit(1)


    #
    # stdout and stderr redirected to the log directory.
    #
    stdLogs = dsh_bizarro.stdio_logs_open(globals4signal['log_dir'])
    if not stdLogs:
        sys_exit(1)
    stdout,stderr = stdLogs


    #
    # the conversion command should be:
    # lame --resample 22.05 -b 24 test.wav test4.mp3
    #
    mp3Quality = dsh_config.lookup('lame_mp3_quality')
    outputMp3 = inputFile + '.mp3'
    #command = ffmpegPath + ' -i ' + inputWav + mp3Quality + outputMp3
    command = lamePath + mp3Quality + inputWav + ' ' + outputMp3

    try:
        ret = subprocess.call(command, shell=True,
                              stdout=stdout, stderr=stderr)
    except:
        ret = -1
        
    if ret != 0:
        message = 'dsh_django1.signal_handler: ' + \
                  'error in format conversion: ' + \
                  command
        dsh_utils.give_bad_news(message, logging.error)
        dsh_agi.report_event(message, reportLevel='CRT')
        sys_exit(1)

    dsh_utils.give_news('dsh_django1.signal_handler: conversion success: ' +
                        command, logging.info)

    dsh_utils.chmod_tree2(outputMp3, recurse=False)
    
    if not dsh_utils.cleanup_path(inputWav, 'dsh_django1.signal_handler'):
        message = 'dsh_django1.signal_handler: ' + \
                  'failed to remove original wav: ' + \
                  inputWav
        dsh_utils.give_bad_news(message, logging.warning)
        dsh_agi.report_event(message, reportLevel='WRN')


    #
    # calculate some more fields for saving in the database.
    #
    callDur,recDur = calculate_durations()
    dsh_utils.db_print2('dsh_django1.signal_handler: durations are: ' +
                        str(callDur) + ', ' + str(recDur), 101)


    #
    # dirPrefix is: /u/rywang/phone_data/django/
    # chop that off.
    # so what's left is:  /media/voice/09/07/090729_215817_85983050_08935237794_unknown-org_no-name.mp3
    # no, need to chop of '/media/' as well!
    # otherwise deletes don't work!
    #
    dirPrefix = dsh_config.lookup('PHONE_DATA_DJANGO_PATH')
    choppedFileName = outputMp3.replace(dirPrefix, '/')
    #chopAbsURLPrefix = dsh_config.lookup('ABS_URL_PREFIX_CHOP')
    #choppedFileName = choppedFileName.replace(chopAbsURLPrefix, '')
    choppedFileName = dsh_agi.abs_url_to_relative(choppedFileName)
    dsh_utils.db_print2('dsh_django1.signal_handler: choppedFileName is: '+\
                        choppedFileName, 105)


    #
    # FINALLY save the object in the django database!
    #
    item = globals4signal['db_in_obj']
    item.file = choppedFileName
    item.call_duration = callDur
    item.rec_duration = recDur
    try:
        item.save()
        dsh_utils.db_print2('dsh_django1.signal_handler: item saved: ' +
                            choppedFileName, 101)
    except:
        message = 'dsh_django1.signal_handler: saving in django failed: ' + \
                  choppedFileName, 101
        dsh_utils.give_bad_news(message, logging.critical)
        dsh_agi.report_event(message, reportLevel='CRT')
        sys_exit(1)

    #
    # no point continuing execution after hangup.
    #
    sys_exit(0)