def handle(request):
    rec, redirect = codejar.actions.handleSecurity(request, 'recruiter')
    if not rec: return redirect
    
    email_list = dataplus.dictGetSafeVal(request.REQUEST, 'email_list', '')
    email_query = dataplus.dictGetSafeVal(request.REQUEST, 'email_query', '')
    if email_query:
        search_keywords, experience, location, max_salary = cPickle.loads(base64.b64decode(email_query))
        response = search_helper.matchResumes(search_keywords, experience, location, max_salary, datetime.datetime(1981, 1, 9))
        email_list = dataplus.decode(string.join([usr['email'] for usr in response.results], '; '))
    
    action = dataplus.dictGetSafeVal(request.REQUEST, 'action', '')
    if action == 'show_form':
        return codejar.actions.render(request, 'recruiters/emailusers.htm',
                               {'to_list':email_list,
                                'recruiter': rec})
    
    elif action == 'email_users':
        subject = dataplus.dictGetSafeVal(request.REQUEST, 'subject', '')
        message = dataplus.dictGetSafeVal(request.REQUEST, 'message', '')
        
        message += '<p>&nbsp;</p><div style="border-bottom: 1px solid rgb(153, 153, 153);"></div><p>This email has been sent by %s(%s) of %s using <a href="http://www.jobhunt.in">www.jobhunt.in</a> services.</p>' % (rec.name, rec.email, rec.organization)
        mailman.sendMail(rec.name + '<*****@*****.**>', email_list.split(';'), subject, message, reply_to=rec.email)
        
        eventnotifier.sendEventNotification("New Recruiter Mass Mail: " + subject + " - " + rec.name + "(" + rec.email + ")" + " message:\n" + message)
        
        return HttpResponseRedirect('dashboard.htm?flashId=email_sent')
Beispiel #2
0
def handle(request):
    rec, redirect = codejar.actions.handleSecurity(request, 'recruiter')
    if not rec: return redirect

    email_list = dataplus.dictGetSafeVal(request.REQUEST, 'email_list', '')
    email_query = dataplus.dictGetSafeVal(request.REQUEST, 'email_query', '')
    if email_query:
        search_keywords, experience, location, max_salary = cPickle.loads(
            base64.b64decode(email_query))
        response = search_helper.matchResumes(search_keywords, experience,
                                              location, max_salary,
                                              datetime.datetime(1981, 1, 9))
        email_list = dataplus.decode(
            string.join([usr['email'] for usr in response.results], '; '))

    action = dataplus.dictGetSafeVal(request.REQUEST, 'action', '')
    if action == 'show_form':
        return codejar.actions.render(request, 'recruiters/emailusers.htm', {
            'to_list': email_list,
            'recruiter': rec
        })

    elif action == 'email_users':
        subject = dataplus.dictGetSafeVal(request.REQUEST, 'subject', '')
        message = dataplus.dictGetSafeVal(request.REQUEST, 'message', '')

        message += '<p>&nbsp;</p><div style="border-bottom: 1px solid rgb(153, 153, 153);"></div><p>This email has been sent by %s(%s) of %s using <a href="http://www.jobhunt.in">www.jobhunt.in</a> services.</p>' % (
            rec.name, rec.email, rec.organization)
        mailman.sendMail(rec.name + '<*****@*****.**>',
                         email_list.split(';'),
                         subject,
                         message,
                         reply_to=rec.email)

        eventnotifier.sendEventNotification("New Recruiter Mass Mail: " +
                                            subject + " - " + rec.name + "(" +
                                            rec.email + ")" + " message:\n" +
                                            message)

        return HttpResponseRedirect('dashboard.htm?flashId=email_sent')
Beispiel #3
0
def saveEmailedResumes():
    global error_count
    pop = poplib.POP3(pop_server)
    pop.user(pop_user)
    pop.pass_(pop_pass)
    stats = pop.stat()
    rx_headers = re.compile('^(From|To|Subject|Content-Type):', re.IGNORECASE)

    if stats and stats[0] > 0:
        connection = psycopg2.connect(
            "dbname='jhindb' user='******' password='******' host='127.0.0.1'"
        )
        cursor = connection.cursor()

        time_now = datetime.datetime.utcnow()
        count = stats[0]
        for i in range(1, 1 + count):
            try:
                resp, lines, bytes = pop.top(i, 10)
                req_lines = filter(rx_headers.match, lines)
                headers = map(lambda x: x.split(': ', 1), req_lines)

                def find_in_headers(hdr_name):
                    res = filter(lambda x: x[0].lower() == hdr_name.lower(),
                                 headers)
                    if len(res) > 0: return res[0][1]
                    else: return ''

                doc_filename = None
                doc_filepath = None
                has_doc = False
                if find_in_headers('Content-Type').lower().startswith(
                        'multipart'):

                    msg = email.message_from_string('\n'.join(pop.retr(i)[1]))
                    body = {'html': '', 'plain': ''}
                    for part in msg.walk():
                        if part.get_content_maintype() == 'text':
                            sub_type = part.get_content_subtype()
                            if sub_type in ['plain', 'html']:
                                data = dataplus.decode(
                                    part.get_payload(decode=True))
                                if len(data) < 25: pass
                                body[sub_type] = data

                        if part.get_content_maintype(
                        ) == 'application' and part.get_content_subtype(
                        ) == 'msword':
                            doc_filepath = saveResumeFile(
                                part.get_payload(decode=True))
                            doc_filename = part.get_filename()
                            has_doc = True

                    if doc_filename:
                        stmt = "INSERT INTO website_receivedmail (from_address, subject, body_html, body_text, doc_filepath, received_on)"
                        stmt += " VALUES (%(from_address)s, %(subject)s, %(html_body)s, %(plain_body)s, %(doc_filepath)s, %(time_now)s)"
                        cursor.execute(
                            stmt, {
                                'from_address': find_in_headers('From')[:100],
                                'subject': find_in_headers('Subject')[:100],
                                'html_body': body['html'],
                                'plain_body': body['plain'],
                                'doc_filepath': doc_filepath,
                                'time_now': str(time_now)
                            })
                        cursor.execute(
                            "SELECT CURRVAL('website_receivedmail_id_seq');")
                        mail_id = str(cursor.fetchone()[0])
                        resume_key = dataplus.getUniqueId()

                        stmt = 'INSERT INTO website_resume (doc_filename, doc_filepath, html_filepath, text_filepath, doc_hash, posted_on, mail_ref_id, "name", email, experience, tags, industry, "location", current_employer, summary, "key", tagged, is_active, min_salary, desired_employer) '
                        stmt += "VALUES (%(doc_filename)s ,%(doc_filepath)s, '', '', '', %(time_now)s, %(mail_id)s, '', '', 0, '', '', '', '', '', %(resume_key)s, False, False, 0, '')"
                        cursor.execute(
                            stmt, {
                                'doc_filename': doc_filename,
                                'doc_filepath': doc_filepath,
                                'time_now': str(time_now),
                                'mail_id': mail_id,
                                'resume_key': resume_key
                            })

                from_hdr = find_in_headers('From')
                candidate_name = getNameFromHeader(from_hdr)
                if has_doc:
                    params = {'name': candidate_name, 'resume_key': resume_key}
                    mailer.sendResumeReceivedMail(from_hdr, params)
                    eventnotifier.sendEventNotification(
                        'New Resume by mail: %s posted on: %s' %
                        (doc_filename,
                         time_now.strftime('%d/%m/%Y %H:%M:%S %p')))
                else:
                    params = {'name': candidate_name}
                    mailer.sendInvalidResumeMail(from_hdr, params)

                pop.dele(i)

            except:
                error_count += 1
                setErrorCount(error_count)
                logError('Processing mail ' + find_in_headers('From') + ' - ' +
                         find_in_headers('Subject') + ' failed : ' +
                         str(sys.exc_info()[0]) + ', ' +
                         str(sys.exc_info()[1]))
                if error_count == max_errors:
                    logError(
                        'Jobhunt Job Error: Stopping mail_pickup_job as it has encountered Maximum number of errors.'
                    )
                    break

        connection.commit()
    pop.quit()
