Esempio n. 1
0
def add_to_tar(fileToAdd, tarFilePath):
    """adds fileToAdd to tarFilePath."""

    tarBin = dsh_django_config.lookup('TAR_PATH')
    mediaDir = dsh_config.lookup('MEDIA_DIR')
    
    try:
        os.chdir(mediaDir)

        if not dsh_utils.is_valid_file(fileToAdd, silent=True):
            message = 'dsh_dump.add_to_tar: invalid file: ' + fileToAdd
            tarMsg = dsh_utils.red_error_break_msg(message)
            dsh_django_utils.error_event(message, errorLevel='ERR')
            return (False, tarMsg)
        
        command = tarBin + ' rf ' + tarFilePath + ' ' + fileToAdd
        dsh_django_utils.debug_event(
            'dsh_dump.add_to_tar: command: ' + command, 8)
        result = dsh_utils.try_execute(command)
        if result == None:
            message = 'dsh_dump.add_to_tar: tar problem: ' + command
            dsh_django_utils.error_event(message, errorLevel='CRT')
            return (False, dsh_utils.red_error_break_msg(message))
        return (True, '')
    
    except:
        message = 'dsh_dump.add_to_tar: unknown tar problem: ' + command
        dsh_django_utils.error_event(message, errorLevel='CRT')
        return (False, dsh_utils.red_error_break_msg(message))
def select_starred():
    """called by views.select_starred()."""

    response = ''

    starred = dv2.db.models.Item.objects.filter(starred=True)
    if not starred:
        response += dsh_utils.red_error_break_msg(
            'no starred item.')
        return response

    count = 0
    for item in starred:
        if item.u17:
            continue
        item.u17 = True

        try:
            item.save(noLogging=True)
            count += 1
        except:
            message = 'dsh_selection.select_starred: failed to save: ' +\
                      item.dsh_uid
            dsh_django_utils.error_event(message, errorLevel='CRT')
            response += dsh_utils.red_error_break_msg(message)
            return response

    message = '%s starred item(s) selected.' % (str(count),)
    response += dsh_utils.black_break_msg(message)
    dsh_agi.report_event(message)

    return response
def auto_schedule_delete_all(force=False, sessionID=None):
    """
    moved from dsh_django_utils.py
    called by views.schedule_del_all().
    force=True when initiated by views.schedule_delete_all().
    """

    disableWipe = dsh_db_config.get('reschedule_wipe_disable')
    if not force and disableWipe:
        message = 'dsh_common_agi.auto_schedule_delete_all: ' +\
                  'note: wiping of existing schedule is disabled.'
        dsh_agi.report_event(message, sessionID=sessionID)
        return dsh_utils.black_break_msg(message)

    spoolDir = dsh_common_config.lookup('ASTERISK_DOT_CALL_DIR')
    if not dsh_utils.is_valid_dir(spoolDir, silence=True):
        message = 'dsh_common_agi.auto_schedule_delete_all: ' + \
                  'spool directory invalid: ' + spoolDir
        dsh_agi.report_event(message, reportLevel = 'CRT', sessionID=sessionID)
        return dsh_utils.red_error_break_msg(message)
    
    message = 'dsh_common_agi.auto_schedule_delete_all: ' +\
              'listdir() failed: ' + spoolDir
    try:
        listing = os.listdir(spoolDir)
        listing = dsh_common_db.filter_listdir_with_dbname(listing)
    except:
        dsh_agi.report_event(message, reportLevel = 'CRT', sessionID=sessionID)
        return dsh_utils.red_error_break_msg(message)

    message = dsh_utils.black_break_msg('deleting...')
    
    for one in listing:
        full = os.path.join(spoolDir, one)
        if not one:
            continue
        if os.path.isdir(full):
            continue
        if not dsh_utils.is_valid_file(full):
            continue
        if not one.endswith('.call'):
            continue

        dsh_utils.cleanup_path(
            full, 'dsh_common_agi.auto_schedule_delete_all: ')
        message += dsh_utils.black_break_msg(full)

    message += dsh_utils.black_break_msg('done.')
    return message
def clear_current_dial_set(personTable):
    """
    10/03/22:
    called by dsh_common_views.clear_current_dial_set().
    """

    response = ''
    people = personTable.objects.filter(current_dial=True)

    count = 0
    for person in people:
        person.current_dial = False

        try:
            person.save(noLogging=True)
            count += 1
        except:
            message = 'dsh_common_selection.clear_current_dial_set: ' +\
                      'failed to save person: ' + person.dsh_uid
            dsh_django_utils.error_event(message, item=person,
                                         errorLevel='CRT')
            response += dsh_utils.red_error_break_msg(message)
            return response

    response += dsh_utils.black_break_msg(
        'number of people removed from the current dial set: ' +\
        str(count) + '.')
    return response
