We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Show appears on schedule page to air "today" even though it airs on different day
**Describe the bug**
The TV Show "Last Week Tonight with John Oliver" appears on schedule page to air "today" even though it airs on different day.

**To Reproduce**
http://x.x.x.x:8081/schedule/

**Expected behavior**
The TV Show "Last Week Tonight with John Oliver" airs on Sunday nights, as shown on the individual show page, and should appear on the schedule page as such instead of always appearing under "Today".

**Screenshots**

![image](https://user-images.githubusercontent.com/2957454/129420471-1da271c3-0a4e-48b4-92f7-c01f35a115a4.png)


**Medusa (please complete the following information):**
Branch: master
Commit: 9b23c72f7e24bf638819e32d72f33e433f9649c4
Version: 0.5.15
Database: 44.18

Python Version: | 3.8.9 (default, Jul 15 2021, 01:46:40) [GCC 10.2.0]
SSL Version: | OpenSSL 1.1.1k 25 Mar 2021
OS: | Linux-5.10.47-x86_64-with-glibc2.2.5
Locale: | en_US.UTF-8
Timezone: | EDT

**Debug logs (at least 50 lines):**
General > Advanced Settings > Enable debug

[https://paste.kodi.tv/rucoceqelu.kodi](url)

**Additional context**
Tried choosing different index, and restarted services,  but issue remains with just the TV Show "Last Week Tonight with John Oliver".


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `medusa/show/coming_episodes.py`
Content:
```
1 # coding=utf-8
2 # This file is part of Medusa.
3 #
4 # Medusa is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # Medusa is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with Medusa. If not, see <http://www.gnu.org/licenses/>.
16 
17 from __future__ import unicode_literals
18 
19 from builtins import object
20 from builtins import str
21 from datetime import date, timedelta
22 from operator import itemgetter
23 
24 from medusa import app
25 from medusa.common import (
26     ARCHIVED,
27     DOWNLOADED,
28     IGNORED,
29     SNATCHED,
30     SNATCHED_BEST,
31     SNATCHED_PROPER,
32     UNAIRED,
33     WANTED
34 )
35 from medusa.db import DBConnection
36 from medusa.helper.common import dateFormat, timeFormat
37 from medusa.helpers.quality import get_quality_string
38 from medusa.network_timezones import parse_date_time
39 from medusa.sbdatetime import sbdatetime
40 from medusa.tv.series import Series, SeriesIdentifier
41 
42 
43 class ComingEpisodes(object):
44     """
45     Missed:   yesterday...(less than 1 week)
46     Today:    today
47     Soon:     tomorrow till next week
48     Later:    later than next week
49     """
50 
51     categories = ['later', 'missed', 'soon', 'today']
52     sorts = {
53         'date': itemgetter('localtime'),
54         'network': itemgetter('network', 'localtime'),
55         'show': itemgetter('show_name', 'localtime'),
56     }
57 
58     def __init__(self):
59         pass
60 
61     @staticmethod
62     def get_coming_episodes(categories, sort, group, paused=app.COMING_EPS_DISPLAY_PAUSED):
63         """
64         :param categories: The categories of coming episodes. See ``ComingEpisodes.categories``
65         :param sort: The sort to apply to the coming episodes. See ``ComingEpisodes.sorts``
66         :param group: ``True`` to group the coming episodes by category, ``False`` otherwise
67         :param paused: ``True`` to include paused shows, ``False`` otherwise
68         :return: The list of coming episodes
69         """
70         categories = ComingEpisodes._get_categories(categories)
71         sort = ComingEpisodes._get_sort(sort)
72 
73         today = date.today().toordinal()
74         next_week = (date.today() + timedelta(days=7)).toordinal()
75         recently = (date.today() - timedelta(days=app.COMING_EPS_MISSED_RANGE)).toordinal()
76         status_list = [DOWNLOADED, SNATCHED, SNATCHED_BEST, SNATCHED_PROPER,
77                        ARCHIVED, IGNORED]
78 
79         db = DBConnection()
80         fields_to_select = ', '.join(
81             ['airdate', 'airs', 'e.description as description', 'episode', 'imdb_id', 'e.indexer',
82              'indexer_id', 'name', 'network', 'paused', 's.quality', 'runtime', 'season', 'show_name',
83              'showid', 's.status']
84         )
85         results = db.select(
86             'SELECT %s ' % fields_to_select +
87             'FROM tv_episodes e, tv_shows s '
88             'WHERE season != 0 '
89             'AND airdate >= ? '
90             'AND airdate < ? '
91             'AND s.indexer = e.indexer '
92             'AND s.indexer_id = e.showid '
93             'AND e.status NOT IN (' + ','.join(['?'] * len(status_list)) + ')',
94             [today, next_week] + status_list
95         )
96 
97         done_shows_list = [int(result['showid']) for result in results]
98         placeholder = ','.join(['?'] * len(done_shows_list))
99         placeholder2 = ','.join(['?'] * len([DOWNLOADED, SNATCHED, SNATCHED_BEST, SNATCHED_PROPER]))
100 
101         # FIXME: This inner join is not multi indexer friendly.
102         results += db.select(
103             'SELECT %s ' % fields_to_select +
104             'FROM tv_episodes e, tv_shows s '
105             'WHERE season != 0 '
106             'AND showid NOT IN (' + placeholder + ') '
107             'AND s.indexer_id = e.showid '
108             'AND airdate = (SELECT airdate '
109             'FROM tv_episodes inner_e '
110             'WHERE inner_e.season != 0 '
111             'AND inner_e.showid = e.showid '
112             'AND inner_e.indexer = e.indexer '
113             'AND inner_e.airdate >= ? '
114             'ORDER BY inner_e.airdate ASC LIMIT 1) '
115             'AND e.status NOT IN (' + placeholder2 + ')',
116             done_shows_list + [next_week] + [DOWNLOADED, SNATCHED, SNATCHED_BEST, SNATCHED_PROPER]
117         )
118 
119         results += db.select(
120             'SELECT %s ' % fields_to_select +
121             'FROM tv_episodes e, tv_shows s '
122             'WHERE season != 0 '
123             'AND s.indexer_id = e.showid '
124             'AND airdate < ? '
125             'AND airdate >= ? '
126             'AND e.status IN (?,?) '
127             'AND e.status NOT IN (' + ','.join(['?'] * len(status_list)) + ')',
128             [today, recently, WANTED, UNAIRED] + status_list
129         )
130 
131         for index, item in enumerate(results):
132             identifier = SeriesIdentifier.from_id(int(item['indexer']), item['indexer_id'])
133             show = Series.find_by_identifier(identifier)
134             item['series_slug'] = identifier.slug
135             results[index]['localtime'] = sbdatetime.convert_to_setting(
136                 parse_date_time(item['airdate'], item['airs'], item['network']))
137             results[index]['externals'] = show.externals
138 
139         results.sort(key=ComingEpisodes.sorts[sort])
140 
141         if not group:
142             return results
143 
144         grouped_results = ComingEpisodes._get_categories_map(categories)
145 
146         for result in results:
147             if result['paused'] and not paused:
148                 continue
149 
150             result['airs'] = str(result['airs']).replace('am', ' AM').replace('pm', ' PM').replace('  ', ' ')
151             result['airdate'] = result['localtime'].toordinal()
152 
153             if result['airdate'] < today:
154                 category = 'missed'
155             elif result['airdate'] >= next_week:
156                 category = 'later'
157             elif result['airdate'] == today:
158                 category = 'today'
159             else:
160                 category = 'soon'
161 
162             if len(categories) > 0 and category not in categories:
163                 continue
164 
165             if not result['network']:
166                 result['network'] = ''
167 
168             result['qualityValue'] = result['quality']
169             result['quality'] = get_quality_string(result['quality'])
170             result['airs'] = sbdatetime.sbftime(result['localtime'], t_preset=timeFormat).lstrip('0').replace(' 0', ' ')
171             result['weekday'] = 1 + date.fromordinal(result['airdate']).weekday()
172             result['tvdbid'] = result['indexer_id']
173             result['airdate'] = sbdatetime.sbfdate(result['localtime'], d_preset=dateFormat)
174             result['localtime'] = result['localtime'].toordinal()
175 
176             grouped_results[category].append(result)
177 
178         return grouped_results
179 
180     @staticmethod
181     def _get_categories(categories):
182         if not categories:
183             return []
184 
185         if not isinstance(categories, list):
186             return categories.split('|')
187 
188         return categories
189 
190     @staticmethod
191     def _get_categories_map(categories):
192         if not categories:
193             return {}
194 
195         return {category: [] for category in categories}
196 
197     @staticmethod
198     def _get_sort(sort):
199         sort = sort.lower() if sort else ''
200 
201         if sort not in ComingEpisodes.sorts:
202             return 'date'
203 
204         return sort
205
```
--- 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/medusa/show/coming_episodes.py b/medusa/show/coming_episodes.py
--- a/medusa/show/coming_episodes.py
+++ b/medusa/show/coming_episodes.py
@@ -168,7 +168,8 @@
             result['qualityValue'] = result['quality']
             result['quality'] = get_quality_string(result['quality'])
             result['airs'] = sbdatetime.sbftime(result['localtime'], t_preset=timeFormat).lstrip('0').replace(' 0', ' ')
-            result['weekday'] = 1 + date.fromordinal(result['airdate']).weekday()
+            # Monday - Sunday (0 - 6)
+            result['weekday'] = date.fromordinal(result['airdate']).weekday()
             result['tvdbid'] = result['indexer_id']
             result['airdate'] = sbdatetime.sbfdate(result['localtime'], d_preset=dateFormat)
             result['localtime'] = result['localtime'].toordinal()

{"golden_diff": "diff --git a/medusa/show/coming_episodes.py b/medusa/show/coming_episodes.py\n--- a/medusa/show/coming_episodes.py\n+++ b/medusa/show/coming_episodes.py\n@@ -168,7 +168,8 @@\n             result['qualityValue'] = result['quality']\n             result['quality'] = get_quality_string(result['quality'])\n             result['airs'] = sbdatetime.sbftime(result['localtime'], t_preset=timeFormat).lstrip('0').replace(' 0', ' ')\n-            result['weekday'] = 1 + date.fromordinal(result['airdate']).weekday()\n+            # Monday - Sunday (0 - 6)\n+            result['weekday'] = date.fromordinal(result['airdate']).weekday()\n             result['tvdbid'] = result['indexer_id']\n             result['airdate'] = sbdatetime.sbfdate(result['localtime'], d_preset=dateFormat)\n             result['localtime'] = result['localtime'].toordinal()\n", "issue": "Show appears on schedule page to air \"today\" even though it airs on different day\n**Describe the bug**\r\nThe TV Show \"Last Week Tonight with John Oliver\" appears on schedule page to air \"today\" even though it airs on different day.\r\n\r\n**To Reproduce**\r\nhttp://x.x.x.x:8081/schedule/\r\n\r\n**Expected behavior**\r\nThe TV Show \"Last Week Tonight with John Oliver\" airs on Sunday nights, as shown on the individual show page, and should appear on the schedule page as such instead of always appearing under \"Today\".\r\n\r\n**Screenshots**\r\n\r\n![image](https://user-images.githubusercontent.com/2957454/129420471-1da271c3-0a4e-48b4-92f7-c01f35a115a4.png)\r\n\r\n\r\n**Medusa (please complete the following information):**\r\nBranch:\u00a0master\r\nCommit:\u00a09b23c72f7e24bf638819e32d72f33e433f9649c4\r\nVersion:\u00a00.5.15\r\nDatabase:\u00a044.18\r\n\r\nPython Version: | 3.8.9 (default, Jul 15 2021, 01:46:40) [GCC 10.2.0]\r\nSSL Version: | OpenSSL 1.1.1k 25 Mar 2021\r\nOS: | Linux-5.10.47-x86_64-with-glibc2.2.5\r\nLocale: | en_US.UTF-8\r\nTimezone: | EDT\r\n\r\n**Debug logs (at least 50 lines):**\r\nGeneral > Advanced Settings > Enable debug\r\n\r\n[https://paste.kodi.tv/rucoceqelu.kodi](url)\r\n\r\n**Additional context**\r\nTried choosing different index, and restarted services,  but issue remains with just the TV Show \"Last Week Tonight with John Oliver\".\r\n\n", "before_files": [{"content": "# coding=utf-8\n# This file is part of Medusa.\n#\n# Medusa is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Medusa is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Medusa. If not, see <http://www.gnu.org/licenses/>.\n\nfrom __future__ import unicode_literals\n\nfrom builtins import object\nfrom builtins import str\nfrom datetime import date, timedelta\nfrom operator import itemgetter\n\nfrom medusa import app\nfrom medusa.common import (\n    ARCHIVED,\n    DOWNLOADED,\n    IGNORED,\n    SNATCHED,\n    SNATCHED_BEST,\n    SNATCHED_PROPER,\n    UNAIRED,\n    WANTED\n)\nfrom medusa.db import DBConnection\nfrom medusa.helper.common import dateFormat, timeFormat\nfrom medusa.helpers.quality import get_quality_string\nfrom medusa.network_timezones import parse_date_time\nfrom medusa.sbdatetime import sbdatetime\nfrom medusa.tv.series import Series, SeriesIdentifier\n\n\nclass ComingEpisodes(object):\n    \"\"\"\n    Missed:   yesterday...(less than 1 week)\n    Today:    today\n    Soon:     tomorrow till next week\n    Later:    later than next week\n    \"\"\"\n\n    categories = ['later', 'missed', 'soon', 'today']\n    sorts = {\n        'date': itemgetter('localtime'),\n        'network': itemgetter('network', 'localtime'),\n        'show': itemgetter('show_name', 'localtime'),\n    }\n\n    def __init__(self):\n        pass\n\n    @staticmethod\n    def get_coming_episodes(categories, sort, group, paused=app.COMING_EPS_DISPLAY_PAUSED):\n        \"\"\"\n        :param categories: The categories of coming episodes. See ``ComingEpisodes.categories``\n        :param sort: The sort to apply to the coming episodes. See ``ComingEpisodes.sorts``\n        :param group: ``True`` to group the coming episodes by category, ``False`` otherwise\n        :param paused: ``True`` to include paused shows, ``False`` otherwise\n        :return: The list of coming episodes\n        \"\"\"\n        categories = ComingEpisodes._get_categories(categories)\n        sort = ComingEpisodes._get_sort(sort)\n\n        today = date.today().toordinal()\n        next_week = (date.today() + timedelta(days=7)).toordinal()\n        recently = (date.today() - timedelta(days=app.COMING_EPS_MISSED_RANGE)).toordinal()\n        status_list = [DOWNLOADED, SNATCHED, SNATCHED_BEST, SNATCHED_PROPER,\n                       ARCHIVED, IGNORED]\n\n        db = DBConnection()\n        fields_to_select = ', '.join(\n            ['airdate', 'airs', 'e.description as description', 'episode', 'imdb_id', 'e.indexer',\n             'indexer_id', 'name', 'network', 'paused', 's.quality', 'runtime', 'season', 'show_name',\n             'showid', 's.status']\n        )\n        results = db.select(\n            'SELECT %s ' % fields_to_select +\n            'FROM tv_episodes e, tv_shows s '\n            'WHERE season != 0 '\n            'AND airdate >= ? '\n            'AND airdate < ? '\n            'AND s.indexer = e.indexer '\n            'AND s.indexer_id = e.showid '\n            'AND e.status NOT IN (' + ','.join(['?'] * len(status_list)) + ')',\n            [today, next_week] + status_list\n        )\n\n        done_shows_list = [int(result['showid']) for result in results]\n        placeholder = ','.join(['?'] * len(done_shows_list))\n        placeholder2 = ','.join(['?'] * len([DOWNLOADED, SNATCHED, SNATCHED_BEST, SNATCHED_PROPER]))\n\n        # FIXME: This inner join is not multi indexer friendly.\n        results += db.select(\n            'SELECT %s ' % fields_to_select +\n            'FROM tv_episodes e, tv_shows s '\n            'WHERE season != 0 '\n            'AND showid NOT IN (' + placeholder + ') '\n            'AND s.indexer_id = e.showid '\n            'AND airdate = (SELECT airdate '\n            'FROM tv_episodes inner_e '\n            'WHERE inner_e.season != 0 '\n            'AND inner_e.showid = e.showid '\n            'AND inner_e.indexer = e.indexer '\n            'AND inner_e.airdate >= ? '\n            'ORDER BY inner_e.airdate ASC LIMIT 1) '\n            'AND e.status NOT IN (' + placeholder2 + ')',\n            done_shows_list + [next_week] + [DOWNLOADED, SNATCHED, SNATCHED_BEST, SNATCHED_PROPER]\n        )\n\n        results += db.select(\n            'SELECT %s ' % fields_to_select +\n            'FROM tv_episodes e, tv_shows s '\n            'WHERE season != 0 '\n            'AND s.indexer_id = e.showid '\n            'AND airdate < ? '\n            'AND airdate >= ? '\n            'AND e.status IN (?,?) '\n            'AND e.status NOT IN (' + ','.join(['?'] * len(status_list)) + ')',\n            [today, recently, WANTED, UNAIRED] + status_list\n        )\n\n        for index, item in enumerate(results):\n            identifier = SeriesIdentifier.from_id(int(item['indexer']), item['indexer_id'])\n            show = Series.find_by_identifier(identifier)\n            item['series_slug'] = identifier.slug\n            results[index]['localtime'] = sbdatetime.convert_to_setting(\n                parse_date_time(item['airdate'], item['airs'], item['network']))\n            results[index]['externals'] = show.externals\n\n        results.sort(key=ComingEpisodes.sorts[sort])\n\n        if not group:\n            return results\n\n        grouped_results = ComingEpisodes._get_categories_map(categories)\n\n        for result in results:\n            if result['paused'] and not paused:\n                continue\n\n            result['airs'] = str(result['airs']).replace('am', ' AM').replace('pm', ' PM').replace('  ', ' ')\n            result['airdate'] = result['localtime'].toordinal()\n\n            if result['airdate'] < today:\n                category = 'missed'\n            elif result['airdate'] >= next_week:\n                category = 'later'\n            elif result['airdate'] == today:\n                category = 'today'\n            else:\n                category = 'soon'\n\n            if len(categories) > 0 and category not in categories:\n                continue\n\n            if not result['network']:\n                result['network'] = ''\n\n            result['qualityValue'] = result['quality']\n            result['quality'] = get_quality_string(result['quality'])\n            result['airs'] = sbdatetime.sbftime(result['localtime'], t_preset=timeFormat).lstrip('0').replace(' 0', ' ')\n            result['weekday'] = 1 + date.fromordinal(result['airdate']).weekday()\n            result['tvdbid'] = result['indexer_id']\n            result['airdate'] = sbdatetime.sbfdate(result['localtime'], d_preset=dateFormat)\n            result['localtime'] = result['localtime'].toordinal()\n\n            grouped_results[category].append(result)\n\n        return grouped_results\n\n    @staticmethod\n    def _get_categories(categories):\n        if not categories:\n            return []\n\n        if not isinstance(categories, list):\n            return categories.split('|')\n\n        return categories\n\n    @staticmethod\n    def _get_categories_map(categories):\n        if not categories:\n            return {}\n\n        return {category: [] for category in categories}\n\n    @staticmethod\n    def _get_sort(sort):\n        sort = sort.lower() if sort else ''\n\n        if sort not in ComingEpisodes.sorts:\n            return 'date'\n\n        return sort\n", "path": "medusa/show/coming_episodes.py"}], "after_files": [{"content": "# coding=utf-8\n# This file is part of Medusa.\n#\n# Medusa is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Medusa is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Medusa. If not, see <http://www.gnu.org/licenses/>.\n\nfrom __future__ import unicode_literals\n\nfrom builtins import object\nfrom builtins import str\nfrom datetime import date, timedelta\nfrom operator import itemgetter\n\nfrom medusa import app\nfrom medusa.common import (\n    ARCHIVED,\n    DOWNLOADED,\n    IGNORED,\n    SNATCHED,\n    SNATCHED_BEST,\n    SNATCHED_PROPER,\n    UNAIRED,\n    WANTED\n)\nfrom medusa.db import DBConnection\nfrom medusa.helper.common import dateFormat, timeFormat\nfrom medusa.helpers.quality import get_quality_string\nfrom medusa.network_timezones import parse_date_time\nfrom medusa.sbdatetime import sbdatetime\nfrom medusa.tv.series import Series, SeriesIdentifier\n\n\nclass ComingEpisodes(object):\n    \"\"\"\n    Missed:   yesterday...(less than 1 week)\n    Today:    today\n    Soon:     tomorrow till next week\n    Later:    later than next week\n    \"\"\"\n\n    categories = ['later', 'missed', 'soon', 'today']\n    sorts = {\n        'date': itemgetter('localtime'),\n        'network': itemgetter('network', 'localtime'),\n        'show': itemgetter('show_name', 'localtime'),\n    }\n\n    def __init__(self):\n        pass\n\n    @staticmethod\n    def get_coming_episodes(categories, sort, group, paused=app.COMING_EPS_DISPLAY_PAUSED):\n        \"\"\"\n        :param categories: The categories of coming episodes. See ``ComingEpisodes.categories``\n        :param sort: The sort to apply to the coming episodes. See ``ComingEpisodes.sorts``\n        :param group: ``True`` to group the coming episodes by category, ``False`` otherwise\n        :param paused: ``True`` to include paused shows, ``False`` otherwise\n        :return: The list of coming episodes\n        \"\"\"\n        categories = ComingEpisodes._get_categories(categories)\n        sort = ComingEpisodes._get_sort(sort)\n\n        today = date.today().toordinal()\n        next_week = (date.today() + timedelta(days=7)).toordinal()\n        recently = (date.today() - timedelta(days=app.COMING_EPS_MISSED_RANGE)).toordinal()\n        status_list = [DOWNLOADED, SNATCHED, SNATCHED_BEST, SNATCHED_PROPER,\n                       ARCHIVED, IGNORED]\n\n        db = DBConnection()\n        fields_to_select = ', '.join(\n            ['airdate', 'airs', 'e.description as description', 'episode', 'imdb_id', 'e.indexer',\n             'indexer_id', 'name', 'network', 'paused', 's.quality', 'runtime', 'season', 'show_name',\n             'showid', 's.status']\n        )\n        results = db.select(\n            'SELECT %s ' % fields_to_select +\n            'FROM tv_episodes e, tv_shows s '\n            'WHERE season != 0 '\n            'AND airdate >= ? '\n            'AND airdate < ? '\n            'AND s.indexer = e.indexer '\n            'AND s.indexer_id = e.showid '\n            'AND e.status NOT IN (' + ','.join(['?'] * len(status_list)) + ')',\n            [today, next_week] + status_list\n        )\n\n        done_shows_list = [int(result['showid']) for result in results]\n        placeholder = ','.join(['?'] * len(done_shows_list))\n        placeholder2 = ','.join(['?'] * len([DOWNLOADED, SNATCHED, SNATCHED_BEST, SNATCHED_PROPER]))\n\n        # FIXME: This inner join is not multi indexer friendly.\n        results += db.select(\n            'SELECT %s ' % fields_to_select +\n            'FROM tv_episodes e, tv_shows s '\n            'WHERE season != 0 '\n            'AND showid NOT IN (' + placeholder + ') '\n            'AND s.indexer_id = e.showid '\n            'AND airdate = (SELECT airdate '\n            'FROM tv_episodes inner_e '\n            'WHERE inner_e.season != 0 '\n            'AND inner_e.showid = e.showid '\n            'AND inner_e.indexer = e.indexer '\n            'AND inner_e.airdate >= ? '\n            'ORDER BY inner_e.airdate ASC LIMIT 1) '\n            'AND e.status NOT IN (' + placeholder2 + ')',\n            done_shows_list + [next_week] + [DOWNLOADED, SNATCHED, SNATCHED_BEST, SNATCHED_PROPER]\n        )\n\n        results += db.select(\n            'SELECT %s ' % fields_to_select +\n            'FROM tv_episodes e, tv_shows s '\n            'WHERE season != 0 '\n            'AND s.indexer_id = e.showid '\n            'AND airdate < ? '\n            'AND airdate >= ? '\n            'AND e.status IN (?,?) '\n            'AND e.status NOT IN (' + ','.join(['?'] * len(status_list)) + ')',\n            [today, recently, WANTED, UNAIRED] + status_list\n        )\n\n        for index, item in enumerate(results):\n            identifier = SeriesIdentifier.from_id(int(item['indexer']), item['indexer_id'])\n            show = Series.find_by_identifier(identifier)\n            item['series_slug'] = identifier.slug\n            results[index]['localtime'] = sbdatetime.convert_to_setting(\n                parse_date_time(item['airdate'], item['airs'], item['network']))\n            results[index]['externals'] = show.externals\n\n        results.sort(key=ComingEpisodes.sorts[sort])\n\n        if not group:\n            return results\n\n        grouped_results = ComingEpisodes._get_categories_map(categories)\n\n        for result in results:\n            if result['paused'] and not paused:\n                continue\n\n            result['airs'] = str(result['airs']).replace('am', ' AM').replace('pm', ' PM').replace('  ', ' ')\n            result['airdate'] = result['localtime'].toordinal()\n\n            if result['airdate'] < today:\n                category = 'missed'\n            elif result['airdate'] >= next_week:\n                category = 'later'\n            elif result['airdate'] == today:\n                category = 'today'\n            else:\n                category = 'soon'\n\n            if len(categories) > 0 and category not in categories:\n                continue\n\n            if not result['network']:\n                result['network'] = ''\n\n            result['qualityValue'] = result['quality']\n            result['quality'] = get_quality_string(result['quality'])\n            result['airs'] = sbdatetime.sbftime(result['localtime'], t_preset=timeFormat).lstrip('0').replace(' 0', ' ')\n            # Monday - Sunday (0 - 6)\n            result['weekday'] = date.fromordinal(result['airdate']).weekday()\n            result['tvdbid'] = result['indexer_id']\n            result['airdate'] = sbdatetime.sbfdate(result['localtime'], d_preset=dateFormat)\n            result['localtime'] = result['localtime'].toordinal()\n\n            grouped_results[category].append(result)\n\n        return grouped_results\n\n    @staticmethod\n    def _get_categories(categories):\n        if not categories:\n            return []\n\n        if not isinstance(categories, list):\n            return categories.split('|')\n\n        return categories\n\n    @staticmethod\n    def _get_categories_map(categories):\n        if not categories:\n            return {}\n\n        return {category: [] for category in categories}\n\n    @staticmethod\n    def _get_sort(sort):\n        sort = sort.lower() if sort else ''\n\n        if sort not in ComingEpisodes.sorts:\n            return 'date'\n\n        return sort\n", "path": "medusa/show/coming_episodes.py"}]}