a76c54ff2da5c58f9c77db9c687c40468b41431f
[odoo/odoo.git] / addons / mail / update.py
1 # -*- coding: utf-8 -*-
2 import datetime
3 import logging
4 import sys
5 import werkzeug.urls
6 import urllib2
7
8 import openerp
9 from openerp import release, SUPERUSER_ID
10 from openerp.osv import osv
11 from openerp.tools.translate import _
12 from openerp.tools.safe_eval import safe_eval
13 from openerp.tools.config import config
14 from openerp.tools import misc
15
16 _logger = logging.getLogger(__name__)
17
18 """
19 Time interval that will be used to determine up to which date we will
20 check the logs to see if a message we just received was already logged.
21 @type: datetime.timedelta
22 """
23 _PREVIOUS_LOG_CHECK = datetime.timedelta(days=365)
24
25 def get_sys_logs(self, cr, uid):
26     """
27     Utility method to send a publisher warranty get logs messages.
28     """
29     pool = openerp.registry(cr.dbname)
30
31     dbuuid = pool.get('ir.config_parameter').get_param(cr, uid, 'database.uuid')
32     db_create_date = pool.get('ir.config_parameter').get_param(cr, SUPERUSER_ID, 'database.create_date')
33     limit_date = datetime.datetime.now()
34     limit_date = limit_date - datetime.timedelta(15)
35     limit_date_str = limit_date.strftime(misc.DEFAULT_SERVER_DATETIME_FORMAT)
36     nbr_users = pool.get("res.users").search(cr, uid, [], count=True)
37     nbr_active_users = pool.get("res.users").search(cr, uid, [("login_date", ">=", limit_date_str)], count=True)
38     nbr_share_users = False
39     nbr_active_share_users = False
40     if "share" in pool.get("res.users")._all_columns:
41         nbr_share_users = pool.get("res.users").search(cr, uid, [("share", "=", True)], count=True)
42         nbr_active_share_users = pool.get("res.users").search(cr, uid, [("share", "=", True), ("login_date", ">=", limit_date_str)], count=True)
43     user = pool.get("res.users").browse(cr, uid, uid)
44
45     web_base_url = self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url', 'False')
46     msg = {
47         "dbuuid": dbuuid,
48         "nbr_users": nbr_users,
49         "nbr_active_users": nbr_active_users,
50         "nbr_share_users": nbr_share_users,
51         "nbr_active_share_users": nbr_active_share_users,
52         "dbname": cr.dbname,
53         "db_create_date": db_create_date,
54         "version": release.version,
55         "language": user.lang,
56         "web_base_url": web_base_url,
57     }
58     msg.update(pool.get("res.company").read(cr,uid,[1],["name","email","phone"])[0])
59
60     add_arg = {"timeout":30} if sys.version_info >= (2,6) else {}
61     arguments = {'arg0': msg, "action": "update",}
62     arguments_raw = werkzeug.urls.url_encode(arguments)
63
64     url = config.get("publisher_warranty_url")
65
66     uo = urllib2.urlopen(url, arguments_raw, **add_arg)
67     result = {}
68     try:
69         submit_result = uo.read()
70         result = safe_eval(submit_result)
71     finally:
72         uo.close()
73     return result
74
75 class publisher_warranty_contract(osv.osv):
76     _name = "publisher_warranty.contract"
77
78     def update_notification(self, cr, uid, ids, cron_mode=True, context=None):
79         """
80         Send a message to OpenERP's publisher warranty server to check the
81         validity of the contracts, get notifications, etc...
82
83         @param cron_mode: If true, catch all exceptions (appropriate for usage in a cron).
84         @type cron_mode: boolean
85         """
86         try:
87             try:
88                 result = get_sys_logs(self, cr, uid)
89             except Exception:
90                 if cron_mode: # we don't want to see any stack trace in cron
91                     return False
92                 _logger.debug("Exception while sending a get logs messages", exc_info=1)
93                 raise osv.except_osv(_("Error"), _("Error during communication with the publisher warranty server."))
94             # old behavior based on res.log; now on mail.message, that is not necessarily installed
95             IMD = self.pool['ir.model.data']
96             user = self.pool['res.users'].browse(cr, SUPERUSER_ID, SUPERUSER_ID)
97             poster = IMD.xmlid_to_object(cr, SUPERUSER_ID, 'mail.group_all_employees', context=context)
98             if not (poster and poster.exists()):
99                 if not user.exists():
100                     return True
101                 poster = user
102             for message in result["messages"]:
103                 try:
104                     poster.message_post(body=message, subtype='mt_comment', partner_ids=[user.partner_id.id])
105                 except Exception:
106                     _logger.warning('Cannot send ping message', exc_info=True)
107         except Exception:
108             if cron_mode:
109                 return False # we don't want to see any stack trace in cron
110             else:
111                 raise
112         return True
113
114 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
115