def get_airdates(self, item):
     if not item:
         return
     infoproperties = {}
     if item.get('last_episode_to_air'):
         i = item.get('last_episode_to_air', {})
         infoproperties['last_aired'] = utils.date_to_format(i.get('air_date'), xbmc.getRegion('dateshort'))
         infoproperties['last_aired.long'] = utils.date_to_format(i.get('air_date'), xbmc.getRegion('datelong'))
         infoproperties['last_aired.day'] = utils.date_to_format(i.get('air_date'), "%A")
         infoproperties['last_aired.episode'] = i.get('episode_number')
         infoproperties['last_aired.name'] = i.get('name')
         infoproperties['last_aired.tmdb_id'] = i.get('id')
         infoproperties['last_aired.plot'] = i.get('overview')
         infoproperties['last_aired.season'] = i.get('season_number')
         infoproperties['last_aired.rating'] = '{:0,.1f}'.format(utils.try_parse_float(i.get('vote_average')))
         infoproperties['last_aired.votes'] = i.get('vote_count')
         infoproperties['last_aired.thumb'] = self.get_season_thumb(i)
     if item.get('next_episode_to_air'):
         i = item.get('next_episode_to_air', {})
         infoproperties['next_aired'] = utils.date_to_format(i.get('air_date'), xbmc.getRegion('dateshort'))
         infoproperties['next_aired.long'] = utils.date_to_format(i.get('air_date'), xbmc.getRegion('datelong'))
         infoproperties['next_aired.day'] = utils.date_to_format(i.get('air_date'), "%A")
         infoproperties['next_aired.episode'] = i.get('episode_number')
         infoproperties['next_aired.name'] = i.get('name')
         infoproperties['next_aired.tmdb_id'] = i.get('id')
         infoproperties['next_aired.plot'] = i.get('overview')
         infoproperties['next_aired.season'] = i.get('season_number')
         infoproperties['next_aired.thumb'] = self.get_season_thumb(i)
     return infoproperties
Example #2
0
def date2timeStamp(pdate):
    # Kodi bug: returns '%H%H' or '%I%I'
    df = xbmc.getRegion('dateshort') + ' ' + xbmc.getRegion('time').replace(
        '%H%H', '%H').replace('%I%I', '%I').replace(':%S', '')
    notifyLog(pdate + ' ' + df)
    dtt = time.strptime(pdate, df)
    return int(time.mktime(dtt))
Example #3
0
    def add_date_properties(self):
        try:
            try:
                year, month, day = self.item_information['info'].get(
                    'aired', '0000-00-00').split('-')
            except ValueError:
                year, month, day = self.item_information['info'].get(
                    'aired', '00/00/0000').split('/')

            self.setProperty('item.info.aired.year', year)
            self.setProperty('item.info.aired.month', month)
            self.setProperty('item.info.aired.day', day)
        except ValueError:
            pass

        if 'aired' in self.item_information['info']:
            aired_date = self.item_information['info']['aired']
            aired_date = tools.parse_datetime(aired_date, g.DATE_TIME_FORMAT)
            aired_date = aired_date.strftime(xbmc.getRegion('dateshort'))
            try:
                aired_date = aired_date[:10]
            except IndexError:
                aired_date = "TBA"
            self.setProperty('item.info.aired', str(aired_date))

        if 'premiered' in self.item_information['info']:
            premiered = self.item_information['info']['premiered']
            premiered = tools.parse_datetime(premiered, g.DATE_TIME_FORMAT)
            premiered = premiered.strftime(xbmc.getRegion('dateshort'))
            try:
                premiered = premiered[:10]
            except IndexError:
                premiered = "TBA"
            self.setProperty('item.info.premiered', str(premiered))
    def add_date_properties(self):
        try:
            try:
                year, month, day = self.item_information['info'].get(
                    'aired', '0000-00-00').split('-')
            except ValueError:
                year, month, day = self.item_information['info'].get(
                    'aired', '00/00/0000').split('/')

            self.setProperty('item.info.aired.year', year)
            self.setProperty('item.info.aired.month', month)
            self.setProperty('item.info.aired.day', day)
        except ValueError:
            pass

        if 'aired' in self.item_information['info']:
            aired_date = self.item_information['info']['aired']
            aired_date = tools.parse_datetime(aired_date)
            aired_date = aired_date.strftime(xbmc.getRegion('dateshort'))
            self.item_information['info']['aired'] = aired_date

        if 'premiered' in self.item_information['info']:
            premiered = self.item_information['info']['premiered']
            premiered = tools.parse_datetime(premiered)
            premiered = premiered.strftime(xbmc.getRegion('dateshort'))
            self.item_information['info']['premiered'] = premiered
 def _normalize_outlook( self, outlook ):
     # set temperature and speed unit
     tempunit = xbmc.getRegion( id="tempunit" )
     speedunit = xbmc.getRegion( id="speedunit" )
     # enumerate thru and localize values
     for count, tmp_outlook in enumerate( outlook ):
         if ( tempunit != "°F" ):
             # find all temps
             temps = re.findall( "[0-9]+F", tmp_outlook )
             for temp in temps:
                 tmp_outlook = re.sub( temp, self.localize_unit( temp ) + tempunit, tmp_outlook, 1 )
             # calculate the localized temp ranges if C is required
             temps = re.findall( "[low|mid|high]+ [0-9]+s", tmp_outlook )
             add = { "l": 3, "m": 6, "h": 9 }
             for temp in temps:
                 new_temp = self.localize_unit( str( int( re.search( "[0-9]+", temp ).group( 1 ) ) + add.get( temp[ 0 ], 3 ) ) )
                 temp_int = int( float( new_temp ) / 10 ) * 10
                 temp_rem = int( float( new_temp ) % 10 )
                 temp_text = [ "low %ds", "mid %ds", "high %ds" ][ ( temp_rem >= 4 ) + ( temp_rem >= 6 ) ]
                 tmp_outlook = re.sub( temp, temp_text % ( temp_int, ), tmp_outlook, 1 )
         if ( speedunit != "mph" ):
             # calculate the localized wind if C is required
             winds = re.findall( "[0-9]+ to [0-9]+ mph", tmp_outlook )
             for wind in winds:
                 speeds = re.findall( "[0-9]+", wind )
                 for speed in speeds:
                     wind = re.sub( speed, self.localize_unit( speed, "speed" ).split( " " )[ 0 ], wind, 1 )
                 tmp_outlook = re.sub( "[0-9]+ to [0-9]+ mph", wind.replace( "mph", speedunit ), tmp_outlook, 1 )
         # add our text back to the main variable
         outlook[ count ] = tmp_outlook
     # return normalized text
     return outlook
