def geoip(self):
retry = 0
query = ''
while (retry < 6) and (not xbmc.abortRequested):
query = self.call('geolookup', 'lang:EN', 'autoip', self.FORMAT)
if query != '':
retry = 6
else:
retry += 1
xbmc.sleep(10000)
commons.debug('GeoIP download failed')
commons.debug('GeoIP data: %s' % query)
data = self._parse(query)
if data is not None and data.has_key('location'):
location = data['location']['city']
locationid = data['location']['l'][3:]
xbmcaddon.Addon().setSetting('Location1', location)
xbmcaddon.Addon().setSetting('Location1id', locationid)
commons.debug('Detected GeoIP location: %s' % location)
else:
location = ''
locationid = ''
return location, locationid
python类abortRequested()的实例源码
def forecast(self, loc, locid):
try:
lang = LANG[self.LANG]
except:
lang = 'EN'
opt = 'lang:' + lang
commons.debug('Weather location: %s' % locid)
retry = 0
query = ''
while (retry < 6) and (not xbmc.abortRequested):
query = self.call(self.WEATHER_FEATURES, opt, locid, self.FORMAT)
if query != '':
retry = 6
else:
retry += 1
xbmc.sleep(10000)
commons.debug('Weather download failed')
commons.trace('Forecast data: %s' % query)
data = self._parse(query)
if data is not None and data.has_key('response') and not data['response'].has_key('error'):
self.properties(data, loc, locid)
else:
self.clear()
def _player(self):
try:
if not xbmc.abortRequested and sctop.player.isPlayingVideo() and sctop.player.scid > 0:
notificationtime = 30
playTime = sctop.player.getTime()
totalTime = sctop.player.getTotalTime()
sctop.player.watchedTime = playTime
self.timer += 1
if self.timer >= 600:
sctop.player.waitForChange()
self.timer = 0
data = {'scid': sctop.player.scid, 'action': 'ping', 'prog': sctop.player.timeRatio()}
sctop.player.action(data)
util.debug("[SC] upNext [%s] " % str((totalTime - playTime) <= int(notificationtime)))
showupnext = sctop.getSettingAsBool("show_up_next")
if showupnext and (totalTime - playTime) <= int(notificationtime):
sctop.player.upNext()
except Exception, e:
bug.onExceptionRaised(e)
util.debug("[SC] _player e: %s" % str(e))
pass
def get_album_json_thread(self):
try:
while not xbmc.abortRequested and not self.abortAlbumThreads:
try:
album_id = self.albumQueue.get_nowait()
except:
break
try:
self.get_album(album_id, withCache=False)
except requests.HTTPError as e:
r = e.response
msg = _T(30505)
try:
msg = r.reason
msg = r.json().get('userMessage')
except:
pass
log('Error getting Album ID %s' % album_id, xbmc.LOGERROR)
if r.status_code == 429 and not self.abortAlbumThreads:
self.abortAlbumThreads = True
log('Too many requests. Aborting Workers ...', xbmc.LOGERROR)
self.albumQueue._init(9999)
xbmcgui.Dialog().notification(plugin.name, msg, xbmcgui.NOTIFICATION_ERROR)
except Exception, e:
traceback.print_exc()
def onSourceProgressUpdate(self, percentageComplete):
control = self.getControl(self.C_MAIN_LOADING_PROGRESS)
if percentageComplete < 1:
if control:
control.setPercent(1)
self.progressStartTime = datetime.datetime.now()
self.progressPreviousPercentage = percentageComplete
elif percentageComplete != self.progressPreviousPercentage:
if control:
control.setPercent(percentageComplete)
self.progressPreviousPercentage = percentageComplete
delta = datetime.datetime.now() - self.progressStartTime
if percentageComplete < 20:
self.setControlLabel(self.C_MAIN_LOADING_TIME_LEFT, strings(CALCULATING_REMAINING_TIME))
else:
secondsLeft = int(delta.seconds) / float(percentageComplete) * (100.0 - percentageComplete)
if secondsLeft > 30:
secondsLeft -= secondsLeft % 10
self.setControlLabel(self.C_MAIN_LOADING_TIME_LEFT, strings(TIME_LEFT) % secondsLeft)
return not xbmc.abortRequested and not self.isClosing
def updateTimebar(self, scheduleTimer=True):
# move timebar to current time
timeDelta = datetime.datetime.today() - self.viewStartDate
control = self.getControl(self.C_MAIN_TIMEBAR)
if control:
(x, y) = control.getPosition()
try:
# Sometimes raises:
# exceptions.RuntimeError: Unknown exception thrown from the call "setVisible"
self.setControlVisible(self.C_MAIN_TIMEBAR,timeDelta.days == 0)
control.setPosition(self._secondsToXposition(timeDelta.seconds), y)
self.timebar.setPosition(self._secondsToXposition(timeDelta.seconds), y)
except:
pass
if scheduleTimer and not xbmc.abortRequested and not self.isClosing:
threading.Timer(1, self.updateTimebar).start()
def updateQuickTimebar(self, scheduleTimer=True):
# move timebar to current time
timeDelta = datetime.datetime.today() - self.quickViewStartDate
control = self.getControl(self.C_QUICK_EPG_TIMEBAR)
if control:
(x, y) = control.getPosition()
try:
# Sometimes raises:
# exceptions.RuntimeError: Unknown exception thrown from the call "setVisible"
self.setControlVisible(self.C_QUICK_EPG_TIMEBAR,timeDelta.days == 0)
except:
pass
control.setPosition(self._secondsToXposition(timeDelta.seconds), y)
self.quicktimebar.setPosition(self._secondsToXposition(timeDelta.seconds), self.quickEpgView.top) #TODO use marker
if scheduleTimer and not xbmc.abortRequested and not self.isClosing:
threading.Timer(1, self.updateQuickTimebar).start()
def range(self, url):
control.idle()
yes = control.yesnoDialog(control.lang(32555).encode('utf-8'), '', '')
if not yes: return
if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'):
control.infoDialog(control.lang(32552).encode('utf-8'), time=10000000)
self.infoDialog = True
from resources.lib.indexers import movies
items = movies.movies().get(url, idx=False)
if items == None: items = []
for i in items:
try:
if xbmc.abortRequested == True: return sys.exit()
self.add('%s (%s)' % (i['title'], i['year']), i['title'], i['year'], i['imdb'], i['tmdb'], range=True)
except:
pass
if self.infoDialog == True:
control.infoDialog(control.lang(32554).encode('utf-8'), time=1)
if self.library_setting == 'true' and not control.condVisibility('Library.IsScanningVideo'):
control.execute('UpdateLibrary(video)')
def range(self, url):
control.idle()
yes = control.yesnoDialog(control.lang(32555).encode('utf-8'), '', '')
if not yes: return
if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'):
control.infoDialog(control.lang(32552).encode('utf-8'), time=10000000)
self.infoDialog = True
from resources.lib.indexers import tvshows
items = tvshows.tvshows().get(url, idx=False)
if items == None: items = []
for i in items:
try:
if xbmc.abortRequested == True: return sys.exit()
self.add(i['title'], i['year'], i['imdb'], i['tvdb'], range=True)
except:
pass
if self.infoDialog == True:
control.infoDialog(control.lang(32554).encode('utf-8'), time=1)
if self.library_setting == 'true' and not control.condVisibility('Library.IsScanningVideo'):
control.execute('UpdateLibrary(video)')
def updateWindow(name, gui):
time.sleep(0.5)
track_old = {'item': '', 'is_playing': False, 'shuffle_state': 'off'}
while windowopen and (not xbmc.abortRequested):
track = sp.get_player()
if track['item'] != track_old['item'] or track['is_playing'] != track_old['is_playing'] or track['shuffle_state'] != track_old['shuffle_state'] or track['repeat_state'] != track_old['repeat_state']:
# insert update functions here
gui.onUpdate(track)
track_old = track
gui.setProgress(track['progress_ms'], track['item']['duration_ms'])
time.sleep(1)
# Define the GUI
def range(self, url):
control.idle()
yes = control.yesnoDialog(control.lang(32555).encode('utf-8'), '', '')
if not yes: return
if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'):
control.infoDialog(control.lang(32552).encode('utf-8'), time=10000000)
self.infoDialog = True
from resources.lib.indexers import movies
items = movies.movies().get(url, idx=False)
if items == None: items = []
for i in items:
try:
if xbmc.abortRequested == True: return sys.exit()
self.add('%s (%s)' % (i['title'], i['year']), i['title'], i['year'], i['imdb'], i['tmdb'], range=True)
except:
pass
if self.infoDialog == True:
control.infoDialog(control.lang(32554).encode('utf-8'), time=1)
if self.library_setting == 'true' and not control.condVisibility('Library.IsScanningVideo'):
control.execute('UpdateLibrary(video)')
def range(self, url):
control.idle()
yes = control.yesnoDialog(control.lang(32555).encode('utf-8'), '', '')
if not yes: return
if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'):
control.infoDialog(control.lang(32552).encode('utf-8'), time=10000000)
self.infoDialog = True
from resources.lib.indexers import tvshows
items = tvshows.tvshows().get(url, idx=False)
if items == None: items = []
for i in items:
try:
if xbmc.abortRequested == True: return sys.exit()
self.add(i['title'], i['year'], i['imdb'], i['tvdb'], range=True)
except:
pass
if self.infoDialog == True:
control.infoDialog(control.lang(32554).encode('utf-8'), time=1)
if self.library_setting == 'true' and not control.condVisibility('Library.IsScanningVideo'):
control.execute('UpdateLibrary(video)')
def wait_if_xbmc_not_closing(espera):
logger.info("tvalacarta.service_subscription.wait_if_xbmc_not_closing "+repr(espera))
while not xbmc.abortRequested and espera > 0:
#logger.info("tvalacarta.service_subscription xbmc.abortRequested="+repr(xbmc.abortRequested)+" espera="+repr(espera))
# Cada segundo se comprueba si XBMC esta cerrándose, hasta que ha pasado el tiempo
xbmc.sleep(1000)
espera = espera - 1
if espera==0:
logger.info("tvalacarta.service_subscription Wait finished")
def range(self, url):
control.idle()
yes = control.yesnoDialog(control.lang(32555).encode('utf-8'), '', '')
if not yes: return
if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'):
control.infoDialog(control.lang(32552).encode('utf-8'), time=10000000)
self.infoDialog = True
from resources.lib.indexers import movies
items = movies.movies().get(url, idx=False)
if items == None: items = []
for i in items:
try:
if xbmc.abortRequested == True: return sys.exit()
self.add('%s (%s)' % (i['title'], i['year']), i['title'], i['year'], i['imdb'], i['tmdb'], range=True)
except:
pass
if self.infoDialog == True:
control.infoDialog(control.lang(32554).encode('utf-8'), time=1)
if self.library_setting == 'true' and not control.condVisibility('Library.IsScanningVideo'):
control.execute('UpdateLibrary(video)')
def range(self, url):
control.idle()
yes = control.yesnoDialog(control.lang(32555).encode('utf-8'), '', '')
if not yes: return
if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'):
control.infoDialog(control.lang(32552).encode('utf-8'), time=10000000)
self.infoDialog = True
from resources.lib.indexers import tvshows
items = tvshows.tvshows().get(url, idx=False)
if items == None: items = []
for i in items:
try:
if xbmc.abortRequested == True: return sys.exit()
self.add(i['title'], i['year'], i['imdb'], i['tvdb'], range=True)
except:
pass
if self.infoDialog == True:
control.infoDialog(control.lang(32554).encode('utf-8'), time=1)
if self.library_setting == 'true' and not control.condVisibility('Library.IsScanningVideo'):
control.execute('UpdateLibrary(video)')
def service(self):
util.info("SC Service Started")
#dialog = sctop.dialog.textviewer('heading', 'Prosim podporte vyvoj pluginu na adrese: http://stream-cinema.online/')
if sctop.player is None:
sctop.player = myPlayer.MyPlayer(parent=self)
try:
sleep_time = int(self.getSetting("start_sleep_time")) * 1000 * 60
except:
sleep_time = self.sleep_time
pass
util.debug("[SC] start delay: %s" % str(sleep_time))
start = 0
while not xbmc.abortRequested and start < sleep_time:
self._player()
start += 1000
sctop.sleep(1000)
del start
util.debug("[SC] start sleep end")
try:
self.last_run = float(self.cache.get("subscription.last_run"))
except:
self.last_run = time.time()
self.cache.set("subscription.last_run", str(self.last_run))
pass
util.debug("[SC] last_rum: %s" % str(self.last_run))
if not xbmc.abortRequested and time.time() > self.last_run:
self.evalSchedules()
self.sleep_time = 1000
while not xbmc.abortRequested:
self._player()
self._sheduler()
sctop.sleep(self.sleep_time)
del sctop.player
util.info("[SC] Shutdown")
def waitForChange(self):
scutils.KODISCLib.sleep(200)
while True:
if xbmc.abortRequested or not self.isPlayingVideo():
return
pom = xbmc.getInfoLabel('Player.FinishTime(hh:mm:ss)')
if pom != self.estimateFinishTime:
self.estimateFinishTime = pom
break
scutils.KODISCLib.sleep(100)
def sleep(sleep_time):
while not xbmc.abortRequested and sleep_time > 0:
sleep_time -= 100
xbmc.sleep(99)
def save_album_cache(self):
numAlbums = 0
if self._config.cache_albums:
album_ids = self.albumJsonBuffer.keys()
for album_id in album_ids:
if xbmc.abortRequested:
break
json_obj = self.albumJsonBuffer.get(album_id, None)
if json_obj != None and 'id' in json_obj and not json_obj.get('_cached', False):
numAlbums += 1
self.metaCache.insertAlbumJson(json_obj)
if numAlbums > 0:
log('Wrote %s from %s Albums into the MetaCache' % (numAlbums, len(album_ids)))
return numAlbums
def range(self, url):
control.idle()
yes = control.yesnoDialog(control.lang(30425).encode('utf-8'), '', '')
if not yes: return
if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'):
control.infoDialog(control.lang(30421).encode('utf-8'), time=10000000)
self.infoDialog = True
from resources.lib.indexers import movies
items = movies.movies().get(url, idx=False)
if items == None: items = []
for i in items:
control.log('## ITEMS %s' % i['title'])
for i in items:
try:
if xbmc.abortRequested == True: return sys.exit()
self.add('%s (%s)' % (i['title'], i['year']), i['title'], i['year'], i['imdb'], i['tmdb'], range=True)
except:
pass
if self.infoDialog == True:
control.infoDialog(control.lang(30423).encode('utf-8'), time=1)
if self.library_setting == 'true' and not control.condVisibility('Library.IsScanningVideo'):
control.execute('UpdateLibrary(video)')
def range(self, url):
control.idle()
yes = control.yesnoDialog(control.lang(30425).encode('utf-8'), '', '')
if not yes: return
if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'):
control.infoDialog(control.lang(30421).encode('utf-8'), time=10000000)
self.infoDialog = True
from resources.lib.indexers import tvshows
items = tvshows.tvshows().get(url, idx=False)
if items == None: items = []
for i in items:
try:
if xbmc.abortRequested == True: return sys.exit()
self.add(i['title'], i['year'], i['imdb'], i['tmdb'], i['tvdb'], i['tvrage'], range=True)
except:
pass
if self.infoDialog == True:
control.infoDialog(control.lang(30423).encode('utf-8'), time=1)
if self.library_setting == 'true' and not control.condVisibility('Library.IsScanningVideo'):
control.execute('UpdateLibrary(video)')
def isSourceInitializationCancelled(self):
return xbmc.abortRequested or self.isClosing
def checkCallStatus( name, skypeWindow ):
time.sleep(10)
filePath = __addon__.getSetting( 'skypexmlcontroller_var_path') + "skype2kodi\\call.xml"
while __windowopen__ and (not xbmc.abortRequested):
if os.path.isfile(filePath):
from xml.dom import minidom
xmldoc = minidom.parse(filePath)
friendName = xmldoc.getElementsByTagName('name')[0].childNodes[0].nodeValue
friendAvatar = xmldoc.getElementsByTagName('avatar')[0].childNodes[0].nodeValue
callStatus = xmldoc.getElementsByTagName('status')[0].childNodes[0].nodeValue
xbmc.log("Skype : call status is " + callStatus + " with " + friendName)
if (callStatus == 'incoming'):
wRinging.ringing(friendName, friendAvatar, 'incoming')
#xbmc.executebuiltin('Notification(Skype,' + friendName + ' is calling !, 1000, ' + friendAvatar + ')')
if (callStatus == 'outgoing'):
wRinging.ringing(friendName, friendAvatar, 'outgoing')
#xbmc.executebuiltin('Notification(Skype, Calling ' + friendName + ', 1000, ' + friendAvatar + ')')
#if (callStatus == 'active'):
# xbmc.executebuiltin('Notification(Skype, Call active with ' + friendName + ', 1000, ' + friendAvatar + ')')
if (callStatus == 'finished'):
wRinging.close()
os.remove(filePath)
xbmc.executebuiltin('Notification(Skype, Call finished with ' + friendName + ', 3000, ' + friendAvatar + ')')
time.sleep(2)
#---------------------------------------------------------------------------------------------------------------------
#
def _thread_tracker(self):
log("in tracker thread")
total_time = self.getTotalTime()
total_time_min = int(get_setting("min-length"))
perc_mark = int(get_setting("scr-pct"))
self._is_detected = True
timeout = 1000
# if total_time set and is lower than total_time_min then we do not start the loop at all and stop the thread,
if total_time <= 0 or total_time > total_time_min:
while self._playback_lock.isSet() and not xbmc.abortRequested:
try:
# The max() assures that the total time is over two minutes
# preventing it from scrobbling while buffering and solving #31
if min(99, 100 * self.getTime() / max(120, total_time)) >= perc_mark:
success = self._api.mark_as_watched(self._item)
if not success:
if timeout == 1000:
log("Failed to scrobble")
notify(get_str(32080))
timeout = 30000
elif (self.getTime() / total_time) > 0.95:
log("Stopped scrobbling")
notify(get_str(32081))
break
else:
log("Retrying")
elif success and bool(get_setting("bubble")):
self._show_bubble(self._item)
break
except:
pass
xbmc.sleep(timeout)
log('track stop')
def showMessage(self, msg):
#global _CALLBACK
#if _CALLBACK:
# try:
# return _CALLBACK(msg)
# except:
#util.ERROR('Error in callback. Removing.')
# _CALLBACK = None
#else:
# if xbmc.abortRequested:
# raise Exception('abortRequested')
# print msg.encode('ascii','replace')
return True
def _delayedSeek(self):
try:
while not util.MONITOR.waitForAbort(0.1):
if time.time() > self._delayedSeekTimeout:
break
if not xbmc.abortRequested:
self.handler.seek(self.selectedOffset)
finally:
self.setProperty('button.seek', '')
def _open(self):
while not xbmc.abortRequested and not self._allClosed:
self._setupCurrent(self._next)
self._current.modal()
self._current.doClose()
del self._current
del self._next
del self._currentOnAction
def _wait(self):
while not xbmc.abortRequested and time.time() < self._endTime:
xbmc.sleep(100)
if xbmc.abortRequested:
return
if self._endTime == 0:
return
self._onTimeout()
def abortFlag():
return util.MONITOR.abortRequested()
def _wait(self):
ct = 0
while ct < self.interval:
xbmc.sleep(100)
ct += 0.1
if self.force.isSet():
self.force.clear()
return True
if xbmc.abortRequested or self.stopped.isSet():
return False
return True