Esempio n. 5
0
def reply_submit(request):
    """processes a reply form submission."""

    if dsh_django_request.deny_it(request):
        return please_log_in()
    
    response = page_header('process reply')

    if not 'from_red5' in request.POST or \
       not request.POST['from_red5'] or \
       not 'dsh_uid' in request.POST or \
       not request.POST['dsh_uid']:
        response += dsh_utils.red_error_break_msg('invalid submission.')
        response += page_footer()
        return HttpResponse(response)    

    dshUid = request.POST['dsh_uid']
    name = request.POST['from_red5']

    success,msgs,mp3Path = dsh_django_utils.convert_red5_flv_to_mp3(name)
    response += msgs

    if not success:
        response += page_footer()
        dsh_django_utils.cleanup_red5_conversion(success, name)
        return HttpResponse(response)

    success,msgs = dsh_django_utils.save_red5_mp3_in_django(
        mp3Path, originalItemDshUid=dshUid)
    response += msgs
    dsh_django_utils.cleanup_red5_conversion(success, name)

    response += page_footer()
    return HttpResponse(response)    
Esempio n. 6
0
def schedule_one_callee(request, personDshUid):
    """triggerred by clicking the little clock icon on the Person page.
    for scheduling auto-dialed call for one person."""
    
    if dsh_django_request.deny_it(request):
        return please_log_in()
    
    response = page_header('schedule auto-dialed call for one callee')
    response += '\n'

    disabled = dsh_db_config.get('auto_dial_disable')
    if disabled:
        response += dsh_utils.black_break_msg(
            'auto-dial is currently <font color=red><b>disabled</b></font>.')
        response += page_footer()
        return HttpResponse(response)
    
    persons = dvoice.db.models.Person.objects.filter(dsh_uid=personDshUid)
    if not persons or len(persons) > 1:
        message = 'views.schedule_one_callee: bad DshUid: ' + personDshUid
        response += dsh_utils.red_error_break_msg(message)
        dsh_django_utils.error_event(message, errorLevel='CRT')
        response += page_footer()
        return HttpResponse(response)

    person = persons[0]
    dsh_django_utils.check_auto_timed_calls_for_person(person)
    response += dsh_utils.black_break_msg('done.')
    response += dsh_utils.black_break_msg(
        'see the <a href=/scheduled>schedule</a>.')

    response += page_footer()
    return HttpResponse(response)
Esempio n. 7
0
def save_submit(request):
    """processes a red5 save.  very much like reply_submit().
    only simpler."""

    if dsh_django_request.deny_it(request):
        return please_log_in()
    
    response = page_header('process save')

    if not 'from_red5' in request.POST or \
       not request.POST['from_red5']:
        response += dsh_utils.red_error_break_msg('invalid submission.')
        response += page_footer()
        return HttpResponse(response)    

    name = request.POST['from_red5']

    success,msgs,mp3Path = dsh_django_utils.convert_red5_flv_to_mp3(name)
    response += msgs

    if not success:
        response += page_footer()
        dsh_django_utils.cleanup_red5_conversion(success, name)
        return HttpResponse(response)

    success,msgs = dsh_django_utils.save_red5_mp3_in_django(mp3Path)
    response += msgs
    dsh_django_utils.cleanup_red5_conversion(success, name)

    response += page_footer()
    return HttpResponse(response)    
def auto_dial_disable(request):
    """10/03/19: moved from view.py"""

    if dsh_django_request.deny_it(request):
        return views.please_log_in()

    response = views.page_header('disable auto-dial')

    dsh_db_config.set('auto_dial_disable', True)
    disabled = dsh_db_config.get('auto_dial_disable')
    
    if not disabled:
        message = 'views.auto_dial_disable: unexpected error.'
        response += dsh_utils.red_error_break_msg(message)
        dsh_django_utils.error_event(message, errorLevel='CRT')
        response += views.page_footer()
        return HttpResponse(response)

    response += spool_wipe_status_message()
    dsh_django_utils.auto_schedule_delete_all()

    response += dsh_utils.black_break_msg(
        'now <font color=red><b>disabled</b></font>. ' +\
        'wanna <a href="/autodialenable">re-enable</a>?')
    
    response += views.page_footer()

    dsh_agi.report_event('auto-dial disabled.')

    return HttpResponse(response)