Example #6
0
def Hehestreams(home, away, orig_title):
	try:
		html = GetURL("http://hehestreams.xyz/")
		titles = common.parseDOM(html, "a", attrs={"class": "results-link"})
		links = common.parseDOM(html, "a", attrs={"class": "results-link"}, ret="href")
		for title in titles:
			if home.lower() in title.lower() and away.lower() in title.lower():
				link = links[titles.index(title)]
				link = "http://hehestreams.xyz"+link
				html = GetURL(link)
				lnks = common.parseDOM(html, "option", ret="value")
				print lnks
				for lnk in lnks:
					if 'turner' in lnk:
						try:
							timest = lnk.split("exp=")[-1].split("~acl")[0]
							time_exp = datetime.fromtimestamp(int(timest)).strftime(xbmc.getRegion('time').replace('%H%H','%H').replace(':%S',''))
						except:
							time_exp = ''
						addDirectLink('Turner - (external player) link expires '+time_exp, {'Title': orig_title}, lnk)
					elif 'neulion' in lnk:
						lnk = lnk.replace('amp;','')
						try:
							timest = lnk.split("expires%3D")[-1].split("%7E")[0]
							time_exp = datetime.fromtimestamp(int(timest)).strftime(xbmc.getRegion('time').replace('%H%H','%H').replace(':%S',''))
						except:
							time_exp = ''
						addDirectLink('Neulion link expires '+time_exp, {'Title': orig_title}, lnk)
	except:
		pass
Example #7
0
    def add_date_properties(self):
        info = deepcopy(self.item_information['info'])
        media_type = info.get("mediatype", None)
        if media_type in [g.MEDIA_SHOW, g.MEDIA_SEASON, g.MEDIA_EPISODE]:
            # Convert dates to localtime for display
            g.convert_info_dates(info)
        try:
            year, month, day = self.item_information['info'].get(
                'aired', '0000-00-00').split('-')

            self.setProperty('item.info.aired.year', year)
            self.setProperty('item.info.aired.month', month)
            self.setProperty('item.info.aired.day', day)
        except ValueError:
            pass

        if 'aired' in info:
            aired_date = info['aired']
            aired_date = tools.parse_datetime(aired_date, g.DATE_TIME_FORMAT)
            aired_date = aired_date.strftime(xbmc.getRegion('dateshort'))
            try:
                aired_date = aired_date[:10]
            except IndexError:
                aired_date = "TBA"
            self.setProperty('item.info.aired', g.UNICODE(aired_date))

        if 'premiered' in info:
            premiered = info['premiered']
            premiered = tools.parse_datetime(premiered, g.DATE_TIME_FORMAT)
            premiered = premiered.strftime(xbmc.getRegion('dateshort'))
            try:
                premiered = premiered[:10]
            except IndexError:
                premiered = "TBA"
            self.setProperty('item.info.premiered', g.UNICODE(premiered))
Example #8
0
def prettydate(dt, addtime=True):
    dt = dt + utc_offset()
    if addtime:
        return dt.strftime(
            xbmc.getRegion("datelong") + ", " +
            xbmc.getRegion("time").replace(":%S", "").replace("%H%H", "%H"))
    else:
        return dt.strftime(xbmc.getRegion("datelong"))
def format_date_new(date, abbrev=False, time=False, pretty=True, if_modified=False, hours=0):
    #def format_date(date, pretty=True, short=True, reverse=False, modified=False, hours=0):
    try:  #FIXME: clean this up, too many hacks
        # set proper format

        # Thursday, March 7, 2013   -   Thu, Mar 7, 2013
        pretty_output = [xbmc.getRegion("datelong"), xbmc.getRegion("datelong").replace("%A", "%a").replace("%B", "%b")][abbrev]

        # 03/07/2013 02:30:00 pm   -   03/07/2013
        regular_output = ["{date} {hours}".format(date=xbmc.getRegion("dateShort"), time=xbmc.getRegion("dateShort")), xbmc.getRegion("dateShort")][short]

        # Thu, 13 Mar 2013 14:30:00 GMT
        if_modified_output = "%a, %d %b %Y %H:%M:%S GMT"


        format = [
            [["%Y-%m-%d %H:%M:%S", "%Y-%m-%d"][short], [xbmc.getRegion("dateshort"), xbmc.getRegion("datelong")][pretty]],
            ["%Y-%m-%d %H:%M:%S", "%a, %d %b %Y %H:%M:%S GMT"]
        ][modified]



        """
        ['xbmc.getRegion("dateshort")', '%m/%d/%Y']
        ['xbmc.getRegion("datelong")', '%A, %B %d, %Y']
        format = {
                "input": ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d"][short],
                "output": [xbmc.getRegion("dateshort"), "%a, %d %b %Y %H:%M:%S GMT"][if_modified]
            }
            "long": {
                "input": ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M:%S"][if_modified],
                "output": [xbmc.getRegion("dateshort"), "%a, %d %b %Y %H:%M:%S GMT"][if_modified]
            }


              [xbmc.getRegion("dateshort"), xbmc.getRegion("datelong")][pretty]
            ],
            ["%Y-%m-%d %H:%M:%S", "%a, %d %b %Y %H:%M:%S GMT"]
        ][if_modified]
"""
        # reverse for saving in NFO and DB
        if (reverse):
            format.reverse()
        # format as date/time
        if (modified):
            dt = datetime.datetime(*time.strptime(date, format[0])[ : 6]) + datetime.timedelta(hours=hours)
        # format as date
        else:
            dt = datetime.date(*time.strptime(date, format[0])[ : 3])
        # return result
        #print format
        return dt.strftime(format[1])
    except Exception as error:
        #print str(error)
        # something is wrong, return original
        return date
Example #10
0
def getDateFormat():
    df = xbmc.getRegion("dateshort")
    tf = xbmc.getRegion("time").split(":")

    try:
        # time format is 12h with am/pm
        return df + " " + tf[0][0:2] + ":" + tf[1] + " " + tf[2].split()[1]
    except IndexError:
        # time format is 24h with or w/o leading zero
        return df + " " + tf[0][0:2] + ":" + tf[1]
Example #11
0
def getDateFormat():
    df = xbmc.getRegion('dateshort')
    tf = xbmc.getRegion('time').split(':')

    try:
        # time format is 12h with am/pm
        return df + ' ' + tf[0][0:2] + ':' + tf[1] + ' ' + tf[2].split()[1]
    except IndexError:
        # time format is 24h with or w/o leading zero
        return df + ' ' + tf[0][0:2] + ':' + tf[1]
