summaryrefslogtreecommitdiffstats
path: root/lib/mongo.py
blob: 0c4c71eb16fe611149bd7eb807766be1730e3e8b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#-*- coding: utf-8 -*-

import pymongo
import re
from bunch import Bunch
from datetime import datetime

connection = pymongo.Connection('localhost', 27017)

def _build_thread(emails):
    thread = {}
    for email in emails:
        #print email['Date'], email['From'] #, email['Message-ID']
        email = Bunch(email)
        ref = []
        if 'References' in email:
            ref.extend(email['References'].split()[-1:])
        elif 'In-Reply-To' in email:
            ref.append(email['In-Reply-To'])
        if email['Message-ID'] not in thread:
            thread[email['Message-ID']] = Bunch(
                {'email': email, 'child': []})
        else:
            thread[email['Message-ID']].email = email
        for ref in set(ref):
            if ref in thread:
                thread[ref].child.append(email['Message-ID'])
            else:
                thread[ref] = Bunch(
                {'email': None, 'child': [email['Message-ID']]})
    return thread

def _tree_to_list(tree, mailid, level, thread_list):
    start = tree[mailid]
    start.level = level
    thread_list.append(start)
    for mail in start.child:
        mail = tree[mail]
        thread_list = _tree_to_list(tree, mail.email['Message-ID'],
            level + 1, thread_list)
    return thread_list

def get_thread_list(table, threadid):
    db = connection[table]
    thread = list(db.mails.find({'ThreadID': int(threadid)},
        sort=[('Date', pymongo.ASCENDING)]))

    tree = _build_thread(thread)
    thread_list = []
    if thread:
        thread = _tree_to_list(tree, thread[0]['Message-ID'], 0, thread_list)
        return thread
    else:
        return []

def get_thread_name(table, threadid):
    db = connection[table]
    thread = list(db.mails.find({'ThreadID': int(threadid)},
        sort=[('Date', pymongo.ASCENDING)]))
    if thread:
        return thread[0]['Subject']
    else:
        return ''

def get_emails_thread(table, start_email, thread):
    db = connection[table]
    db.mails.create_index('Date')
    db.mails.ensure_index('Date')
    db.mails.create_index('In-Reply-To')
    db.mails.ensure_index('In-Reply-To')
    db.mails.create_index('Message-ID')
    db.mails.ensure_index('Message-ID')
    regex = '.*%s.*' % start_email['Message-ID']
    for el in db.mails.find({'References': re.compile(regex, re.IGNORECASE)},
        sort=[('Date', pymongo.DESCENDING)]):
        thread.append(el)
        get_emails_thread(el, thread)
    return thread


def get_archives(table, start, end):
    db = connection[table]
    db.mails.create_index('Date')
    db.mails.ensure_index('Date')
    db.mails.create_index('References')
    db.mails.ensure_index('References')
    # Beginning of thread == No 'References' header
    archives = []
    for el in db.mails.find({'References': {'$exists':False},
            "Date": {"$gte": start, "$lt": end}}, 
            sort=[('Date', pymongo.DESCENDING)]):
        archives.append(el)
    return archives


def get_thread(table, start, end):
    db = connection[table]
    db.mails.create_index('Date')
    db.mails.ensure_index('Date')
    db.mails.create_index('References')
    db.mails.ensure_index('References')
    # Beginning of thread == No 'References' header
    archives = Bunch()
    for el in db.mails.find({'References': {'$exists':False},
            "Date": {"$gte": start, "$lt": end}}, 
            sort=[('Date', pymongo.DESCENDING)]):
        thread = get_emails_thread(el, [el])
        #print el['Subject'], len(thread)
        archives[el['Subject']] = thread
    return archives


def get_thread_length(table, thread_id):
    db = connection[table]
    db.mails.create_index('ThreadID')
    db.mails.ensure_index('ThreadID')
    return db.mails.find({'ThreadID': thread_id}).count()


def get_thread_participants(table, thread_id):
    db = connection[table]
    db.mails.create_index('ThreadID')
    db.mails.ensure_index('ThreadID')
    authors = set()
    for mail in db.mails.find({'ThreadID': thread_id}):
        authors.add(mail['From'])
    return len(authors)


def get_archives_length(table):
    db = connection[table]
    db.mails.create_index('Date')
    db.mails.ensure_index('Date')
    archives = {}
    entry = db.mails.find_one(sort=[('Date', pymongo.ASCENDING)])
    date = entry['Date']
    now = datetime.now()
    year = date.year
    month = date.month
    while year < now.year:
        archives[year] = range(1,13)[(month -1):]
        year = year + 1
        month = 1
    archives[now.year] = range(1,13)[:now.month]
    return archives


def search_archives(table, query):
    db = connection[table]
    db.mails.create_index('Date')
    db.mails.ensure_index('Date')
    for el in query:
        db.mails.create_index(str(el))
        db.mails.ensure_index(str(el))
    return list(db.mails.find(query, sort=[('Date',
        pymongo.DESCENDING)]))