def star(action='add'):
    """star the selection."""

    response = ''
    
    selectedItems = dv2.db.models.Item.objects.filter(u17=True)
    if not selectedItems:
        response += dsh_utils.red_error_break_msg(
            'no item selected currently.')
        return response

    count = 0
    for item in selectedItems:

        if action == 'add':
            if item.starred:
                continue
            item.starred = True
        else:
            if not item.starred:
                continue
            item.starred = False

        try:
            item.save(noLogging=True)
            count += 1
        except:
            message = 'dsh_selection.star: failed to save: ' +\
                      item.dsh_uid
            dsh_django_utils.error_event(message, errorLevel='CRT')
            response += dsh_utils.red_error_break_msg(message)
            return response

    if action == 'add':
        actDone = 'starred'
    else:
        actDone = 'de-starred'
        

    message = '%s item(s) %s.' % (str(count), actDone)
    response += dsh_utils.black_break_msg(message)
    dsh_agi.report_event(message, action='STAR')

    return response
Esempio n. 10
0
def email_selection(request):
    """emails the selected items."""

    if dsh_django_request.deny_it(request):
        return please_log_in()
    
    response = page_header('email the selected items')

    if not 'email_addresses' in request.POST or \
       not request.POST['email_addresses']:
        response += dsh_utils.red_error_break_msg('no email address given.')
        response += page_footer()
        return HttpResponse(response)    

    response += dsh_utils.black_break_msg_debug(
        'emails: ' + repr(request.POST['email_addresses']), 117)

    if ('comments' in request.POST) and request.POST['comments']:
        comments = request.POST['comments']
    else:
        comments = ''        

    attachVoice = False
    if 'attach_voice' in request.POST:
        response += dsh_utils.black_break_msg_debug(
            'attach: ' + repr(request.POST['attach_voice']), 117)
        if request.POST['attach_voice']:
            attachVoice = True
    else:
        response += dsh_utils.black_break_msg_debug('attach: not found.', 117)


    fields = {'dsh_url': False, 'lan_url': False, 'vpn_url': False}
    for varStr,varVal in fields.iteritems():
        if varStr in request.POST and request.POST[varStr]:
            fields[varStr] = True
    

    returnMsg,emailAddrs = dsh_django_utils.check_valid_email_addresses(
        request.POST['email_addresses'])
    if not emailAddrs:
        response += returnMsg
        response += page_footer()
        return HttpResponse(response)
    else:
        response += dsh_utils.black_break_msg_debug(
            'email addresses are: ' + repr(emailAddrs), 117)

    response += dsh_selection.email_selections(emailAddrs, attachVoice,
                                               comments, urlFields=fields)

    response += page_footer()
    return HttpResponse(response)    
def select_current_dial_set(personTable, action='set'):
    """
    10/03/22.
    called by dsh_common_views.select_current_dial_set().
    add/remove the people in the current dial set to/from
    the current selection.
    basically copied from process_selected_people_current_dial().
    """
    
    response = ''

    people = personTable.objects.filter(current_dial=True)

    count = 0
    for person in people:
        if action == 'set':
            if person.u17:
                continue
            person.u17 = True
        elif action == 'clear':
            if not person.u17:
                continue
            person.u17 = False
        else:
            break

        try:
            person.save(noLogging=True)
            count += 1
        except:
            message = 'dsh_common_selection.' +\
                      'select_current_dial_set: ' +\
                      'failed to save person: ' + person.dsh_uid
            dsh_django_utils.error_event(message, item=person,
                                         errorLevel='CRT')
            response += dsh_utils.red_error_break_msg(message)
            return response

    if action == 'set':
        message = 'People added to the current selection: '
    elif action == 'clear':
        message = 'People removed from the current selection: '
    else:
        message = ''

    if message:
        message += str(count) + '.'

    response += dsh_utils.black_break_msg(message)
    dsh_agi.report_event(message)

    return response
Esempio n. 12
0
def schedule_one_callee(request, personDshUid):
    """triggerred by clicking the little clock icon on the Person page.
    for scheduling auto-dialed call for one person."""
    
    if dsh_django_request.deny_it(request):
        return please_log_in()
    
    response = page_header('schedule auto-dialed call for one callee')
    response += '\n'

    disabled = dsh_db_config.get('auto_dial_disable')
    if disabled:
        response += dsh_utils.black_break_msg(
            'auto-dial is currently <font color=red><b>disabled</b></font>.')
        #response += page_footer()
        #return HttpResponse(response)
        #
        # 10/03/18:
        # I'm going to schedule a call anyways.
        # for sending out doctor replies even though global auto-dial
        # has been turned off.
        #
        response += dsh_utils.black_break_msg(
            "but we are scheduling a call anyhow.")
    
    persons = dv2.db.models.Person.objects.filter(dsh_uid=personDshUid)
    if not persons or len(persons) > 1:
        message = 'views.schedule_one_callee: bad DshUid: ' + personDshUid
        response += dsh_utils.red_error_break_msg(message)
        dsh_django_utils.error_event(message, errorLevel='CRT')
        response += page_footer()
        return HttpResponse(response)

    person = persons[0]
    
    scheduled,respStr = dsh_django_utils.check_auto_timed_calls_for_person(
        person)
    response += dsh_utils.black_break_msg(respStr)
    if scheduled:
        response += dsh_utils.black_break_msg('scheduled.')
    else:
        response += dsh_utils.black_break_msg('not scheduled.')
    
    response += dsh_utils.black_break_msg('done.')
    response += dsh_utils.black_break_msg(
        'see the <a href=/scheduled>schedule</a>.')

    response += page_footer()
    return HttpResponse(response)