Example #12
0
def getDateFormat():
    df = xbmc.getRegion('dateshort')
    tf = xbmc.getRegion('time').split(':')

    try:
        # time format is 12h with am/pm
        return df + ' ' + tf[0][0:2] + ':' + tf[1] + ' ' + tf[2].split()[1]
    except IndexError:
        # time format is 24h with or w/o leading zero
        return df + ' ' + tf[0][0:2] + ':' + tf[1]
Example #13
0
def to_local_time(utc_time):
    date_long = xbmc.getRegion("datelong")
    time_long = xbmc.getRegion("time")
    format_string = settings.get_localized_string(30035).format(
        date_long, time_long)

    utc_parsed = parser.parse(utc_time)
    local_time = utc_parsed.astimezone(tz.tzlocal())

    return local_time.strftime(format_string)
 def _get_local_date(self, datestr, long_date=False):
     '''returns the localized representation of the date provided by the api'''
     result = ""
     try:
         if long_date:
             result = arrow.get(datestr).strftime(xbmc.getRegion('datelong'))
         else:
             result = arrow.get(datestr).strftime(xbmc.getRegion('dateshort'))
     except Exception as exc:
         self._log_msg("Exception in _get_local_date: %s" % exc)
     return result
    def __init__(self, id_=''):
        """
        Class constructor
        """
        super(Addon, self).__init__(id_)

        self._reg_tempunit = py2_decode(xbmc.getRegion('tempunit'))
        self._reg_tempunit = py2_decode(xbmc.getRegion('tempunit'))
        self._reg_speedunit = xbmc.getRegion('speedunit')
        self._reg_dateshort = xbmc.getRegion('dateshort')
        self._reg_meridiem = xbmc.getRegion('meridiem')
Example #16
0
def Games(mode):
	GAMEURL = 'https://www.reddit.com/r/'+mode+'streams'
	today = datetime.utcnow() - timedelta(hours=8)
	today_from = str(today.strftime('%Y-%m-%d'))+'T00:00:00.000-05:00'
	today_to = str(today.strftime('%Y-%m-%d'))+'T23:59:00.000-05:00'
	js = GetJSON('http://www.sbnation.com/sbn_scoreboard/ajax_leagues_and_events?ranges['+mode+'][from]='+today_from+'&ranges['+mode+'][until]='+today_to)
	js = js['leagues'][mode]
	if js:	
		if mode == 'nfl':
			addDir('[COLOR=FF00FF00][B]NFL Redzone[/B][/COLOR]', GAMEURL, iconImg=logos[mode], home='redzone', away='redzone', mode="STREAMS")
		for game in js:
			home = game['away_team']['name']
			away = game['home_team']['name']
			hs = str(game['score']['home'][game['score']['cols'].index('Total')])
			if not hs:
				hs = '0'
			avs = str(game['score']['away'][game['score']['cols'].index('Total')])
			if not avs:
				avs = '0'
			score = ' - '+avs+':'+hs
			start_time = game['start_time']
			try:
				plus = False
				st = start_time.replace('T', ' ')
				if '+' in st:
					plus = True
					str_new = st.split('+')[-1]
					st = st.replace('+'+str_new,'')
				else:
					str_new = st.split('-')[-1]
					st = st.replace('-'+str_new,'')
				str_new = str_new.split(':')[0]
				if plus:
					st_time_utc = datetime(*(time.strptime(st, '%Y-%m-%d %H:%M:%S')[0:6]))-timedelta(hours=int(str_new))
				else:
					st_time_utc = datetime(*(time.strptime(st, '%Y-%m-%d %H:%M:%S')[0:6]))+timedelta(hours=int(str_new))
				local_game_time = utc_to_local(st_time_utc)
				local_time_str = ' - '+local_game_time.strftime(xbmc.getRegion('dateshort')+' '+xbmc.getRegion('time').replace('%H%H','%H').replace(':%S',''))
			except:
				local_time_str = ''
			status = GameStatus(game['status'])
			status = ' - '+status
			title = '[COLOR=FF00FF00][B]'+game['title'].replace(game['title'].split()[-1],'')+'[/B][/COLOR]'
			if display_start_time=='true':
				title = title+'[COLOR=FFFFFF00]'+local_time_str+'[/COLOR]'
			if display_status=='true':
				title = title+'[COLOR=FFFF0000]'+status+'[/COLOR]'
			if display_score=='true':
				title = title+'[COLOR=FF00FFFF]'+score+'[/COLOR]'
			addDir(title, GAMEURL, iconImg=logos[mode], home=home, away=away, mode="STREAMS")
	else:
		addDir("[COLOR=FFFF0000]Could not fetch today's "+mode.upper()+" games... Probably no games today?[/COLOR]", '', iconImg="", mode="")
	xbmcplugin.endOfDirectory(h, cacheToDisc=True)
 def getSettings(self):
     self.__showNoticeBeforeSw = True if __addon__.getSetting('showNoticeBeforeSw').upper() == 'TRUE' else False
     self.__dispMsgTime = int(re.match('\d+', __addon__.getSetting('dispTime')).group())*1000
     self.__discardTmr = int(re.match('\d+', __addon__.getSetting('discardOldTmr')).group())*60
     self.__confirmTmrAdded = True if __addon__.getSetting('confirmTmrAdded').upper() == 'TRUE' else False
     
     df = xbmc.getRegion('dateshort')
     tf = xbmc.getRegion('time').split(':')
     
     self.__dateFormat = df + ' ' + tf[0][0:2] + ':' + tf[1]
             
     notifyLog('settings (re)loaded')
     self.SettingsChanged = False
Example #18
0
def get_episode_to_air(v, name):
    i = v or {}
    infoproperties = {}
    infoproperties[u'{}'.format(name)] = format_date(i.get('air_date'), xbmc.getRegion('dateshort'))
    infoproperties[u'{}.long'.format(name)] = format_date(i.get('air_date'), xbmc.getRegion('datelong'))
    infoproperties[u'{}.day'.format(name)] = format_date(i.get('air_date'), "%A")
    infoproperties[u'{}.episode'.format(name)] = i.get('episode_number')
    infoproperties[u'{}.name'.format(name)] = i.get('name')
    infoproperties[u'{}.tmdb_id'.format(name)] = i.get('id')
    infoproperties[u'{}.plot'.format(name)] = i.get('overview')
    infoproperties[u'{}.season'.format(name)] = i.get('season_number')
    infoproperties[u'{}.rating'.format(name)] = u'{:0,.1f}'.format(try_float(i.get('vote_average')))
    infoproperties[u'{}.votes'.format(name)] = i.get('vote_count')
    infoproperties[u'{}.thumb'.format(name)] = get_imagepath_poster(i.get('still_path'))
    return infoproperties
Example #19
0
    def __init__(self, id_=''):
        """
        Class constructor
        """
        super(Weather, self).__init__(id_)
        self._url = 'plugin://{0}/'.format(self.id)
        self.actions = {}
        self._params = None

        self._window = xbmcgui.Window(12600)

        self._reg_tempunit = py2_decode(xbmc.getRegion('tempunit'))
        self._reg_speedunit = xbmc.getRegion('speedunit')
        self._reg_dateshort = xbmc.getRegion('dateshort')
        self._reg_meridiem = xbmc.getRegion('meridiem')
Example #20
0
def round_down_to_half_hour(xtime):
    """
    Returns a string with the time rounded down to the nearest half-hour in format h:mm am
    Example:
        now_time = time.localtime()
        r_time = round_down_to_half_hour(now_time)
        > 7:30 am
    @param xtime: the time to be converted in either string YYYYmmddHHMMSS format or a time.struct_time typed obj
    @type xtime: str
    @type xtime: time.struct_time
    @rtype: str
    """
    if type(xtime) is str:
        try:
            xxtime = time.strptime(xtime, '%Y%m%d%H%M%S')
        except:
            return None
    elif type(xtime) is time.struct_time:
        xxtime = xtime
    else:
        return None
    if xxtime.tm_min <= 30:
        newmin = ':00'
    else:
        newmin = ':30'
    xformat = xbmc.getRegion('time').replace(':%S', '').replace('%H%H', '%H')
    tmp = time.strftime(xformat, xxtime).lower()
    ret = re.sub(':..', newmin, tmp)
    return ret
Example #21
0
def getTimeFormat():
    """
    Get global time format.
    Kodi's time format handling is broken right now, as they return incompatible formats for strftime.
    %H%H is being returned for manually set zero-padded values, in case of a regional zero-padded hour component,
    only %H is returned.

    For now, sail around that by testing the current time for padded hour values.

    Tests of the values returned by xbmc.getRegion("time"):
    %I:%M:%S %p = h:mm:ss, non-zero-padded, 12h PM
    %I:%M:%S = 12h, h:mm:ss, non-zero-padded, regional
    %I%I:%M:%S = 12h, zero padded, hh:mm:ss
    %H%H:%M:%S = 24h, zero padded, hh:mm:ss
    %H:%M:%S = 24h, zero padded, regional, regional (central europe)

    :return: tuple of strftime-compatible format, boolean padHour
    """
    origFmt = xbmc.getRegion('time')
    fmt = origFmt.replace("%H%H", "%H").replace("%I%I", "%I")

    # Checking for %H%H or %I%I only would be the obvious way here to determine whether the hour should be padded,
    # but the formats returned for regional settings with padding only have %H in them. This seems like a Kodi bug.
    # Use a fallback.
    currentTime = unicode(xbmc.getInfoLabel('System.Time'), encoding="utf-8")
    padHour = "%H%H" in origFmt or "%I%I" in origFmt or (
        currentTime[0] == "0" and currentTime[1] != ":")
    return fmt, padHour
Example #22
0
    def format_time(self, time_obj):
        time_format = xbmc.getRegion('time')
        _time_obj = time_obj
        if isinstance(_time_obj, datetime.time):
            _time_obj = datetime.time(_time_obj.hour, _time_obj.minute, _time_obj.second)

        return _time_obj.strftime(time_format.replace("%H%H", "%H"))
Example #23
0
    def format_date_short(self, date_obj):
        date_format = xbmc.getRegion('dateshort')
        _date_obj = date_obj
        if isinstance(_date_obj, datetime.date):
            _date_obj = datetime.datetime(_date_obj.year, _date_obj.month, _date_obj.day)

        return _date_obj.strftime(date_format)
Example #24
0
    def getDate(self):
        
        format = xbmc.getRegion('dateshort')
        dialog = xbmcgui.Dialog()
        today = datetime.date.today()
        date = dialog.numeric(1, localString(31924)).replace(' ','0').replace('/','.')
        if date == today.strftime('%d.%m.%Y'): return
        datelow = (datetime.date.today() - datetime.timedelta(days=7))
        datehigh = (datetime.date.today() + datetime.timedelta(days=14))

        debug('date EPG '+ str(date))
        
        if time.strptime(date, '%d.%m.%Y') < time.strptime(str(datelow), '%Y-%m-%d'):
            xbmcgui.Dialog().notification(str(date), localString(31304), time=3000) 
            return
        if time.strptime(date, '%d.%m.%Y') > time.strptime(str(datehigh), '%Y-%m-%d'):
            xbmcgui.Dialog().notification(str(date), localString(31303), time=3000) 
            return
        date = time.strptime(date, '%d.%m.%Y')
        current = time.strptime(str(self.viewStartDate.strftime ('%Y-%m-%d')), '%Y-%m-%d')
        timedelta = datetime.timedelta(seconds=time.mktime(date) - time.mktime(current))
        if timedelta.seconds == 82800: 
            timedelta += datetime.timedelta(hours=1)
        debug('Timedelta '+str(timedelta))
        if date > current:
            self.viewStartDate += datetime.timedelta(days=int(str(timedelta)[:2]))
            self.onRedrawEPG(self.channelIdx, self.viewStartDate)
        elif date < current:
            delta = str(timedelta).replace('-','')[:2]
            self.viewStartDate -= datetime.timedelta(days=int(delta))
            self.onRedrawEPG(self.channelIdx, self.viewStartDate)
Example #25
0
 def formatTime(self, timestamp):
     if timestamp:
         format = xbmc.getRegion('time').replace(':%S',
                                                 '').replace('%H%H', '%H')
         return timestamp.strftime(format)
     else:
         return ''
Example #26
0
def convDateUtil(timestring, newfrmt='default', in_zone='UTC'):
    import xbmc
    try:
        import json
    except ImportError:
        import simplejson as json
    from dateutil.parser import parse
    from dateutil.tz import gettz
    try:
        locale_timezone = json.loads(
            xbmc.executeJSONRPC(
                '{"jsonrpc": "2.0", "method": "Settings.GetSettingValue", "params": {"setting": "locale.timezone"}, "id": 1}'
            ))
        local_tzinfo = gettz(locale_timezone['result']['value'])
        if local_tzinfo == None:
            raise ValueError()
    except ValueError:
        from dateutil.tz import tzlocal
        local_tzinfo = tzlocal()
    if newfrmt == 'default':
        newfrmt = xbmc.getRegion('time').replace(':%S', '')
    try:
        in_time = parse(timestring)
        in_time_with_timezone = in_time.replace(tzinfo=gettz(in_zone))
        local_time = in_time_with_timezone.astimezone(local_tzinfo)
        return local_time.strftime(newfrmt)
    except ValueError:
        traceback.print_exc(file=sys.stdout)
        return ''
Example #27
0
def getRegionalTimestamp(date_time, dateformat=['dateshort']):
    result = ''

    for aFormat in dateformat:
        result = result + ("%s " % date_time.strftime(xbmc.getRegion(aFormat)))

    return result.strip()
 def _get_local_time(self, timestr):
     '''returns the correct localized representation of the time provided by the api'''
     result = ""
     try:
         if timestr and ":" in timestr:
             timestr = timestr.replace(".", ":")
             if "H" in xbmc.getRegion('time'):
                 time_format = "HH:mm"
             else:
                 time_format = "h:mm A"
             if " AM" in timestr or " PM" in timestr:
                 result = arrow.get(timestr, 'h:mm A').format(time_format, locale=KODI_LANGUAGE)
             elif " am" in timestr or " pm" in timestr:
                 result = arrow.get(timestr, 'h:mm a').format(time_format, locale=KODI_LANGUAGE)
             elif "AM" in timestr or "PM" in timestr:
                 result = arrow.get(timestr, 'h:mmA').format(time_format, locale=KODI_LANGUAGE)
             elif "am" in timestr or "pm" in timestr:
                 result = arrow.get(timestr, 'h:mma').format(time_format, locale=KODI_LANGUAGE)
             elif len(timestr.split(":")[0]) == 1:
                 result = arrow.get(timestr, 'h:mm').format(time_format, locale=KODI_LANGUAGE)
             else:
                 result = arrow.get(timestr, 'HH:mm').format(time_format, locale=KODI_LANGUAGE)
     except Exception as exc:
         self._log_msg(str(exc), xbmc.LOGWARNING)
         return timestr
     return result
Example #29
0
 def formatDate(self, timestamp):
     if timestamp:
         format = xbmc.getRegion('datelong')
         date = timestamp.strftime(format)
         date = date.replace('Monday', local(11))
         date = date.replace('Tuesday', local(12))
         date = date.replace('Wednesday', local(13))
         date = date.replace('Thursday', local(14))
         date = date.replace('Friday', local(15))
         date = date.replace('Saturday', local(16))
         date = date.replace('Sunday', local(17))
         date = date.replace('January', local(21))
         date = date.replace('February', local(22))
         date = date.replace('March', local(23))
         date = date.replace('April', local(24))
         date = date.replace('May', local(25))
         date = date.replace('June', local(26))
         date = date.replace('July', local(27))
         date = date.replace('August', local(28))
         date = date.replace('September', local(29))
         date = date.replace('October', local(30))
         date = date.replace('November', local(31))
         date = date.replace('December', local(32))
         return date
     else:
         return ''
Example #30
0
def getTimeFormat():
    tf = xbmc.getRegion('time').split(':')
    try:
        return '%s:%s %s' % (tf[0][0:2], tf[1], tf[2].split()[1]
                             )  # time format is 12h with am/pm
    except IndexError:
        return '%s:%s' % (tf[0][0:2], tf[1]
                          )  # time format is 24h with or w/o leading zero
    def format_time(self, time_obj):
        time_format = xbmc.getRegion("time")
        _time_obj = time_obj
        if isinstance(_time_obj, datetime.time):
            _time_obj = datetime.time(_time_obj.hour, _time_obj.minute, _time_obj.second)
            pass

        return _time_obj.strftime(time_format)
Example #32
0
    def _fetch_changelog(self, view, msg):
        def _pysvn_cancel_callback():
            # check if user cancelled operation
            return False
        # import required modules
        import datetime
        import pysvn
        # get our regions format
        date_format = "{date} {time}".format(date=xbmc.getRegion("datelong"), time=xbmc.getRegion("time"))
        # get client
        client = pysvn.Client()
        client.callback_cancel = _pysvn_cancel_callback
        try:
            # grab current revision and repo URL
            info = client.info(path=self.m_addon.getAddonInfo("Path"))
            # fetch changelog for current revision
            if (view == "changelog"):
                log = client.log(url_or_path=info["url"], limit=25, revision_start=pysvn.Revision(pysvn.opt_revision_kind.number, info["commit_revision"].number))
            # updates
            else:
                log = client.log(url_or_path=info["url"], limit=25, revision_end=pysvn.Revision(pysvn.opt_revision_kind.number, info["commit_revision"].number + 1))
        except:
            # changelog
            log = client.log(url_or_path=u"{repo}{branch}{id}".format(repo=self.m_addon.getSetting("Repo"), branch=self.m_addon.getSetting("Branch"), id=self.m_addon.getAddonInfo("Id"),), limit=25)
        # if no entries set user message
        if (len(log)):
            # initialize our log text
            changelog = "{0:-<150}\n".format("")
        else:
            # should only happen for "updates" and there are none
            changelog = self.m_addon.getLocalizedString(30701)
        # we need to compile so we can add flags
        clean_entry = re.compile("\[.+?\][\s]+(?P<name>[^\[]+)(?:\[.+)?", re.DOTALL)
        version = re.compile("(Version.+)", re.IGNORECASE)
        # iterate thru and format each message
        for entry in log:
            # add version
            changelog += u"{version}\n".format(version=version.search(entry["message"]).group(1))
            # add heading
            changelog += u"r{revision} - {date} - {author}\n".format(revision=entry["revision"].number, date=datetime.datetime.fromtimestamp(entry["date"]).strftime(date_format), author=entry["author"])
            # add formatted message
            changelog += "\n".join([re.sub("(?P<name>^[a-zA-Z])", "- \\1", line.lstrip(" -")) for line in entry["message"].strip().splitlines() if (not line.startswith("["))])
            # add separator
            changelog += "\n{0:-<150}\n".format("")

        return self._colorize_text(changelog)
 def __init__( self, xmlSource, settings, MediaWindow ):
     self.success = True
     self.settings = settings
     self.MediaWindow = MediaWindow
     # get our regions format
     self.date_format = xbmc.getRegion( "datelong" ).replace( "DDDD,", "" ).replace( "MMMM", "%B" ).replace( "D", "%d" ).replace( "YYYY", "%Y" ).strip()
     # get the list
     self.success = self._get_current_videos( xmlSource )
Example #34
0
def LIST_STREAMS():
    live_streams = []
    upcoming_streams = []
    url = 'http://api.new.livestream.com/curated_events?page=1&maxItems=500'
    req = urllib2.Request(url)
    req.add_header('User-Agent', IPHONE_UA)              
    response = urllib2.urlopen(req)      
    json_source = json.load(response)
    response.close()

    for event in json_source['data']:            
        event_id = str(event['id'])
        owner_id = str(event['owner_account_id'])

        owner_name = name = event['owner']['full_name'].encode('utf-8')
        full_name = event['full_name'].encode('utf-8')
        name = owner_name + ' - ' + full_name
        icon = event['logo']['url']

        #2013-03-26T14:28:00.000Z
        pattern = "%Y-%m-%dT%H:%M:%S.000Z"
        start_time = str(event['start_time'])
        end_time =  str(event['end_time'])
        current_time =  datetime.utcnow().strftime(pattern) 
        my_time = int(time.mktime(time.strptime(current_time, pattern)))             
        event_end = int(time.mktime(time.strptime(end_time, pattern)))

        length = 0
        try:
            length = int(item['duration'])
        except:        
            pass

        print start_time         
        aired = start_time[0:4]+'-'+start_time[5:7]+'-'+start_time[8:10]
        print aired

        info = {'plot':'','tvshowtitle':'Livestream','title':name,'originaltitle':name,'duration':length,'aired':aired}
        
        if event['in_progress']:
            name = '[COLOR=FF00B7EB]'+name+'[/COLOR]'
            live_streams.append([name,icon,event_id,owner_id,info])
        else:

            if my_time < event_end:                
                start_date = datetime.fromtimestamp(time.mktime(time.strptime(start_time, pattern)))    
                start_date = datetime.strftime(utc_to_local(start_date),xbmc.getRegion('dateshort')+' '+xbmc.getRegion('time').replace('%H%H','%H').replace(':%S',''))
                info['plot'] = "Starting at: "+str(start_date)
                #name = name + ' ' + start_date
                upcoming_streams.append([name,icon,event_id,owner_id,info])

    
    for stream in  sorted(live_streams, key=lambda tup: tup[0]):        
        addDir(stream[0],'/live_now',101,stream[1],FANART,stream[2],stream[3],stream[4])            


    for stream in  sorted(upcoming_streams, key=lambda tup: tup[0]):
        addDir(stream[0],'/live_now',101,stream[1],FANART,stream[2],stream[3],stream[4])            
 def _fetch_changelog( self, kind ):
     # import required modules
     import datetime
     import pysvn
     # get our regions format and correct path
     if ( DEBUG ):
         date_format = "%x %X"
         path = os.path.dirname( os.path.dirname( os.getcwd() ) )
     else:
         date_format = xbmc.getRegion( "datelong" ).replace( "DDDD,", "%a," ).replace( "MMMM", "%B" ).replace( "D", "%d" ).replace( "YYYY", "%Y" ).strip()
         date_format = "%s %s" % ( date_format, xbmc.getRegion( "time" ).replace( "xx", "%p" ).replace( "H", "%H" ).replace( "h", "%I" ).replace( "mm", "%M" ).replace( "ss", "%S" ), )
         path = os.getcwd()
     # get client
     client = pysvn.Client()
     client.callback_cancel = self._pysvn_cancel_callback
     # grab current revision and repo url
     info = client.info( path=path )
     # fetch log for current revision
     if ( kind == "changelog" ):
         # changelog
         log = client.log( url_or_path=info[ "url" ], limit=25, revision_start=pysvn.Revision( pysvn.opt_revision_kind.number, info[ "commit_revision" ].number ) )
     else:
         # updates
         log = client.log( url_or_path=info[ "url" ], limit=25, revision_end=pysvn.Revision( pysvn.opt_revision_kind.number, info[ "commit_revision" ].number + 1 ) )
     # if no entries set user message
     if ( len( log ) ):
         # initialize our log variable
         changelog = "%s\n" % ( "-" * 150, )
     else:
         if ( DEBUG ):
             changelog = "Your version is up to date."
         else:
             changelog = Addon.getLocalizedString( 30704 )
     # we need to compile so we can add DOTALL
     clean_entry = self.re.compile( "\[.+?\][\s]+(?P<name>[^\[]+)(?:\[.+)?", self.re.DOTALL )
     # iterate thru and format each message
     for entry in log:
         # add heading
         changelog += "r%d - %s - %s\n\n" % ( entry[ "revision" ].number, datetime.datetime.fromtimestamp( entry[ "date" ] ).strftime( date_format ), entry[ "author" ], )
         # add formatted message  "\[.+?\][\s]+(?P<name>[^\[]+)", "\\1"
         changelog += "\n".join( [ self.re.sub( "(?P<name>^[a-zA-Z])", "- \\1", line.lstrip( " -" ) ) for line in clean_entry.sub( "\\1", entry[ "message" ] ).strip().splitlines() ] )
         # add separator
         changelog += "\n%s\n" % ( "-" * 150, )
     # return colorized result
     return self._colorize_text( changelog )
Example #36
0
 def __init__(self):
     self.base_url = "http://www.google.com"
     try:
         self.date_format = xbmc.getRegion("datelong").replace(
             "DDDD",
             "%A").replace("MMMM",
                           "%B").replace("D", "%d").replace("YYYY", "%Y")
     except:
         self.date_format = "%A, %B %d, %Y"
Example #37
0
def get_stream_start_date_formatted(start_date):

    if start_date is None:
        common.plugin.log_error('utils.is_live_media() : missing start_date')
        return None

    now_datetime = now()
    start_date = dateutil.parser.parse(start_date)

    formatted_date = start_date.strftime(xbmc.getRegion('dateshort'))
    formatted_time = start_date.strftime(xbmc.getRegion('time'))

    if now_datetime.date() != start_date.date():
        formatted_datetime = formatted_date + " - " + formatted_time
    else:
        formatted_datetime = formatted_time

    return formatted_datetime
 def _get_settings(self):
     # get the users preferences
     self.settings = {
         "showtimes_location": self.Addon.getSetting("showtimes_location"),
         "showtimes_scraper": self.Addon.getSetting("showtimes_scraper"),
         "showtimes_scraper_day": self.Addon.getSetting("showtimes_scraper_day"),
         "showtimes_scraper_fallback_list_type": ["theater", "movie"][int(self.Addon.getSetting("showtimes_scraper_fallback_list_type"))],
         "date_format": xbmc.getRegion("datelong")
     }
Example #39
0
def date_format(value, date='short'):
    try:
        date_time = arrow.get(value)
        value = date_time.strftime(xbmc.getRegion('date%s' % date))

    except Exception:
        pass

    return value
Example #40
0
def convDateUtil(timestring, newfrmt='default', in_zone='UTC'):
    if newfrmt == 'default':
        newfrmt = xbmc.getRegion('time').replace(':%S', '')
    try:
        in_time = parse(timestring)
        in_time_with_timezone = in_time.replace(tzinfo=gettz(in_zone))
        local_time = in_time_with_timezone.astimezone(local_tzinfo)
        return local_time.strftime(newfrmt)
    except:
        return timestring
Example #41
0
 def __init__( self, xmlSource, mpaa, genre, settings, watched ):
     self.mpaa = mpaa
     self.genre = genre.replace( "Sci-Fi", "Science Fiction" ).replace( "Action", "Action and ADV" ).replace( "Adventure", "ACT and Adventure" ).replace( "ACT",  "Action" ).replace( "ADV",  "Adventure" ).split( " / " )
     self.settings = settings
     self.watched = watched
     self.trailers = []
     # get our regions format
     self.date_format = xbmc.getRegion( "datelong" ).replace( "DDDD,", "" ).replace( "MMMM", "%B" ).replace( "D", "%d" ).replace( "YYYY", "%Y" ).strip()
     # get the list
     self._parse_source( xmlSource )
Example #42
0
def utc_to_local(value):
    conv_date = arrow.get(value).to(TIMEZONE)
    conv_date_str = conv_date.strftime('%Y-%m-%d')

    if xbmc.getRegion('time').startswith('%I'):
        conv_time_str = conv_date.strftime('%I:%M %p')
    else:
        conv_time_str = conv_date.strftime('%H:%M')

    return conv_date_str, conv_time_str
 def __init__( self, xmlSource, mpaa, genre, settings, watched ):
     self.mpaa = mpaa
     self.genre = genre.replace( "Sci-Fi", "Science Fiction" ).replace( "Action", "Action and ADV" ).replace( "Adventure", "ACT and Adventure" ).replace( "ACT",  "Action" ).replace( "ADV",  "Adventure" ).split( " / " )
     self.settings = settings
     self.watched = watched
     self.trailers = []
     # get our regions format
     self.date_format = xbmc.getRegion( "datelong" ).replace( "DDDD,", "" ).replace( "MMMM", "%B" ).replace( "D", "%d" ).replace( "YYYY", "%Y" ).strip()
     # get the list
     self._parse_source( xmlSource )
 def _fetch_text_file( self, kind ):
     # set path, first try translated version
     _path = os.path.join( Addon.getAddonInfo( "Path" ), "%s-%s.txt" % ( kind, xbmc.getRegion( "locale" ), ) )
     # if doesn't exist, use default
     if ( not os.path.isfile( _path ) ):
         _path = os.path.join( Addon.getAddonInfo( "Path" ), "%s.txt" % ( kind, ) )
     # read  file
     text = open( _path, "r" ).read()
     # return colorized result
     return text##self._colorize_text( text )
Example #45
0
 def _showShotDate(self, date_tupel):
     if date_tupel:
         y, m, d = date_tupel
         date = datetime.date(y, m, d)
         date_format = xbmc.getRegion('dateshort')
         date_string = date.strftime(date_format)
     else:
         date_string = self.getString(self.SID_NOT_RELEASED)
     self.label_shot_date.setLabel(self.getString(self.SID_SHOT_DATE)
                                   % date_string)
def parsetime(txt):
    merid = xbmc.getRegion('meridiem')
    h, m = getNumbers(txt)
    if merid.__len__() > 2:
        AM, PM = merid.split('/')
        if txt.endswith(AM) and h == 12:
            h = 0
        elif txt.endswith(PM) and h < 12:
            h += 12
    return '%02d:%02d' % (h, m)
Example #47
0
 def _showShotDate(self, date_tupel):
     if date_tupel:
         y, m, d = date_tupel
         date = datetime.date(y, m, d)
         date_format = xbmc.getRegion('dateshort')
         date_string = date.strftime(date_format)
     else:
         date_string = self.getString(self.SID_NOT_RELEASED)
     self.label_shot_date.setLabel(self.getString(self.SID_SHOT_DATE)
                                   % date_string)
Example #48
0
def convDateUtil(timestring, newfrmt='default', in_zone='UTC'):
    if newfrmt == 'default':
        newfrmt = xbmc.getRegion('time').replace(':%S','')
    try:
        in_time = parse(timestring)
        in_time_with_timezone = in_time.replace(tzinfo=gettz(in_zone))
        local_time = in_time_with_timezone.astimezone(local_tzinfo)
        return local_time.strftime(newfrmt)
    except:
        return timestring
 def __init__( self, xmlSource, settings ):
     self.success = True
     self.settings = settings
     # get our regions format
     try:
         self.date_format = xbmc.getRegion( "datelong" ).replace( "DDDD,", "" ).replace( "MMMM", "%B" ).replace( "D", "%d" ).replace( "YYYY", "%Y" ).strip()
     except:
         self.date_format = "%B %d, %Y"
     # get the list
     self.success = self._get_current_videos( xmlSource )
Example #50
0
def get_user_date_format( str_date, format="datelong" ):
    try:
        y, m, d = str_date.split( "-" )
        str_date = datetime.date( int( y ), int( m ), int( d ) )
        if format: #datelong, dateshort
            return str_date.strftime( xbmc.getRegion( format ) )
    except ValueError:
        pass
    except:
        print_exc()
    return str_date
