[BUG-FIX] lp:680704
[odoo/odoo.git] / addons / fetchmail / fetchmail.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 import time
23
24 from imaplib import IMAP4
25 from imaplib import IMAP4_SSL
26 from poplib import POP3
27 from poplib import POP3_SSL
28
29 import netsvc
30 from osv import osv, fields
31
32 logger = netsvc.Logger()
33
34
35 class email_server(osv.osv):
36
37     _name = 'email.server'
38     _description = "POP/IMAP Server"
39
40     _columns = {
41         'name':fields.char('Name', size=256, required=True, readonly=False),
42         'active':fields.boolean('Active', required=False),
43         'state':fields.selection([
44             ('draft', 'Not Confirmed'),
45             ('waiting', 'Waiting for Verification'),
46             ('done', 'Confirmed'),
47         ], 'State', select=True, readonly=True),
48         'server' : fields.char('Server', size=256, required=True, readonly=True, states={'draft':[('readonly', False)]}),
49         'port' : fields.integer('Port', required=True, readonly=True, states={'draft':[('readonly', False)]}),
50         'type':fields.selection([
51             ('pop', 'POP Server'),
52             ('imap', 'IMAP Server'),
53         ], 'Server Type', select=True, readonly=False),
54         'is_ssl':fields.boolean('SSL ?', required=False),
55         'attach':fields.boolean('Add Attachments ?', required=False, help="Fetches mail with attachments if true."),
56         'date': fields.date('Date', readonly=True, states={'draft':[('readonly', False)]}),
57         'user' : fields.char('User Name', size=256, required=True, readonly=True, states={'draft':[('readonly', False)]}),
58         'password' : fields.char('Password', size=1024, invisible=True, required=True, readonly=True, states={'draft':[('readonly', False)]}),
59         'note': fields.text('Description'),
60         'action_id':fields.many2one('ir.actions.server', 'Email Server Action', required=False, domain="[('state','=','email')]", help="An Email Server Action. It will be run whenever an e-mail is fetched from server."),
61         'object_id': fields.many2one('ir.model', "Model", required=True, help="OpenObject Model. Generates a record of this model.\nSelect Object with message_new attrbutes."),
62         'priority': fields.integer('Server Priority', readonly=True, states={'draft':[('readonly', False)]}, help="Priority between 0 to 10, select define the order of Processing"),
63         'user_id':fields.many2one('res.users', 'User', required=False),
64         'message_ids': fields.one2many('mailgate.message', 'server_id', 'Messages', readonly=True),
65     }
66     _defaults = {
67         'state': lambda *a: "draft",
68         'active': lambda *a: True,
69         'priority': lambda *a: 5,
70         'date': lambda *a: time.strftime('%Y-%m-%d'),
71         'user_id': lambda self, cr, uid, ctx: uid,
72     }
73
74     def check_duplicate(self, cr, uid, ids):
75         # RFC *-* Why this limitation? why not in SQL constraint?
76         vals = self.read(cr, uid, ids, ['user', 'password'])[0]
77         cr.execute("select count(id) from email_server where user=%s and password=%s", (vals['user'], vals['password']))
78         res = cr.fetchone()
79         if res:
80             if res[0] > 1:
81                 return False
82         return True
83
84     def check_model(self, cr, uid, ids, context = None):
85         if not context:
86             context = {}
87         current_rec = self.read(cr, uid, ids, context)[0]
88         if current_rec:
89             model = self.pool.get(current_rec.get('object_id')[1])
90             if hasattr(model, 'message_new'):
91                 return True
92         return False
93
94     _constraints = [
95         (check_duplicate, 'Warning! Can\'t have duplicate server configuration!', ['user', 'password']),
96         (check_model, 'Warning! Record for slected Model can not be created\nPlease choose valid Model', ['object_id'])
97     ]
98
99     def onchange_server_type(self, cr, uid, ids, server_type=False, ssl=False):
100         port = 0
101         if server_type == 'pop':
102             port = ssl and 995 or 110
103         elif server_type == 'imap':
104             port = ssl and 993 or 143
105
106         return {'value':{'port':port}}
107
108     def set_draft(self, cr, uid, ids, context={}):
109         self.write(cr, uid, ids , {'state':'draft'})
110         return True
111     
112     def button_confirm_login(self, cr, uid, ids, context={}):
113         for server in self.browse(cr, uid, ids, context):
114             logger.notifyChannel('imap', netsvc.LOG_INFO, 'fetchmail start checking for new emails on %s' % (server.name))
115             context.update({'server_id': server.id, 'server_type': server.type})
116             count = 0
117             try:
118                 if server.type == 'imap':
119                     imap_server = None
120                     if server.is_ssl:
121                         imap_server = IMAP4_SSL(server.server, int(server.port))
122                     else:
123                         imap_server = IMAP4(server.server, int(server.port))
124
125                     imap_server.login(server.user, server.password)
126                     ret_server = imap_server
127                     
128                 elif server.type == 'pop':
129                     pop_server = None
130                     if server.is_ssl:
131                         pop_server = POP3_SSL(server.server, int(server.port))
132                     else:
133                         pop_server = POP3(server.server, int(server.port))
134
135                     #TODO: use this to remove only unread messages
136                     #pop_server.user("recent:"+server.user)
137                     pop_server.user(server.user)
138                     pop_server.pass_(server.password)
139                     ret_server = pop_server
140                     
141                 self.write(cr, uid, [server.id], {'state':'done'})
142                 if context.get('get_server',False):
143                     return ret_server
144             except Exception, e:
145                 logger.notifyChannel(server.type, netsvc.LOG_WARNING, '%s' % (e))
146         return True
147
148     def button_fetch_mail(self, cr, uid, ids, context={}):
149         self.fetch_mail(cr, uid, ids, context=context)
150         return True
151
152     def _fetch_mails(self, cr, uid, ids=False, context={}):
153         if not ids:
154             ids = self.search(cr, uid, [])
155         return self.fetch_mail(cr, uid, ids, context=context)
156
157     def fetch_mail(self, cr, uid, ids, context={}):
158         email_tool = self.pool.get('email.server.tools')
159         action_pool = self.pool.get('ir.actions.server')
160         context.update({'get_server': True})
161         for server in self.browse(cr, uid, ids, context):
162             count = 0
163             user = server.user_id.id or uid
164             try:
165                 if server.type == 'imap':
166                     imap_server = self.button_confirm_login(cr, uid, [server.id], context=context)
167                     imap_server.select()
168                     result, data = imap_server.search(None, '(UNSEEN)')
169                     for num in data[0].split():
170                         result, data = imap_server.fetch(num, '(RFC822)')
171                         res_id = email_tool.process_email(cr, user, server.object_id.model, data[0][1], attach=server.attach, context=context)
172                         if res_id and server.action_id:
173                             action_pool.run(cr, uid, [server.action_id.id], {'active_id': res_id, 'active_ids':[res_id]})
174
175                             imap_server.store(num, '+FLAGS', '\\Seen')
176                         count += 1
177                     logger.notifyChannel('imap', netsvc.LOG_INFO, 'fetchmail fetch/process %s email(s) from %s' % (count, server.name))
178
179                     imap_server.close()
180                     imap_server.logout()
181                 elif server.type == 'pop':
182                     pop_server = self.button_confirm_login(cr, uid, [server.id], context=context)
183                     pop_server.list()
184                     (numMsgs, totalSize) = pop_server.stat()
185                     for num in range(1, numMsgs + 1):
186                         (header, msges, octets) = pop_server.retr(num)
187                         msg = '\n'.join(msges)
188                         res_id = email_tool.process_email(cr, user, server.object_id.model, msg, attach=server.attach, context=context)
189                         if res_id and server.action_id:
190                             action_pool.run(cr, uid, [server.action_id.id], {'active_id': res_id, 'active_ids':[res_id]})
191
192                         pop_server.dele(num)
193
194                     pop_server.quit()
195
196                     logger.notifyChannel('imap', netsvc.LOG_INFO, 'fetchmail fetch %s email(s) from %s' % (numMsgs, server.name))
197
198             except Exception, e:
199                 logger.notifyChannel(server.type, netsvc.LOG_WARNING, '%s' % (e))
200
201         return True
202
203 email_server()
204
205 class mailgate_message(osv.osv):
206
207     _inherit = "mailgate.message"
208
209     _columns = {
210         'server_id': fields.many2one('email.server', "Mail Server", readonly=True, select=True),
211         'server_type':fields.selection([
212             ('pop', 'POP Server'),
213             ('imap', 'IMAP Server'),
214         ], 'Server Type', select=True, readonly=True),
215     }
216     _order = 'id desc'
217
218     def create(self, cr, uid, values, context=None):
219         if not context:
220             context={}
221         server_id = context.get('server_id',False)
222         server_type = context.get('server_type',False)
223         if server_id:
224             values['server_id'] = server_id
225         if server_type:
226             values['server_type'] = server_type
227         res = super(mailgate_message,self).create(cr, uid, values, context=context)
228         return res
229
230     def write(self, cr, uid, ids, values, context=None):
231         if not context:
232             context={}
233         server_id = context.get('server_id',False)
234         server_type = context.get('server_type',False)
235         if server_id:
236             values['server_id'] = server_id
237         if server_type:
238             values['server_type'] = server_type
239         res = super(mailgate_message,self).write(cr, uid, ids, values, context=context)
240         return res
241
242 mailgate_message()
243
244 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: