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.

135 lines
5.3 KiB

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