Example #51
0
	def game_title(self, game):
		# Get the team names.
		home_team = game['home_team']
		away_team = game['away_team']
		if self.team_info_key is not None:
			if home_team in self.team_info:
				home_team = self.team_info[home_team][self.team_info_key]
			if away_team in self.team_info:
				away_team = self.team_info[away_team][self.team_info_key]

		# Get the score for the game.
		home_team_score, away_team_score = game['home_goals'], game['away_goals']

		# Get the required dates and times.
		current_time_utc = datetime.utcnow().replace(tzinfo=tz.tzutc())
		if game['start_time'] is not None:
			start_time_local = game['start_time'].astimezone(tz.tzlocal()).strftime(game_time_format)
		else:
			start_time_local = game['date'].strftime(xbmc.getRegion('dateshort'))

		# Start with the basic title of "Team vs Team".
		lang_id = 30027
		if self.at_instead_of_vs == True:
			home_team, away_team = away_team, home_team
			home_team_score, away_team_score = away_team_score, home_team_score
			lang_id = 30028
		title = home_team + __language__(lang_id) + away_team

		# Handle game status flags.
		status_flags = ''
		if game['blocked']:
			status_flags = __language__(30022)
		else:
			if game['live']:
				status_flags = __language__(30023)
			elif game['ended']:
				time_delta = current_time_utc - game['start_time']
				# Any game that has ended and started within the last 12 hours
				# get flagged as having recently ended.
				if time_delta.seconds + (time_delta.days * 86400) < 43200:
					status_flags = __language__(30024)

		# Handle showing the game score.
		game_score = ''
		if self.show_scores and (game['live'] or game['ended']) and home_team_score is not None and away_team_score is not None:
			game_score = '(%s-%s)' % (home_team_score, away_team_score)

		# Prepend the game start time.
		return (
			title,
			start_time_local,
			status_flags,
			game_score,
		)
Example #52
0
def getLang():
    lang = ""
    try:
        lang = xbmc.getRegion( "locale" )# supported on xbox, but not supported with XBMC mainline
        if not lang:
            langinfo = xbmc.translatePath( "special://xbmc/language/%s/langinfo.xml" % xbmc.getLanguage() )
            lang = re.search( '<menu>(.+?)</menu>', open( langinfo ).read() ).group( 1 )
    except Exception, e:
        #NameError: global name 'xbmc' is not defined
        if "'xbmc'" not in str( e ):
            print_exc()
 def _fetch_changelog( self, kind ):
     # import required modules
     import datetime
     import pysvn
     # get our regions format
     date_format = "%s %s" % ( xbmc.getRegion( "datelong" ), xbmc.getRegion( "time" ), )
     # get client
     client = pysvn.Client()
     client.callback_cancel = self._pysvn_cancel_callback
     try:
         # grab current revision and repo url
         info = client.info( path=Addon.getAddonInfo( "Path" ) )
         # fetch changelog for current revision
         if ( kind == "changelog" ):
             log = client.log( url_or_path=info[ "url" ], limit=25, revision_start=pysvn.Revision( pysvn.opt_revision_kind.number, info[ "commit_revision" ].number ) )
         # updates
         else:
             log = client.log( url_or_path=info[ "url" ], limit=25, revision_end=pysvn.Revision( pysvn.opt_revision_kind.number, info[ "commit_revision" ].number + 1 ) )
     except:
         # changelog
         log = client.log( url_or_path="http://xbmc-addons.googlecode.com/svn/addons/%s" % ( Addon.getAddonInfo( "Id" ), ), limit=25 )
     # if no entries set user message
     if ( len( log ) ):
         # initialize our log variable
         changelog = "%s\n" % ( "-" * 150, )
     else:
         # should only happen for "updates" and there are none
         changelog = Addon.getLocalizedString( 30704 )
     # we need to compile so we can add DOTALL
     clean_entry = self.re.compile( "\[.+?\][\s]+(?P<name>[^\[]+)(?:\[.+)?", self.re.DOTALL )
     # iterate thru and format each message
     for entry in log:
         # add heading
         changelog += "r%d - %s - %s\n\n" % ( entry[ "revision" ].number, datetime.datetime.fromtimestamp( entry[ "date" ] ).strftime( date_format ), entry[ "author" ], )
         # add formatted message
         changelog += "\n".join( [ self.re.sub( "(?P<name>^[a-zA-Z])", "- \\1", line.lstrip( " -" ) ) for line in clean_entry.sub( "\\1", entry[ "message" ] ).strip().splitlines() ] )
         # add separator
         changelog += "\n%s\n" % ( "-" * 150, )
     # return colorized result
     return self._colorize_text( changelog )
def format_date(date, pretty=True, short=True, reverse=False, modified=False, hours=0):
    try:  #FIXME: clean this up, too many hacks
        # set proper format
        #print [date, xbmc.getRegion("time")]
        format_ = [
            [["%Y-%m-%d %H:%M:%S", "%Y-%m-%d"][short], [xbmc.getRegion("dateshort"), xbmc.getRegion("datelong")][pretty]],
            ["%Y-%m-%d %H:%M:%S", "%a, %d %b %Y %H:%M:%S GMT"]
        ][modified]
        # reverse for saving in NFO and DB
        if (reverse):
            format_.reverse()
        # format as date/time
        if (modified):
            dt = datetime.datetime(*time.strptime(date, format_[0])[ : 6]) + datetime.timedelta(hours=hours)
        # format as date
        else:
            dt = datetime.date(*time.strptime(date, format_[0])[ : 3])
        # return result
        return dt.strftime(format_[1])
    except:
        # something is wrong, return original
        return date
 def __init__( self, path, mpaa, genre, settings, scraper ):
     self.mpaa = self.mpaa_ratings.index(mpaa)
     self.genre = genre.replace( "Sci-Fi", "Science Fiction" ).replace( "Action", "Action and ADV" ).replace( "Adventure", "ACT and Adventure" ).replace( "ACT", "Action" ).replace( "ADV", "Adventure" ).split( " / " )
     self.settings = settings
     self.trailers = []
     # get our regions format
     self.date_format = xbmc.getRegion( "datelong" ).replace( "DDDD,", "" ).replace( "MMMM", "%B" ).replace( "D", "%d" ).replace( "YYYY", "%Y" ).strip()
     # override the requested mpaa rating per user preference
     if not self.settings[ 'trailer_limit_mpaa' ]:
         self.mpaa = len( self.mpaa_ratings )
     if self.settings[ 'trailer_rating' ] != '--':
         self.mpaa = self.mpaa_ratings.index( self.settings[ 'trailer_rating' ] )
     # get the list
     self._parse_source( path, scraper )
 def _get_client( self ):
     # do we want to translate?
     self.settings = { "translate": [ "en", xbmc.getRegion( "locale" ) ][ self.Addon.getSetting( "translate" ) == "true" ] }
     # get area code
     if ( self.index is None ):
         self.areacode = xbmc.getInfoLabel( "Window(Weather).Property(Location.Index)" )
     else:
         self.areacode = self.index
     # set if new location
     self.new_location = ( xbmc.getInfoLabel( "Window(Weather).Property(Weather.AreaCode)" ) != self.areacode )
     # if new location, set it
     if ( self.new_location ):
         self.WINDOW.setProperty( "Weather.AreaCode", self.areacode )
     # setup our weather client
     self.WeatherClient = WeatherClient( self.location_id, self.Addon )