def make_dot_call_file(callee, sessionID=''):
    """
    10/04/10:
    called by dsh_common_db.attempt_demo_reply_now() and
    dsh_django2.dial_now().
    """

    now = datetime.datetime.now()
    wait = dsh_common_config.lookup2('DEMO_REPLY_DELAY')
    delta = datetime.timedelta(seconds=wait)
    callTime = now + delta
    success = dsh_django_utils.generate_dot_call_file(
        callee, callTime, None, dialNow=True, sessionID=sessionID)

    if success:
        response = dsh_utils.black_break_msg(
            'Calling %s @ %s...' % (callee.__unicode__(),
                                    callee.phone_number))
    else:
        response = dsh_utils.red_error_break_msg('Something wrong happened.')

    return (success, response)
Esempio n. 14
0
def lookup_phone_number(request, personDshUid):
    if dsh_django_request.deny_it(request):
        return please_log_in()
    
    response = page_header('lookup a phone number')
    response += '\n'
    
    persons = dv2.db.models.Person.objects.filter(dsh_uid=personDshUid)
    if not persons or len(persons) > 1:
        message = 'views.lookup_phone_number: bad DshUid: ' + personDshUid
        response += dsh_utils.red_error_break_msg(message)
        dsh_django_utils.error_event(message, errorLevel='CRT')
        response += page_footer()
        return HttpResponse(response)

    person = persons[0]

    phoneNumber = person.phone_number
    message = '<BR><B><FONT SIZE=3>Phone number: %s</FONT></B>' % \
              (phoneNumber,)
    response += dsh_utils.black_break_msg(message)
    response += '<BR>'
    response += dsh_utils.black_break_msg('People who share this number are:')
    response += '<BR>'

    response += """
<table cellpadding=0 cellspacing=0 border=0 height=600 width=1000>
<tr height="1%%">
<td style="top:0;width:100%%">
<iframe scrolling=auto id=rf
src="http:/admin/db/person/?phone_number=%s"
frameborder=0 allowtransparency=true style="width:100%%;height:100%%">
</iframe>
</td></tr></table>
""" % (phoneNumber,)

    response += page_footer()
    return HttpResponse(response)
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)
Esempio n. 16
0
def red5_frame_page(request, dict):
    """frames the record and play pages from red5.
    called by red5_record() and red5_play().
    the input dict contains keys for:
    'title', 'url', 'width', 'height'.
    """
    
    #if dsh_django_request.deny_it(request):
    #    return please_log_in()

    response = page_header(dict['title'])
    response += '\n'

    hostPort = dsh_django_utils.get_host_port(request)
    if hostPort == None:
        message = 'unable to determine host name.'
        dsh_django_utils.error_event(message, errorLevel='CRT')
        response += dsh_utils.red_error_break_msg(message)
        response += page_footer()
        return HttpResponse(response)    

    dict['hostname'] = hostPort[0]
    
    response += """
<table cellpadding=0 cellspacing=0 height=%(height)s width=%(width)s border=0>
<tr height="1%%">
<td style="top:0;width:100%%">
<iframe scrolling=auto id=rf
src="http://%(hostname)s:5080/%(url)s"
frameborder=0 allowtransparency=true style="width:100%%;height:100%%">
</iframe>
</td></tr></table>
""" % dict

    response += page_footer()
    return HttpResponse(response)
def keyword_add_del(dshUid, action='add'):
    """called by views.keyword_add() and views.keyword_del()."""
    
    errorMsg = ''
    keyWord = dsh_dump.get_foreign_key(dv2.db.models.KeyWord, dshUid)
    if not keyWord:
        message = 'dsh_selection.keyword_add_del: bad key word dshUid: ' +\
                  repr(dshUid)
        dsh_django_utils.error_event(message, errorLevel='ERR')
        errorMsg += dsh_utils.red_error_break_msg(message)
        return errorMsg

    selectedItems = dv2.db.models.Item.objects.filter(u17=True)
    if not selectedItems:
        errorMsg += dsh_utils.red_error_break_msg(
            'no item selected currently.')
        return errorMsg

    count = 0
    for item in selectedItems:
        kwList = item.key_words.all()
        if action == 'add':
            if keyWord in kwList:
                continue
            try:
                item.key_words.add(keyWord)
                item.save(noLogging=True)
                count += 1
            except:
                message = 'dsh_selection.key_word_add_del: key word add ' +\
                          'failed: ' + repr(dshUid)
                dsh_django_utils.error_event(message, errorLevel='CRT')
                errorMsg += dsh_utils.red_error_break_msg(message)
                return errorMsg
        elif action == 'del':
            if not (keyWord in kwList):
                continue
            try:
                item.key_words.remove(keyWord)
                item.save(noLogging=True)
                count += 1
            except:
                message = 'dsh_selection.key_word_add_del: key word del ' +\
                          'failed: ' + repr(dshUid)
                dsh_django_utils.error_event(message, errorLevel='CRT')
                errorMsg += dsh_utils.red_error_break_msg(message)
                return errorMsg
        else:
            return dsh_utils.red_error_break_msg('bad action: ' + action)

    if action == 'add':
        actDone = 'added to'
        logAction = 'KADD'
    elif action == 'del':
        actDone = 'removed from'
        logAction = 'KDEL'
    else:
        return dsh_utils.red_error_break_msg('bad action: ' + action)

    keyStr = keyWord.key_word
    message = 'key word "%s" %s %s items.' % (keyStr, actDone, str(count))
    errorMsg += dsh_utils.black_break_msg(message)

    dsh_agi.report_event(
        message,
        action=logAction,
        item=keyWord)
    
    return errorMsg
Esempio n. 18
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 + \
                    '&nbsp;&nbsp;&nbsp;&#171;&nbsp;&nbsp;&nbsp;' + \
                    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)
def select_keyed_persons(personTable, keyWordTable, dshUid, action='set'):
    """
    10/03/22:
    modeled after keyword_select(). could've combined them but I'm lazy.
    called by dsh_common_views.select_keyed_persons().
    add the keyworded persons to the current selection.
    returns (success, response)
    """

    response = ''

    keyword = dsh_django_utils.get_foreign_key(keyWordTable, dshUid)
    if not keyword:
        message = 'dsh_common_selection.select_keyed_persons: ' +\
                  'no such dsh_uid: ' + dshUid
        response += dsh_utils.red_error_break_msg(message)
        dsh_django_utils.error_event(message, errorLevel='ERR')
        return (False, response)

    response += dsh_utils.black_break_msg(
        'The key word is: "' + keyword.key_word + '".')

    persons = personTable.objects.filter(
        person_key_words__dsh_uid__exact=dshUid)
    if not persons:
        message = 'dsh_common_selection.select_keyed_persons: ' +\
                  'no person with this key word.'
        response += dsh_utils.red_error_break_msg(message)
        return (False, response)

    response += dsh_utils.black_break_msg(
        'Number of persons with this key word: ' + str(len(persons)) + '.')

    #
    # the stuff below is copied from dsh_selection.keyword_select_starred().
    #
    count = 0
    for person in persons:

        if action == 'clear':
            if not person.u17:
                continue
            person.u17 = False
        else:
            if person.u17:
                continue
            person.u17 = True

        try:
            person.save(noLogging=True)
            count += 1
        except:
            message = 'dsh_common_selection.select_keyed_persons: ' +\
                      'failed to save: '+ item.dsh_uid
            dsh_django_utils.error_event(message, errorLevel='CRT')
            response += dsh_utils.red_error_break_msg(message)
            return (False, response)

    if action == 'clear':
        message = 'Items removed from the selection: '
    else:
        message = 'Items added to the selection: '
    message += str(count) + '.'
    response += dsh_utils.black_break_msg(message)
    dsh_agi.report_event(message)
    
    return (True, response)
Esempio n. 20
0
def stats_calculate(sortBy=None, logAction='STT2', textLog=False):
    """called by views.stats().
    possible values of sortedBy are:
    'recorded'
    'items'
    'callsnorec'
    'calls'
    'starred'
    'recdur'
    'calldur'
    returns (success,response,totals)
    when triggered from daily cron job in dsh_stats_log,
    logAction=='STT1' and textLog=True.
    otherwise, the default value here.
    """

    #
    # fill the tuple list of people and their counts.
    #
    people = dvoice.db.models.Person.objects.all()
    tupleList = []
    for person in people:
        tuple = person_tuple_list(person)
        tupleList.append(tuple)
        

    #
    # what key do we sort it by? and sort it!
    #
    if not sortBy:
        sortBy = dsh_config.lookup('STATS_SORT_BY')

    sortKey = sort_key(sortBy)
    if not sortKey:
        resp = dsh_utils.red_error_break_msg('invalid sort field: ' +
                                             repr(sortBy))
        return (False, resp, None)
        
    sortedTupleList = sorted(tupleList, key=sortKey, reverse=True)


    #
    # just prints a message at the beginning of the page.
    #
    sortStr = sortBy
    if sortBy == 'callsnorec':
        sortStr = 'calls without recording'
    elif sortBy == 'recdur':
        sortStr = 'record duration'
    elif sortBy == 'calldur':
        sortStr = 'call duration'

    response = ''
    response += dsh_utils.black_break_msg(
        'click the column headings to sort by different criteria.')
    response += dsh_utils.black_break_msg(
        'currently sorted by <b><i>%s</i></b>:' % (sortStr,))
    response += '<BR>'


    #
    # table header.
    #
    i = 1
    response += '<TABLE border=1>\n'
    response += table_header()

    #
    # to be replaced.
    #
    response += '<!-- total row -->'

    #
    # the body of the table.
    #
    totals = (0, 0, 0, 0, 0, 0, 0)
    for tuple in sortedTupleList:
        oneRow,totals = one_row(tuple, i, totals)
        response += oneRow
        i += 1

    totalRow = total_row(totals)
    response += totalRow
    response += table_header()
    
    response += '</TABLE>'

    response = response.replace('<!-- total row -->', totalRow)

    log_event(totals, logAction=logAction, textLog=textLog)
    return (True, response, totals)
def demographics(request, dshUid, personTable):
    """
    10/03/13:
    called by views.demographics().
    """

    if dsh_django_request.deny_it(request):
        return views.please_log_in()

    response = views.page_header('demographics', includeMp3Player=True)
    person = dsh_django_utils.get_foreign_key(personTable, dshUid)

    if not person:
        message = 'dsh_common_views.demographics: no person found: ' + dshUid
        response += dsh_utils.red_error_break_msg(message)
        dsh_django_utils.error_event(message, errorLevel='ERR')
        response += page_footer()
        return HttpResponse(response)

    personEditUrl = dsh_django_config.lookup('PERSON_DETAIL_URL') + \
                    str(person.id)
    thumb = dsh_django_utils.thumbnail(
        person, person.mugshot, noCenter=True)
    url = '<a href=%s title="edit person details">%s</a>' % \
          (personEditUrl, thumb)

    response += url

    response += '<BR><BR>'
    response += '<TABLE BORDER=1>'

    name = person.__unicode__()
    if name:
        response += '<TR><TD>name</TD><TD>%s</TD></TR>' % (name,)

    if person.spoken_name:
        spokenName = person.spoken_name_display_field()
        if spokenName:
            response += '<TR><TD>spoken name</TD><TD>%s</TD></TR>' % \
                        (spokenName)

    response += '<TR><TD>dsh uid</TD><TD>%s</TD></TR>' % (person.dsh_uid,)

    if person.phone_number:
        response += '<TR><TD>phone</TD><TD>%s</TD></TR>' % \
                    (person.phone_number,)

    if person.organization and person.organization.alias:
        response += '<TR><TD>org.</TD><TD>%s</TD></TR>' % \
                    (person.organization.alias,)

    if person.ptype:
        response += '<TR><TD>type</TD><TD>%s</TD></TR>' % (person.ptype,)

    if person.gender:
        response += '<TR><TD>gender</TD><TD>%s</TD></TR>' % (person.gender,)
        
    if person.date_birth:
        if person.birth_date_approximate:
            dateStr = str(person.date_birth.year)
        else:
            dateStr = person.date_birth.isoformat()
        response += '<TR><TD>birth date</TD><TD>%s</TD></TR>' % (dateStr,)

    if person.birth_date_approximate:
        response += '<TR><TD>birth date approximate</TD><TD>True</TD></TR>'

    if person.date_birth:
        years = dsh_common_db.calculate_age(person)
        if years:
            response += '<TR><TD>age</TD><TD>%s</TD></TR>' % (str(years),)

    if person.modify_datetime:
        timeStr = person.modify_datetime.strftime(
            '%#Y-%#m-%#d %#H:%#M:%#S')
        response += '<TR><TD>modify time</TD><TD>%s</TD></TR>' % (timeStr,)
    
    response += '</TABLE>'
    
    response += views.mp3_widget_control()
    response += views.page_footer()
    return HttpResponse(response)
