We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[12.0][mail_tracking] many MailTracking email not found warnings
This code snippet is polluting my logs with warning messages.

https://github.com/OCA/social/blob/8d985d8da9fa864113f87cd59a2b3173f7f89193/mail_tracking/controllers/main.py#L69-L78

How can this work if state will be marked 'opened' the first time? Each successive open will trigger above warning, because state is now 'opened' and will not match the above domain `('state', 'in', ['sent', 'delivered'])`.

 Is it intended to generate warnings each time mail is opened? Or what am I missing?

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `mail_tracking/controllers/main.py`
Content:
```
1 # Copyright 2016 Antonio Espinosa - <antonio.espinosa@tecnativa.com>
2 # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
3 
4 import werkzeug
5 import odoo
6 from contextlib import contextmanager
7 from odoo import api, http, SUPERUSER_ID
8 
9 from odoo.addons.mail.controllers.main import MailController
10 import logging
11 import base64
12 _logger = logging.getLogger(__name__)
13 
14 BLANK = 'R0lGODlhAQABAIAAANvf7wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='
15 
16 
17 @contextmanager
18 def db_env(dbname):
19     if not http.db_filter([dbname]):
20         raise werkzeug.exceptions.BadRequest()
21     cr = None
22     if dbname == http.request.db:
23         cr = http.request.cr
24     if not cr:
25         cr = odoo.sql_db.db_connect(dbname).cursor()
26     with api.Environment.manage():
27         yield api.Environment(cr, SUPERUSER_ID, {})
28 
29 
30 class MailTrackingController(MailController):
31 
32     def _request_metadata(self):
33         """Prepare remote info metadata"""
34         request = http.request.httprequest
35         return {
36             'ip': request.remote_addr or False,
37             'user_agent': request.user_agent or False,
38             'os_family': request.user_agent.platform or False,
39             'ua_family': request.user_agent.browser or False,
40         }
41 
42     @http.route(['/mail/tracking/all/<string:db>',
43                  '/mail/tracking/event/<string:db>/<string:event_type>'],
44                 type='http', auth='none', csrf=False)
45     def mail_tracking_event(self, db, event_type=None, **kw):
46         """Route used by external mail service"""
47         metadata = self._request_metadata()
48         res = None
49         with db_env(db) as env:
50             try:
51                 res = env['mail.tracking.email'].event_process(
52                     http.request, kw, metadata, event_type=event_type)
53             except Exception:
54                 pass
55         if not res or res == 'NOT FOUND':
56             return werkzeug.exceptions.NotAcceptable()
57         return res
58 
59     @http.route(['/mail/tracking/open/<string:db>'
60                  '/<int:tracking_email_id>/blank.gif',
61                  '/mail/tracking/open/<string:db>'
62                  '/<int:tracking_email_id>/<string:token>/blank.gif'],
63                 type='http', auth='none', methods=['GET'])
64     def mail_tracking_open(self, db, tracking_email_id, token=False, **kw):
65         """Route used to track mail openned (With & Without Token)"""
66         metadata = self._request_metadata()
67         with db_env(db) as env:
68             try:
69                 tracking_email = env['mail.tracking.email'].search([
70                     ('id', '=', tracking_email_id),
71                     ('state', 'in', ['sent', 'delivered']),
72                     ('token', '=', token),
73                 ])
74                 if tracking_email:
75                     tracking_email.event_create('open', metadata)
76                 else:
77                     _logger.warning(
78                         "MailTracking email '%s' not found", tracking_email_id)
79             except Exception:
80                 pass
81 
82         # Always return GIF blank image
83         response = werkzeug.wrappers.Response()
84         response.mimetype = 'image/gif'
85         response.data = base64.b64decode(BLANK)
86         return response
87 
88     @http.route()
89     def mail_init_messaging(self):
90         """Route used to initial values of Discuss app"""
91         values = super().mail_init_messaging()
92         values.update({
93             'failed_counter':
94                 http.request.env['mail.message'].get_failed_count(),
95         })
96         return values
97
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/mail_tracking/controllers/main.py b/mail_tracking/controllers/main.py
--- a/mail_tracking/controllers/main.py
+++ b/mail_tracking/controllers/main.py
@@ -68,14 +68,13 @@
             try:
                 tracking_email = env['mail.tracking.email'].search([
                     ('id', '=', tracking_email_id),
-                    ('state', 'in', ['sent', 'delivered']),
                     ('token', '=', token),
                 ])
-                if tracking_email:
-                    tracking_email.event_create('open', metadata)
-                else:
+                if not tracking_email:
                     _logger.warning(
                         "MailTracking email '%s' not found", tracking_email_id)
+                elif tracking_email.state in ('sent', 'delivered'):
+                    tracking_email.event_create('open', metadata)
             except Exception:
                 pass

{"golden_diff": "diff --git a/mail_tracking/controllers/main.py b/mail_tracking/controllers/main.py\n--- a/mail_tracking/controllers/main.py\n+++ b/mail_tracking/controllers/main.py\n@@ -68,14 +68,13 @@\n             try:\n                 tracking_email = env['mail.tracking.email'].search([\n                     ('id', '=', tracking_email_id),\n-                    ('state', 'in', ['sent', 'delivered']),\n                     ('token', '=', token),\n                 ])\n-                if tracking_email:\n-                    tracking_email.event_create('open', metadata)\n-                else:\n+                if not tracking_email:\n                     _logger.warning(\n                         \"MailTracking email '%s' not found\", tracking_email_id)\n+                elif tracking_email.state in ('sent', 'delivered'):\n+                    tracking_email.event_create('open', metadata)\n             except Exception:\n                 pass\n", "issue": "[12.0][mail_tracking] many MailTracking email not found warnings\nThis code snippet is polluting my logs with warning messages.\r\n\r\nhttps://github.com/OCA/social/blob/8d985d8da9fa864113f87cd59a2b3173f7f89193/mail_tracking/controllers/main.py#L69-L78\r\n\r\nHow can this work if state will be marked 'opened' the first time? Each successive open will trigger above warning, because state is now 'opened' and will not match the above domain `('state', 'in', ['sent', 'delivered'])`.\r\n\r\n Is it intended to generate warnings each time mail is opened? Or what am I missing?\n", "before_files": [{"content": "# Copyright 2016 Antonio Espinosa - <antonio.espinosa@tecnativa.com>\n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).\n\nimport werkzeug\nimport odoo\nfrom contextlib import contextmanager\nfrom odoo import api, http, SUPERUSER_ID\n\nfrom odoo.addons.mail.controllers.main import MailController\nimport logging\nimport base64\n_logger = logging.getLogger(__name__)\n\nBLANK = 'R0lGODlhAQABAIAAANvf7wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='\n\n\n@contextmanager\ndef db_env(dbname):\n    if not http.db_filter([dbname]):\n        raise werkzeug.exceptions.BadRequest()\n    cr = None\n    if dbname == http.request.db:\n        cr = http.request.cr\n    if not cr:\n        cr = odoo.sql_db.db_connect(dbname).cursor()\n    with api.Environment.manage():\n        yield api.Environment(cr, SUPERUSER_ID, {})\n\n\nclass MailTrackingController(MailController):\n\n    def _request_metadata(self):\n        \"\"\"Prepare remote info metadata\"\"\"\n        request = http.request.httprequest\n        return {\n            'ip': request.remote_addr or False,\n            'user_agent': request.user_agent or False,\n            'os_family': request.user_agent.platform or False,\n            'ua_family': request.user_agent.browser or False,\n        }\n\n    @http.route(['/mail/tracking/all/<string:db>',\n                 '/mail/tracking/event/<string:db>/<string:event_type>'],\n                type='http', auth='none', csrf=False)\n    def mail_tracking_event(self, db, event_type=None, **kw):\n        \"\"\"Route used by external mail service\"\"\"\n        metadata = self._request_metadata()\n        res = None\n        with db_env(db) as env:\n            try:\n                res = env['mail.tracking.email'].event_process(\n                    http.request, kw, metadata, event_type=event_type)\n            except Exception:\n                pass\n        if not res or res == 'NOT FOUND':\n            return werkzeug.exceptions.NotAcceptable()\n        return res\n\n    @http.route(['/mail/tracking/open/<string:db>'\n                 '/<int:tracking_email_id>/blank.gif',\n                 '/mail/tracking/open/<string:db>'\n                 '/<int:tracking_email_id>/<string:token>/blank.gif'],\n                type='http', auth='none', methods=['GET'])\n    def mail_tracking_open(self, db, tracking_email_id, token=False, **kw):\n        \"\"\"Route used to track mail openned (With & Without Token)\"\"\"\n        metadata = self._request_metadata()\n        with db_env(db) as env:\n            try:\n                tracking_email = env['mail.tracking.email'].search([\n                    ('id', '=', tracking_email_id),\n                    ('state', 'in', ['sent', 'delivered']),\n                    ('token', '=', token),\n                ])\n                if tracking_email:\n                    tracking_email.event_create('open', metadata)\n                else:\n                    _logger.warning(\n                        \"MailTracking email '%s' not found\", tracking_email_id)\n            except Exception:\n                pass\n\n        # Always return GIF blank image\n        response = werkzeug.wrappers.Response()\n        response.mimetype = 'image/gif'\n        response.data = base64.b64decode(BLANK)\n        return response\n\n    @http.route()\n    def mail_init_messaging(self):\n        \"\"\"Route used to initial values of Discuss app\"\"\"\n        values = super().mail_init_messaging()\n        values.update({\n            'failed_counter':\n                http.request.env['mail.message'].get_failed_count(),\n        })\n        return values\n", "path": "mail_tracking/controllers/main.py"}], "after_files": [{"content": "# Copyright 2016 Antonio Espinosa - <antonio.espinosa@tecnativa.com>\n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).\n\nimport werkzeug\nimport odoo\nfrom contextlib import contextmanager\nfrom odoo import api, http, SUPERUSER_ID\n\nfrom odoo.addons.mail.controllers.main import MailController\nimport logging\nimport base64\n_logger = logging.getLogger(__name__)\n\nBLANK = 'R0lGODlhAQABAIAAANvf7wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='\n\n\n@contextmanager\ndef db_env(dbname):\n    if not http.db_filter([dbname]):\n        raise werkzeug.exceptions.BadRequest()\n    cr = None\n    if dbname == http.request.db:\n        cr = http.request.cr\n    if not cr:\n        cr = odoo.sql_db.db_connect(dbname).cursor()\n    with api.Environment.manage():\n        yield api.Environment(cr, SUPERUSER_ID, {})\n\n\nclass MailTrackingController(MailController):\n\n    def _request_metadata(self):\n        \"\"\"Prepare remote info metadata\"\"\"\n        request = http.request.httprequest\n        return {\n            'ip': request.remote_addr or False,\n            'user_agent': request.user_agent or False,\n            'os_family': request.user_agent.platform or False,\n            'ua_family': request.user_agent.browser or False,\n        }\n\n    @http.route(['/mail/tracking/all/<string:db>',\n                 '/mail/tracking/event/<string:db>/<string:event_type>'],\n                type='http', auth='none', csrf=False)\n    def mail_tracking_event(self, db, event_type=None, **kw):\n        \"\"\"Route used by external mail service\"\"\"\n        metadata = self._request_metadata()\n        res = None\n        with db_env(db) as env:\n            try:\n                res = env['mail.tracking.email'].event_process(\n                    http.request, kw, metadata, event_type=event_type)\n            except Exception:\n                pass\n        if not res or res == 'NOT FOUND':\n            return werkzeug.exceptions.NotAcceptable()\n        return res\n\n    @http.route(['/mail/tracking/open/<string:db>'\n                 '/<int:tracking_email_id>/blank.gif',\n                 '/mail/tracking/open/<string:db>'\n                 '/<int:tracking_email_id>/<string:token>/blank.gif'],\n                type='http', auth='none', methods=['GET'])\n    def mail_tracking_open(self, db, tracking_email_id, token=False, **kw):\n        \"\"\"Route used to track mail openned (With & Without Token)\"\"\"\n        metadata = self._request_metadata()\n        with db_env(db) as env:\n            try:\n                tracking_email = env['mail.tracking.email'].search([\n                    ('id', '=', tracking_email_id),\n                    ('token', '=', token),\n                ])\n                if not tracking_email:\n                    _logger.warning(\n                        \"MailTracking email '%s' not found\", tracking_email_id)\n                elif tracking_email.state in ('sent', 'delivered'):\n                    tracking_email.event_create('open', metadata)\n            except Exception:\n                pass\n\n        # Always return GIF blank image\n        response = werkzeug.wrappers.Response()\n        response.mimetype = 'image/gif'\n        response.data = base64.b64decode(BLANK)\n        return response\n\n    @http.route()\n    def mail_init_messaging(self):\n        \"\"\"Route used to initial values of Discuss app\"\"\"\n        values = super().mail_init_messaging()\n        values.update({\n            'failed_counter':\n                http.request.env['mail.message'].get_failed_count(),\n        })\n        return values\n", "path": "mail_tracking/controllers/main.py"}]}