Beispiel #4
0
def saveEmailedResumes():
    global error_count
    pop = poplib.POP3(pop_server)
    pop.user(pop_user)
    pop.pass_(pop_pass)
    stats = pop.stat()
    rx_headers = re.compile('^(From|To|Subject|Content-Type):',re.IGNORECASE)
    
    if stats and stats[0] > 0:  
        connection = psycopg2.connect("dbname='jhindb' user='******' password='******' host='127.0.0.1'")
        cursor = connection.cursor()
        
        time_now = datetime.datetime.utcnow()
        count = stats[0]
        for i in range(1,1+count):
            try:
                resp, lines, bytes = pop.top(i,10)
                req_lines = filter(rx_headers.match, lines)
                headers = map(lambda x: x.split(': ', 1), req_lines)
                
                def find_in_headers(hdr_name):
                    res = filter(lambda x: x[0].lower() == hdr_name.lower(), headers)
                    if len(res) > 0:    return res[0][1]
                    else:   return ''
                
                doc_filename = None
                doc_filepath = None
                has_doc = False
                if find_in_headers('Content-Type').lower().startswith('multipart'):
                
                    msg = email.message_from_string('\n'.join(pop.retr(i)[1]))
                    body = {'html':'', 'plain':''}
                    for part in msg.walk():
                        if part.get_content_maintype() == 'text':
                            sub_type = part.get_content_subtype()
                            if sub_type in ['plain','html']:
                                data = dataplus.decode(part.get_payload(decode=True))
                                if len(data) < 25:  pass
                                body[sub_type] = data
                        
                        if part.get_content_maintype() == 'application' and part.get_content_subtype() == 'msword':
                            doc_filepath = saveResumeFile(part.get_payload(decode=True))
                            doc_filename = part.get_filename()
                            has_doc = True
                    
                    if doc_filename:
                        stmt = "INSERT INTO website_receivedmail (from_address, subject, body_html, body_text, doc_filepath, received_on)"
                        stmt += " VALUES (%(from_address)s, %(subject)s, %(html_body)s, %(plain_body)s, %(doc_filepath)s, %(time_now)s)"
                        cursor.execute(stmt, {'from_address':find_in_headers('From')[:100], 'subject':find_in_headers('Subject')[:100],
                                            'html_body':body['html'], 'plain_body':body['plain'],
                                            'doc_filepath':doc_filepath, 'time_now':str(time_now)})
                        cursor.execute("SELECT CURRVAL('website_receivedmail_id_seq');")
                        mail_id = str(cursor.fetchone()[0])
                        resume_key = dataplus.getUniqueId()
                        
                        stmt = 'INSERT INTO website_resume (doc_filename, doc_filepath, html_filepath, text_filepath, doc_hash, posted_on, mail_ref_id, "name", email, experience, tags, industry, "location", current_employer, summary, "key", tagged, is_active, min_salary, desired_employer) '
                        stmt += "VALUES (%(doc_filename)s ,%(doc_filepath)s, '', '', '', %(time_now)s, %(mail_id)s, '', '', 0, '', '', '', '', '', %(resume_key)s, False, False, 0, '')"
                        cursor.execute(stmt, {'doc_filename':doc_filename, 'doc_filepath':doc_filepath, 'time_now':str(time_now), 'mail_id':mail_id, 'resume_key':resume_key})
                    
                from_hdr = find_in_headers('From')
                candidate_name = getNameFromHeader(from_hdr)
                if has_doc:
                    params = {'name':candidate_name, 'resume_key': resume_key}
                    mailer.sendResumeReceivedMail(from_hdr, params)
                    eventnotifier.sendEventNotification('New Resume by mail: %s posted on: %s' % (doc_filename, time_now.strftime('%d/%m/%Y %H:%M:%S %p')))
                else:
                    params = {'name': candidate_name}
                    mailer.sendInvalidResumeMail(from_hdr, params)
                
                pop.dele(i)
                    
            except:
                error_count += 1
                setErrorCount(error_count)
                logError('Processing mail ' + find_in_headers('From') + ' - ' + find_in_headers('Subject') + ' failed : ' + str(sys.exc_info()[0]) + ', ' + str(sys.exc_info()[1]))
                if error_count == max_errors:
                    logError('Jobhunt Job Error: Stopping mail_pickup_job as it has encountered Maximum number of errors.')
                    break
                
        connection.commit()
    pop.quit()
