You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

137 lines
5.3 KiB

  1. # -*- coding: utf-8 -*-
  2. import logging
  3. from odoo import models, fields, api, _
  4. _logger = logging.getLogger(__name__)
  5. class Fetchmail(models.Model):
  6. _inherit = 'fetchmail.server'
  7. check_mailbox_size = fields.Boolean("Check Size")
  8. mailbox_size_partner_ids = fields.Many2many(
  9. "res.partner", string="Contacts to notify",
  10. domain=[('email', '!=', False)]
  11. )
  12. @api.model
  13. def _check_mailboxes_size_cron(self):
  14. """ Method called by cron to fetch mails from servers """
  15. return self.search([
  16. ('state', '=', 'done'),
  17. ('type', '=', 'imap'),
  18. ('check_mailbox_size', '=', True)
  19. ])._check_mailbox_size()
  20. @api.multi
  21. def _check_mailbox_size(self):
  22. for server in self:
  23. result_msg = ''
  24. imap_server = None
  25. try:
  26. if not server.mailbox_size_partner_ids:
  27. continue
  28. result_msg += _('<h3>Server %s</h3>') % server.name
  29. _logger.info(
  30. "Starting to check mailbox size for server %s"
  31. % server.name)
  32. imap_server = server.connect()
  33. # The list of all folders
  34. result, list = imap_server.list()
  35. if result != "OK":
  36. raise Exception(_("Server responded %s") % result)
  37. result_msg += _(
  38. "<table>"
  39. "<thead>"
  40. "<tr>"
  41. "<th style=\"text-align:left\">Folder</th>"
  42. "<th style=\"text-align:right\"># Msg</th>"
  43. "<th style=\"text-align:right\">Size</th>"
  44. "</tr>"
  45. "</thead>"
  46. "<tbody>"
  47. )
  48. number_of_messages_all = 0
  49. size_all = 0
  50. for item in list:
  51. x = item.split()
  52. mailbox = x[-1]
  53. # Select the desired folder
  54. result, number_of_messages = imap_server.select(
  55. mailbox, readonly=1)
  56. if result != 'OK':
  57. _logger.info(
  58. "Server %s responded %s for folder %s"
  59. % (server.name, number_of_messages, mailbox))
  60. continue
  61. number_of_messages_all += int(number_of_messages[0])
  62. size_folder = 0
  63. # Go through all the messages in the selected folder
  64. typ, msg = imap_server.search(None, 'ALL')
  65. # Find the first and last messages
  66. m = [int(msg_part) for msg_part in msg[0].split()]
  67. m.sort()
  68. if m:
  69. message_set = "%d:%d" % (m[0], m[-1])
  70. result, sizes_response = imap_server.fetch(
  71. message_set, "(UID RFC822.SIZE)")
  72. for i in range(m[-1]):
  73. tmp = sizes_response[i].split()
  74. size_folder += int(tmp[-1].replace(')', ''))
  75. else:
  76. size_folder = 0
  77. result_msg += (
  78. "<tr>"
  79. "<td style=\"text-align:left\">%s</td>"
  80. "<td style=\"text-align:right\">%i</td>"
  81. "<td style=\"text-align:right\">%s</td>"
  82. "</tr>"
  83. ) % (mailbox, int(number_of_messages[0]), size_folder)
  84. size_all += size_folder
  85. result_msg += _(
  86. "</tbody>"
  87. "<tfoot>"
  88. "<tr>"
  89. "<td style=\"text-align:left;font-weight:bold\">Sum</td>"
  90. "<td style=\"text-align:right;font-weight:bold\">%i</td>"
  91. "<td style=\"text-align:right;font-weight:bold\">"
  92. "%10.3fMB</td>"
  93. "</tr>"
  94. "</tfoot>"
  95. "</table>"
  96. ) % (number_of_messages_all, size_all / 1e6)
  97. except Exception as e:
  98. result_msg = _(
  99. "An error occured while checking mailbox %s:<br/>%s"
  100. ) % (server.name, str(e))
  101. finally:
  102. if imap_server:
  103. imap_server.logout()
  104. if result_msg:
  105. self.env['mail.mail'].create({
  106. 'subject': _("Mailbox size for server %s") % server.name,
  107. 'body_html': result_msg,
  108. 'recipient_ids': [
  109. (6, 0, server.mailbox_size_partner_ids.ids)]
  110. })
  111. @api.model
  112. def _update_cron(self):
  113. res = super(Fetchmail, self)._update_cron()
  114. if self.env.context.get('fetchmail_cron_running'):
  115. return res
  116. try:
  117. cron = self.env.ref(
  118. 'mail_check_mailbox_size.ir_cron_check_mailbox_size')
  119. cron.toggle(model=self._name, domain=[
  120. ('state', '=', 'done'), ('type', '=', 'imap'),
  121. ('check_mailbox_size', '=', True),
  122. ])
  123. except ValueError:
  124. # Nevermind if ir_cron_check_mailbox_size cannot be found
  125. pass
  126. return res