def add_person_key_word(personTable, keyWordTable, dshUid, action='set'):
    """
    10/03/22:
    copied from dsh_selection.keyword_add_del()
    called by dsh_common_view.add_person_keyword()"""
    
    errorMsg = ''
    keyWord = dsh_django_utils.get_foreign_key(keyWordTable, dshUid)
    if not keyWord:
        message = 'dsh_common_selection.add_person_key_word: ' +\
                  'bad key word dshUid: ' + repr(dshUid)
        dsh_django_utils.error_event(message, errorLevel='ERR')
        errorMsg += dsh_utils.red_error_break_msg(message)
        return errorMsg

    selectedPersons = personTable.objects.filter(u17=True)
    if not selectedPersons:
        errorMsg += dsh_utils.red_error_break_msg(
            'no person selected currently.')
        return errorMsg

    count = 0
    for person in selectedPersons:
        kwList = person.person_key_words.all()
        if action == 'set':
            if keyWord in kwList:
                continue
            try:
                person.person_key_words.add(keyWord)
                person.save(noLogging=True)
                count += 1
            except:
                message = 'dsh_common_selection.add_person_key_word: ' +\
                          'key word add ' +\
                          'failed: ' + repr(dshUid)
                dsh_django_utils.error_event(message, errorLevel='CRT')
                errorMsg += dsh_utils.red_error_break_msg(message)
                return errorMsg
        elif action == 'clear':
            if not (keyWord in kwList):
                continue
            try:
                person.person_key_words.remove(keyWord)
                person.save(noLogging=True)
                count += 1
            except:
                message = 'dsh_common_selection.add_person_key_word: ' +\
                          'key word del ' +\
                          'failed: ' + repr(dshUid)
                dsh_django_utils.error_event(message, errorLevel='CRT')
                errorMsg += dsh_utils.red_error_break_msg(message)
                return errorMsg
        else:
            return dsh_utils.red_error_break_msg('bad action: ' + action)

    if action == 'set':
        actDone = 'added to'
        logAction = 'KADD'
    elif action == 'clear':
        actDone = 'removed from'
        logAction = 'KDEL'
    else:
        return dsh_utils.red_error_break_msg('bad action: ' + action)

    keyStr = keyWord.key_word
    message = 'key word "%s" %s %s persons.' % (keyStr, actDone, str(count))
    errorMsg += dsh_utils.black_break_msg(message)

    dsh_agi.report_event(
        message,
        action=logAction,
        item=keyWord)
    
    return errorMsg
def process_selection(selectedItems, fieldStr, action='set'):
    """
    called by dsh_selection.process_selection().
    initially modeled after dsh_selection.star().
    selectedItems is a list of selected items.
    passed in as arguments because we are selecting different types of
    objects.
    filedStr is something like "starred" or "active" or "peer_shared".
    they are fields defined in db/models.py.
    action is either "set" or "clear".
    returns the html response string to be displayed.
    """
    
    response = ''
    
    if not selectedItems:
        response += dsh_utils.red_error_break_msg(
            'no item selected currently.')
        return response

    count = 0
    changedIds = []
    for item in selectedItems:

        try:
            valCurr = getattr(item, fieldStr)
        except:
            message = 'dsh_common_selection.process_selection(): ' + \
                      'getattr() failed: ' + item.dsh_uid + ', fieldStr: ' +\
                      fieldStr
            dsh_django_utils.error_event(message, errorLevel='CRT')
            response += dsh_utils.red_error_break_msg(message)
            return response

        valChange = False
        if action == 'set':
            if valCurr:
                continue
            valNew = True
            valChange = True
        else:
            #
            # it's 'clear'.
            #
            if not valCurr:
                continue
            valNew = False
            valChange = True

        if not valChange:
            #
            # not really necessary...
            #
            continue
        try:
            setattr(item, fieldStr, valNew)
            item.save(noLogging=True)
            count += 1
            changedIds.append(item.dsh_uid)
        except:
            message = 'dsh_common_selection.process_selection: ' +\
                      'failed to save: ' +\
                      item.dsh_uid + ', fieldStr: ' + fieldStr
            dsh_django_utils.error_event(message, errorLevel='CRT')
            response += dsh_utils.red_error_break_msg(message)
            return response

    if action == 'set':
        actDone = 'set'
    else:
        actDone = 'cleared'
        

    message = '%s item(s) %s. ' % (str(count), actDone)
    messageLog = 'dsh_common_selection.process_selection(): ' + message
    messageLog += 'fieldStr: ' + fieldStr + '. '
    if count:
        messageLog += 'items: ' + repr(changedIds)
    response += dsh_utils.black_break_msg(message)
    dsh_agi.report_event(messageLog)

    return response