Beispiel #5
0
def feedResumes(limit_time):
    s = SearchClient()

    #deleted users have to be moved from index
    stmt = "SELECT user_id FROM website_indexdelta WHERE index_type = 'D' AND marked_at < %(limit_time)s;"
    cursor.execute(stmt, {'limit_time': limit_time})
    results = cursor.fetchall()
    deletions = []
    for row in results:
        print 'deleting.. ', str(row[0])
        deletions.append(IndexUpdateEntry('delete', str(row[0])))

    s.updateIndexes(deletions, CLUSTER_ID)

    #indexing the updated users
    stmt = """SELECT U.id, A.account_type, A.username, U.key, (CASE A.account_type WHEN 'FU' THEN U.email WHEN 'PU' THEN U.proxy_email END) As email,
            name, telephone, industry, experience, curr_employer, curr_designation, tags, summary, min_salary, pref_employment,
            pref_designation, pref_location, text_filepath, rating
            FROM website_user U INNER JOIN website_account A ON U.account_id = A.id
            WHERE U.id IN (SELECT user_id FROM website_indexdelta WHERE index_type = 'U' AND marked_at < %(limit_time)s)
            AND A.account_state = 'A' AND U.is_job_hunting = 'yes' ORDER BY U.id;"""
    cursor.execute(stmt, {'limit_time': limit_time})
    results = cursor.fetchall()

    update_list = []
    for (user_id, account_type, username, key, email, name, telephone, industry, experience, curr_employer, curr_designation, \
        tags, summary, min_salary, pref_employment, pref_designation, pref_location, text_filepath, rating) in results:

        if account_type == 'PU' or (account_type == 'FU' and text_filepath
                                    and os.path.exists(text_filepath)):

            meta = {}
            meta['id'] = str(user_id)
            meta['account_type'] = dataplus.decode(account_type)
            meta['username'] = dataplus.decode(username)
            meta['name'] = dataplus.decode(name)
            meta['key'] = dataplus.decode(key)
            meta['email'] = dataplus.decode(email)
            meta['telephone'] = dataplus.decode(telephone)
            meta['industry'] = dataplus.decode(industry)
            meta['experience'] = format.Int(experience)
            meta['curr_employer'] = dataplus.decode(curr_employer)
            meta['curr_designation'] = dataplus.decode(curr_designation)
            meta['tags'] = dataplus.decode(tags)
            meta['summary'] = dataplus.decode(summary)
            meta['min_salary'] = format.Int(min_salary)
            meta['pref_employment'] = dataplus.decode(pref_employment)
            meta['pref_designation'] = dataplus.decode(pref_designation)
            meta['pref_location'] = dataplus.decode(pref_location)
            meta['rating'] = format.Int(rating)
            meta['indexed_on'] = format.Date(limit_time)

            if account_type == 'FU':
                meta['fulltext'] = format.exactFormat(
                    meta['tags'] + dataplus.decode(open(text_filepath).read()))
            elif account_type == 'PU':
                meta['fulltext'] = format.exactFormat(meta['tags'] + '\n' +
                                                      meta['summary'])

            update_list.append(IndexUpdateEntry('update', str(user_id), meta))
            print user_id, dataplus.decode(meta['tags'])

    print 'finished creating meta data'
    #we are updating the Resume Store (store-name:resume)
    s.updateIndexes(update_list, CLUSTER_ID)
    print "updated indexes successfully"
