SickGear/sickbeard/sbdatetime.py

230 lines
8 KiB
Python
Raw Normal View History

# Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickGear.
#
# SickGear is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# SickGear is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with SickGear. If not, see <http://www.gnu.org/licenses/>.
import datetime
import locale
import functools
import re
Add smart logic to reduce api hits to newznab server types and improve how nzbs are downloaded. Add newznab smart logic to avoid missing releases when there are a great many recent releases. Change improve performance by using newznab server advertised capabilities. Change config/providers newznab to display only non-default categories. Change use scene season for wanted segment in backlog if show is scene numbering. Change combine Manage Searches / Backlog Search / Limited and Full to Force. Change consolidate limited and full backlog. Change config / Search / Backlog search frequency to instead spread backlog searches over a number of days. Change migrate minimum used value for search frequency into new minimum 7 for search spread. Change restrict nzb providers to 1 backlog batch run per day. Add to Config/Search/Unaired episodes/Allow episodes that are released early. Add to Config/Search/Unaired episodes/Use specific api requests to search for early episode releases. Add use related ids for newznab searches to increase search efficiency. Add periodic update of related show ids. Change terminology Edit Show/"Post processing" tab name to "Other". Add advanced feature "Related show IDs" to Edit Show/Other used for finding episodes and TV info. Add search info source image links to those that have zero id under Edit Show/Other/"Related show IDs". Add "set master" button to Edit Show/Other/"Related show IDs" for info source that can be changed. Change terminology displayShow "Indexers" to "Links" to cover internal and web links. Change add related show info sources on displayShow page. Change don't display "temporarily" defunct TVRage image link on displayShow pages unless it is master info source. Change if a defunct info source is the master of a show then present a link on displayShow to edit related show IDs. Change simplify the next backlog search run time display in the page footer. Change try ssl when fetching data thetvdb, imdb, trakt, scene exception. Change improve reliability to Trakt notifier by using show related id support. Change improve config/providers newznab categories layout. Change show loaded log message at start up and include info source. Change if episode has no airdate then set status to unaired (was skipped). Technical Change move scene_exceptions table from cache.db to sickbeard.db. Add related ids to show obj. Add use of mapped indexer ids for newznab. Add indexer to sql in wanted_eps. Add aired in (scene) season for wanted episodes. Add need_anime, need_sports, need_sd, need_hd, need_uhd to wanted episodes and added as parameter to update_providers. Add fix for lib lockfile/mkdirlockfile. Add set master TV info source logic. Change harden ui input validation. Add per action dialog confirmation. Change to reload page under more events. Change implement "Mark all added episodes Wanted to search for releases" when setting new info source.
2016-09-04 20:00:44 +00:00
import time
import sickbeard
from sickbeard.network_timezones import sb_timezone
date_presets = ('%Y-%m-%d',
'%a, %Y-%m-%d',
'%A, %Y-%m-%d',
'%y-%m-%d',
'%a, %y-%m-%d',
'%A, %y-%m-%d',
'%m/%d/%Y',
'%a, %m/%d/%Y',
'%A, %m/%d/%Y',
'%m/%d/%y',
'%a, %m/%d/%y',
'%A, %m/%d/%y',
'%m-%d-%Y',
'%a, %m-%d-%Y',
'%A, %m-%d-%Y',
'%m-%d-%y',
'%a, %m-%d-%y',
'%A, %m-%d-%y',
'%m.%d.%Y',
'%a, %m.%d.%Y',
'%A, %m.%d.%Y',
'%m.%d.%y',
'%a, %m.%d.%y',
'%A, %m.%d.%y',
'%d-%m-%Y',
'%a, %d-%m-%Y',
'%A, %d-%m-%Y',
'%d-%m-%y',
'%a, %d-%m-%y',
'%A, %d-%m-%y',
2014-10-22 02:19:06 +00:00
'%d/%m/%Y',
'%a, %d/%m/%Y',
'%A, %d/%m/%Y',
'%d/%m/%y',
'%a, %d/%m/%y',
'%A, %d/%m/%y',
'%d.%m.%Y',
'%a, %d.%m.%Y',
'%A, %d.%m.%Y',
'%d.%m.%y',
'%a, %d.%m.%y',
'%A, %d.%m.%y',
'%d. %b %Y',
'%a, %d. %b %Y',
'%A, %d. %b %Y',
'%d. %b %y',
'%a, %d. %b %y',
'%A, %d. %b %y',
'%d. %B %Y',
'%a, %d. %B %Y',
'%A, %d. %B %Y',
'%d. %B %y',
'%a, %d. %B %y',
'%A, %d. %B %y',
'%b %d, %Y',
'%a, %b %d, %Y',
'%A, %b %d, %Y',
'%B %d, %Y',
'%a, %B %d, %Y',
'%A, %B %d, %Y')
time_presets = ('%I:%M:%S %p',
'%I:%M:%S %P',
'%H:%M:%S')
# helper class
class static_or_instance(object):
def __init__(self, func):
self.func = func
def __get__(self, instance, owner):
return functools.partial(self.func, instance)
# subclass datetime.datetime to add function to display custom date and time formats
class sbdatetime(datetime.datetime):
has_locale = True
@static_or_instance
def is_locale_eng(self):
today = sbdatetime.sbfdate(sbdatetime.now(), '%A').lower()
return ('day' == today[-3::] and today[0:-3:] in ['sun', 'mon', 'tues', 'wednes', 'thurs', 'fri', 'satur']
and sbdatetime.sbfdate(sbdatetime.now(), '%B').lower() in [
'january', 'february', 'march', 'april', 'may', 'june',
'july', 'august', 'september', 'october', 'november', 'december'])
@static_or_instance
Change overhaul and add API functions Change API version... start with 10 Change set application response header to 'SickGear' + add API version Change return timezone (of network) in API Add indexer to calls Add SickGear Command tip for old SickBeard commands Add warning old sickbeard API calls only support tvdb shows Add "tvdbid" fallback only for sickbeard calls Add listcommands Add list of all commands (old + new) in listcommand page at the beginning Change hide 'listcommands' command from commands list, since it needs the API builder CSS + is html not json Add missing help in webapi Add episode info: absolute_number, scene_season, scene_episode, scene_absolute_number Add fork to SB command Add sg Add sg.activatescenenumbering Add sg.addrootdir Add sg.checkscheduler Add sg.deleterootdir Add sg.episode Add sg.episode.search Add sg.episode.setstatus Add sg.episode.subtitlesearch Add sg.exceptions Add sg.forcesearch Add sg.future Add sg.getdefaults Add sg.getindexericon Add sg.getindexers to list all indexers Add sg.getmessages Add sg.getnetworkicon Add sg.getrootdirs Add sg.getqualities Add sg.getqualitystrings Add sg.history Add sg.history.clear Add sg.history.trim Add sg.listtraktaccounts Add sg.listignorewords Add sg.listrequiedwords Add sg.logs Add sg.pausebacklog Add sg.postprocess Add sg.ping Add sg.restart Add sg.searchqueue Add sg.searchtv to search all indexers Add sg.setexceptions Add sg.setignorewords Add sg.setrequiredwords Add sg.setscenenumber Add sg.show Add sg.show.addexisting Add sg.show.addnew Add sg.show.cache Add sg.show.delete Add sg.show.getbanner Add sg.show.getfanart Add sg.show.getposter Add sg.show.getquality Add sg.show.listfanart Add sg.show.ratefanart Add sg.show.seasonlist Add sg.show.seasons Add sg.show.setquality Add sg.show.stats Add sg.show.refresh Add sg.show.pause Add sg.show.update Add sg.shows Add sg.shows.browsetrakt Add sg.shows.forceupdate Add sg.shows.queue Add sg.shows.stats Change sickbeard to sickgear Change sickbeard_call to property Change sg.episode.setstatus allow setting of quality Change sg.history, history command output Change sg.searchtv to list of indexers Add uhd4kweb to qualities Add upgrade_once to add existing shows Add upgrade_once to add new show Add upgrade_once to show quality settings (get/set) Add 'ids' to Show + Shows Add ids to coming eps + get tvdb id from ids Add 'status_str' to coming eps Add 'local_datetime' to comming eps + runtime Add X-Filename response header to getbanner, getposter Add X-Fanartname response header for sg.show.getfanart Add missing fields to sb.show Add missing fields to sb.shows Change sb.seasons Change overview optional Change make overview optional in shows Add setscenenumber to API builder Change move set_scene_numbering_helper into scnene_numbering for use in web interface and API Change use quality_map instead of fixed list Add eigthlevel for API/builder page Change limit indexer param to valid values Fix wrong parameter in existing apiBuilder.tmpl that prevents javascript from continuing + add console error message for it Fixed: filter missed shows correctly Add @gen.coroutine
2016-08-24 19:02:12 +00:00
def convert_to_setting(self, dt=None, force_local=False):
obj = (dt, self)[self is not None]
try:
Change overhaul and add API functions Change API version... start with 10 Change set application response header to 'SickGear' + add API version Change return timezone (of network) in API Add indexer to calls Add SickGear Command tip for old SickBeard commands Add warning old sickbeard API calls only support tvdb shows Add "tvdbid" fallback only for sickbeard calls Add listcommands Add list of all commands (old + new) in listcommand page at the beginning Change hide 'listcommands' command from commands list, since it needs the API builder CSS + is html not json Add missing help in webapi Add episode info: absolute_number, scene_season, scene_episode, scene_absolute_number Add fork to SB command Add sg Add sg.activatescenenumbering Add sg.addrootdir Add sg.checkscheduler Add sg.deleterootdir Add sg.episode Add sg.episode.search Add sg.episode.setstatus Add sg.episode.subtitlesearch Add sg.exceptions Add sg.forcesearch Add sg.future Add sg.getdefaults Add sg.getindexericon Add sg.getindexers to list all indexers Add sg.getmessages Add sg.getnetworkicon Add sg.getrootdirs Add sg.getqualities Add sg.getqualitystrings Add sg.history Add sg.history.clear Add sg.history.trim Add sg.listtraktaccounts Add sg.listignorewords Add sg.listrequiedwords Add sg.logs Add sg.pausebacklog Add sg.postprocess Add sg.ping Add sg.restart Add sg.searchqueue Add sg.searchtv to search all indexers Add sg.setexceptions Add sg.setignorewords Add sg.setrequiredwords Add sg.setscenenumber Add sg.show Add sg.show.addexisting Add sg.show.addnew Add sg.show.cache Add sg.show.delete Add sg.show.getbanner Add sg.show.getfanart Add sg.show.getposter Add sg.show.getquality Add sg.show.listfanart Add sg.show.ratefanart Add sg.show.seasonlist Add sg.show.seasons Add sg.show.setquality Add sg.show.stats Add sg.show.refresh Add sg.show.pause Add sg.show.update Add sg.shows Add sg.shows.browsetrakt Add sg.shows.forceupdate Add sg.shows.queue Add sg.shows.stats Change sickbeard to sickgear Change sickbeard_call to property Change sg.episode.setstatus allow setting of quality Change sg.history, history command output Change sg.searchtv to list of indexers Add uhd4kweb to qualities Add upgrade_once to add existing shows Add upgrade_once to add new show Add upgrade_once to show quality settings (get/set) Add 'ids' to Show + Shows Add ids to coming eps + get tvdb id from ids Add 'status_str' to coming eps Add 'local_datetime' to comming eps + runtime Add X-Filename response header to getbanner, getposter Add X-Fanartname response header for sg.show.getfanart Add missing fields to sb.show Add missing fields to sb.shows Change sb.seasons Change overview optional Change make overview optional in shows Add setscenenumber to API builder Change move set_scene_numbering_helper into scnene_numbering for use in web interface and API Change use quality_map instead of fixed list Add eigthlevel for API/builder page Change limit indexer param to valid values Fix wrong parameter in existing apiBuilder.tmpl that prevents javascript from continuing + add console error message for it Fixed: filter missed shows correctly Add @gen.coroutine
2016-08-24 19:02:12 +00:00
if force_local or 'local' == sickbeard.TIMEZONE_DISPLAY:
return obj.astimezone(sb_timezone)
except (StandardError, Exception):
pass
return obj
@static_or_instance
def setlocale(self, setlocale=True, use_has_locale=None, locale_str=''):
if setlocale:
try:
if None is use_has_locale or use_has_locale:
locale.setlocale(locale.LC_TIME, locale_str)
except locale.Error:
if None is not use_has_locale:
sbdatetime.has_locale = False
pass
# display Time in SickGear Format
@static_or_instance
def sbftime(self, dt=None, show_seconds=False, t_preset=None, setlocale=True, markup=False):
sbdatetime.setlocale(setlocale=setlocale, use_has_locale=sbdatetime.has_locale, locale_str='us_US')
strt = ''
obj = (dt, self)[self is not None]
if None is not obj:
tmpl = (((sickbeard.TIME_PRESET, sickbeard.TIME_PRESET_W_SECONDS)[show_seconds]),
t_preset)[None is not t_preset]
tmpl = (tmpl.replace(':%S', ''), tmpl)[show_seconds]
strt = sbdatetime.sbstrftime(obj, tmpl.replace('%P', '%p'))
if sickbeard.TRIM_ZERO:
strt = re.sub(r'^0(\d:\d\d)', r'\1', strt)
if re.search(r'(?im)%p$', tmpl):
if '%p' in tmpl:
strt = strt.upper()
elif '%P' in tmpl:
strt = strt.lower()
if sickbeard.TRIM_ZERO:
strt = re.sub(r'(?im)^(\d+)(?::00)?(\s?[ap]m)', r'\1\2', strt)
if markup:
match = re.search(r'(?im)(\d{1,2})(?:(.)(\d\d)(?:(.)(\d\d))?)?(?:\s?([ap]m))?$', strt)
if match:
strt = ('%s%s%s%s%s%s' % (
('<span class="time-hr">%s</span>' % match.group(1), '')[None is match.group(1)],
('<span class="time-hr-min">%s</span>' % match.group(2), '')[None is match.group(2)],
('<span class="time-min">%s</span>' % match.group(3), '')[None is match.group(3)],
('<span class="time-min-sec">%s</span>' % match.group(4), '')[None is match.group(4)],
('<span class="time-sec">%s</span>' % match.group(5), '')[None is match.group(5)],
('<span class="time-am-pm">%s</span>' % match.group(6), '')[None is match.group(6)]))
sbdatetime.setlocale(setlocale=setlocale, use_has_locale=sbdatetime.has_locale)
return strt
# display Date in SickGear Format
@static_or_instance
def sbfdate(self, dt=None, d_preset=None, setlocale=True):
sbdatetime.setlocale(setlocale=setlocale)
strd = ''
try:
obj = (dt, self)[self is not None]
if None is not obj:
strd = sbdatetime.sbstrftime(obj, (sickbeard.DATE_PRESET, d_preset)[None is not d_preset])
finally:
sbdatetime.setlocale(setlocale=setlocale)
return strd
# display Datetime in SickGear Format
@static_or_instance
def sbfdatetime(self, dt=None, show_seconds=False, d_preset=None, t_preset=None, markup=False):
sbdatetime.setlocale()
strd = ''
obj = (dt, self)[self is not None]
try:
if None is not obj:
strd = u'%s, %s' % (
sbdatetime.sbstrftime(obj, (sickbeard.DATE_PRESET, d_preset)[None is not d_preset]),
sbdatetime.sbftime(dt, show_seconds, t_preset, False, markup))
finally:
sbdatetime.setlocale(use_has_locale=sbdatetime.has_locale)
2014-05-26 21:32:47 +00:00
return strd
Add smart logic to reduce api hits to newznab server types and improve how nzbs are downloaded. Add newznab smart logic to avoid missing releases when there are a great many recent releases. Change improve performance by using newznab server advertised capabilities. Change config/providers newznab to display only non-default categories. Change use scene season for wanted segment in backlog if show is scene numbering. Change combine Manage Searches / Backlog Search / Limited and Full to Force. Change consolidate limited and full backlog. Change config / Search / Backlog search frequency to instead spread backlog searches over a number of days. Change migrate minimum used value for search frequency into new minimum 7 for search spread. Change restrict nzb providers to 1 backlog batch run per day. Add to Config/Search/Unaired episodes/Allow episodes that are released early. Add to Config/Search/Unaired episodes/Use specific api requests to search for early episode releases. Add use related ids for newznab searches to increase search efficiency. Add periodic update of related show ids. Change terminology Edit Show/"Post processing" tab name to "Other". Add advanced feature "Related show IDs" to Edit Show/Other used for finding episodes and TV info. Add search info source image links to those that have zero id under Edit Show/Other/"Related show IDs". Add "set master" button to Edit Show/Other/"Related show IDs" for info source that can be changed. Change terminology displayShow "Indexers" to "Links" to cover internal and web links. Change add related show info sources on displayShow page. Change don't display "temporarily" defunct TVRage image link on displayShow pages unless it is master info source. Change if a defunct info source is the master of a show then present a link on displayShow to edit related show IDs. Change simplify the next backlog search run time display in the page footer. Change try ssl when fetching data thetvdb, imdb, trakt, scene exception. Change improve reliability to Trakt notifier by using show related id support. Change improve config/providers newznab categories layout. Change show loaded log message at start up and include info source. Change if episode has no airdate then set status to unaired (was skipped). Technical Change move scene_exceptions table from cache.db to sickbeard.db. Add related ids to show obj. Add use of mapped indexer ids for newznab. Add indexer to sql in wanted_eps. Add aired in (scene) season for wanted episodes. Add need_anime, need_sports, need_sd, need_hd, need_uhd to wanted episodes and added as parameter to update_providers. Add fix for lib lockfile/mkdirlockfile. Add set master TV info source logic. Change harden ui input validation. Add per action dialog confirmation. Change to reload page under more events. Change implement "Mark all added episodes Wanted to search for releases" when setting new info source.
2016-09-04 20:00:44 +00:00
@staticmethod
def sbstrftime(obj, str_format):
try:
result = obj.strftime(str_format),
except ValueError:
result = obj.replace(tzinfo=None).strftime(str_format)
return result if isinstance(result, basestring) else \
isinstance(result, tuple) and 1 == len(result) and '%s' % result[0] or ''
Add smart logic to reduce api hits to newznab server types and improve how nzbs are downloaded. Add newznab smart logic to avoid missing releases when there are a great many recent releases. Change improve performance by using newznab server advertised capabilities. Change config/providers newznab to display only non-default categories. Change use scene season for wanted segment in backlog if show is scene numbering. Change combine Manage Searches / Backlog Search / Limited and Full to Force. Change consolidate limited and full backlog. Change config / Search / Backlog search frequency to instead spread backlog searches over a number of days. Change migrate minimum used value for search frequency into new minimum 7 for search spread. Change restrict nzb providers to 1 backlog batch run per day. Add to Config/Search/Unaired episodes/Allow episodes that are released early. Add to Config/Search/Unaired episodes/Use specific api requests to search for early episode releases. Add use related ids for newznab searches to increase search efficiency. Add periodic update of related show ids. Change terminology Edit Show/"Post processing" tab name to "Other". Add advanced feature "Related show IDs" to Edit Show/Other used for finding episodes and TV info. Add search info source image links to those that have zero id under Edit Show/Other/"Related show IDs". Add "set master" button to Edit Show/Other/"Related show IDs" for info source that can be changed. Change terminology displayShow "Indexers" to "Links" to cover internal and web links. Change add related show info sources on displayShow page. Change don't display "temporarily" defunct TVRage image link on displayShow pages unless it is master info source. Change if a defunct info source is the master of a show then present a link on displayShow to edit related show IDs. Change simplify the next backlog search run time display in the page footer. Change try ssl when fetching data thetvdb, imdb, trakt, scene exception. Change improve reliability to Trakt notifier by using show related id support. Change improve config/providers newznab categories layout. Change show loaded log message at start up and include info source. Change if episode has no airdate then set status to unaired (was skipped). Technical Change move scene_exceptions table from cache.db to sickbeard.db. Add related ids to show obj. Add use of mapped indexer ids for newznab. Add indexer to sql in wanted_eps. Add aired in (scene) season for wanted episodes. Add need_anime, need_sports, need_sd, need_hd, need_uhd to wanted episodes and added as parameter to update_providers. Add fix for lib lockfile/mkdirlockfile. Add set master TV info source logic. Change harden ui input validation. Add per action dialog confirmation. Change to reload page under more events. Change implement "Mark all added episodes Wanted to search for releases" when setting new info source.
2016-09-04 20:00:44 +00:00
@static_or_instance
def totimestamp(self, dt=None, default=None):
obj = (dt, self)[self is not None]
timestamp = default
try:
timestamp = time.mktime(obj.timetuple())
finally:
return (default, timestamp)[isinstance(timestamp, float)]