def email_selections(emailAddrs, attach, comments='', urlFields=None):
    """called by views.email_selection()."""

    returnMsg = ''


    #
    # display the email addresses.
    #
    returnMsg = dsh_utils.black_break_msg('<i><u>email(s) sent to:</u></i>\n')
    for email in emailAddrs:
        returnMsg += dsh_utils.black_break_msg(email)
    returnMsg += '<BR>\n'


    #
    # deal with comments: display them, include them.
    #
    emailText = ''
    if comments:
        returnMsg += '<i><u>comments:</u></i><br>\n'
        returnMsg += comments
        returnMsg += '<br><br>'
        emailText = '[comments:]\n\n%s\n' % (comments,)
        emailText += '\n---------------\n\n'


    #
    # now loop through all the selected items.
    #
    returnMsg += dsh_utils.black_break_msg('<i><u>items sent:</u></i><br>\n')
    
    selectedItems = dv2.db.models.Item.objects.filter(u17=True)
    if not selectedItems:
        returnMsg += dsh_utils.red_error_break_msg(
            'no item selected currently.')
        return returnMsg

    #
    # 09/11/14:
    # reverse it so it's in reverse chronological order.
    # for some reason, this didn't work...
    #
    #selectedItems.reverse()
    

    count = 0
    displayText = '<TABLE border=1>\n'
    fileList = []
    attachedFileList = []
    

    #
    # 09/11/14:
    # reverse it so it's in reverse chronological order.
    #
    for item in selectedItems[::-1]:

        emailText += smart_unicode(item.email_text(attach=attach,
                                                   urlFields=urlFields))
        emailText += '\n---------------\n\n'

        
        displayText += '<TR><TD>%s</TD></TR>\n' % \
                       (item.email_text(br=True, attach=attach,
                                        urlFields=urlFields,
                                        allowTags=True),)

        if attach:
            file = item.full_file_path()
            attachedFile = item.attachment_file_name()
        
            if file and attachedFile:
                fileList.append(file)
                attachedFileList.append(attachedFile)
            
    displayText += '</TABLE>\n'
    returnMsg += smart_unicode(displayText)
    
    returnMsg += dsh_utils.black_break_msg_debug('', 118)
    returnMsg += dsh_utils.black_break_msg_debug(repr(fileList), 118)
    returnMsg += dsh_utils.black_break_msg_debug('', 118)
    returnMsg += dsh_utils.black_break_msg_debug(repr(attachedFileList), 118)

    emailText = smart_unicode(emailText)
    emailText = smart_str(emailText)


    #
    # got everything.  ready to actually call gmail_send().
    #
    try:
        success,errorMsg = dsh_utils.gmail_send(
            dsh_config.lookup('GMAIL_SENDER_ADDRESS'),
            dsh_config.lookup('GMAIL_SENDER_PASSWORD'),
            emailAddrs,
            dsh_config.lookup('GMAIL_SENDER_SUBJECT'),
            emailText,
            attachedFiles=fileList,
            attachmentNames=attachedFileList)
        if success:
            message = 'selection emailed to: %s.  comments: %s.' %\
                      (', '.join(emailAddrs), comments)
            dsh_agi.report_event(message, action='EMAI')
            returnMsg += '<br>' + dsh_utils.black_break_msg('Message sent.')
        else:
            dsh_django_utils.error_event(errorMsg, errorLevel='ERR')
            returnMsg += '<br>' + dsh_utils.red_error_break_msg(errorMsg)
    except:
        message = 'dsh_selection.email_selections: gmail_send() failed. ' +\
                  'Unexpected error.  Tell Randy about this page.'
        dsh_django_utils.error_event(message, errorLevel='ERR')
        returnMsg += '<br>' + dsh_utils.red_error_break_msg(message)
        
    return returnMsg
def keyword_select(dshUid, keyWordTable, itemTable, action='select'):
    """
    10/03/14:
    called by dsh_common_views.keyword_select().
    add the keyworded items to the current selection.
    returns (success, response)
    """

    response = ''

    keyword = dsh_django_utils.get_foreign_key(keyWordTable, dshUid)
    if not keyword:
        message = 'dsh_common_selection.keyword_select: no such dsh_uid: ' +\
                  dshUid
        response += dsh_utils.red_error_break_msg(message)
        dsh_django_utils.error_event(message, errorLevel='ERR')
        return (False, response)

    response += dsh_utils.black_break_msg(
        'The key word is: "' + keyword.key_word + '".')

    items = itemTable.objects.filter(key_words__dsh_uid__exact=dshUid)
    if not items:
        message = 'dsh_common_selection.keyword_select: ' +\
                  'no messages with this key word.'
        response += dsh_utils.red_error_break_msg(message)
        return (False, response)

    response += dsh_utils.black_break_msg(
        'Number of messages with this key word: ' + str(len(items)) + '.')

    #
    # the stuff below is copied from dsh_selection.keyword_select_starred().
    #
    count = 0
    for item in items:

        if action == 'deselect':
            if not item.u17:
                continue
            item.u17 = False
        else:
            if item.u17:
                continue
            item.u17 = True

        try:
            item.save(noLogging=True)
            count += 1
        except:
            message = 'dsh_common_selection.keyword_select: failed to save: '+\
                      item.dsh_uid
            dsh_django_utils.error_event(message, errorLevel='CRT')
            response += dsh_utils.red_error_break_msg(message)
            return (False, response)

    if action == 'deselect':
        message = 'Items removed from the selection: '
    else:
        message = 'Items added to the selection: '
    message += str(count) + '.'
    response += dsh_utils.black_break_msg(message)
    dsh_agi.report_event(message)
    
    return (True, response)