Beispiel #6
0
def feedResumes(limit_time):
    s = SearchClient()
    
    #deleted users have to be moved from index
    stmt = "SELECT user_id FROM website_indexdelta WHERE index_type = 'D' AND marked_at < %(limit_time)s;"
    cursor.execute(stmt, {'limit_time':limit_time})
    results = cursor.fetchall()
    deletions = []
    for row in results:
        print 'deleting.. ', str(row[0])
        deletions.append(IndexUpdateEntry('delete', str(row[0])))
        
    s.updateIndexes(deletions, CLUSTER_ID)

    #indexing the updated users
    stmt = """SELECT U.id, A.account_type, A.username, U.key, (CASE A.account_type WHEN 'FU' THEN U.email WHEN 'PU' THEN U.proxy_email END) As email,
            name, telephone, industry, experience, curr_employer, curr_designation, tags, summary, min_salary, pref_employment,
            pref_designation, pref_location, text_filepath, rating
            FROM website_user U INNER JOIN website_account A ON U.account_id = A.id
            WHERE U.id IN (SELECT user_id FROM website_indexdelta WHERE index_type = 'U' AND marked_at < %(limit_time)s)
            AND A.account_state = 'A' AND U.is_job_hunting = 'yes' ORDER BY U.id;"""
    cursor.execute(stmt, {'limit_time':limit_time})
    results = cursor.fetchall()

    update_list = []
    for (user_id, account_type, username, key, email, name, telephone, industry, experience, curr_employer, curr_designation, \
        tags, summary, min_salary, pref_employment, pref_designation, pref_location, text_filepath, rating) in results:
        
        if account_type == 'PU' or (account_type == 'FU' and text_filepath and os.path.exists(text_filepath)):
            
            meta = {}
            meta['id'] = str(user_id)
            meta['account_type'] = dataplus.decode(account_type)
            meta['username'] = dataplus.decode(username)
            meta['name'] = dataplus.decode(name)
            meta['key'] = dataplus.decode(key)
            meta['email'] = dataplus.decode(email)
            meta['telephone'] = dataplus.decode(telephone)
            meta['industry'] = dataplus.decode(industry)
            meta['experience'] = format.Int(experience)
            meta['curr_employer'] = dataplus.decode(curr_employer)
            meta['curr_designation'] = dataplus.decode(curr_designation)
            meta['tags'] = dataplus.decode(tags)
            meta['summary'] = dataplus.decode(summary)
            meta['min_salary'] = format.Int(min_salary)
            meta['pref_employment'] = dataplus.decode(pref_employment)
            meta['pref_designation'] = dataplus.decode(pref_designation)
            meta['pref_location'] = dataplus.decode(pref_location)
            meta['rating'] = format.Int(rating)
            meta['indexed_on'] = format.Date(limit_time)

            if account_type == 'FU':
                meta['fulltext'] = format.exactFormat(meta['tags'] + dataplus.decode(open(text_filepath).read()))
            elif account_type == 'PU':
                meta['fulltext'] = format.exactFormat(meta['tags'] + '\n' + meta['summary'])
                
            update_list.append(IndexUpdateEntry('update', str(user_id), meta))
            print user_id, dataplus.decode(meta['tags'])

    print 'finished creating meta data'
    #we are updating the Resume Store (store-name:resume)
    s.updateIndexes(update_list, CLUSTER_ID)
    print "updated indexes successfully"