def onAction(self, action):
if action in [ xbmcgui.ACTION_PREVIOUS_MENU, xbmcgui.ACTION_NAV_BACK ]:
self.close()
try:focused_control=self.getFocusId()
except:focused_control=0
#log('focused control='+repr(focused_control)+' action='+repr(action))
if focused_control==self.main_control_id: #main_control_id is the listbox
self.gui_listbox_SelectedPosition = self.gui_listbox.getSelectedPosition()
item = self.gui_listbox.getSelectedItem()
item_type=item.getProperty('item_type').lower()
if action in [ xbmcgui.ACTION_CONTEXT_MENU ]:
ACTION_manage_subreddits=item.getProperty('ACTION_manage_subreddits')
log( " left pressed %d IsPlayable=%s url=%s " %( self.gui_listbox_SelectedPosition, item_type, ACTION_manage_subreddits ) )
if ACTION_manage_subreddits:
xbmc.executebuiltin( ACTION_manage_subreddits )
self.close()
python类log()的实例源码
def populate_tlc_children(self,tlc_id):
#controls_generator=generator(controls)
child_comments_tuple_generator=generator(self.child_lists[tlc_id])
for control_id in self.x_controls:
control=self.getControl(control_id)
try:
post_text,author,depth=child_comments_tuple_generator.next()
except StopIteration:
post_text,author,depth=None,None,0
if post_text:
#control.setText( ("[B]"+repr(control_id-1000)+"[/B] " + post_text) if post_text else None)
#control.setText(post_text+' '+author)
#log(('.'*depth)+repr(post_text))
control.setText(post_text)
else:
control.setText(None)
#use animation to stagger the comments according to how deep they are
control.setAnimations( [ animation_format(0,100,'slide', 0, (20*depth), 'sine', 'in' ) ] )
#either there's no more child comments or we run out of controls
return
def onClick(self, controlID):
clicked_control=self.getControl(controlID)
#log('clicked on controlID='+repr(controlID))
#button control does not have a property, we use a different method.
value_to_search=clicked_control.getLabel() #we'll just use the Property('link_url') that we used as button label to search
listitems=self.listing
li = next(l for l in listitems if l.getProperty('link_url') == value_to_search)
item_type=li.getProperty('item_type')
di_url=li.getProperty('onClick_action')
log( " clicked %s IsPlayable=%s url=%s " %( repr(clicked_control),item_type, di_url ) )
if item_type=='playable':
#a big thank you to spoyser (http://forum.kodi.tv/member.php?action=profile&uid=103929) for this help
pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
pl.clear()
pl.add(di_url, value_to_search)
xbmc.Player().play(pl, windowed=False)
elif item_type=='script':
self.busy_execute_sleep(di_url,5000,False)
def __init__(self, thread_event, image_queue):
#self.log('__init__ start')
self.exit_requested = False
self.toggle_info_display_requested=False
self.background_control = None
self.preload_control = None
self.image_count = 0
#self.image_controls = []
self.tni_controls = []
self.global_controls = []
self.exit_monitor = ExitMonitor(self.stop)
self.init_xbmc_window()
# self.xbmc_window = ScreensaverWindow(self.stop)
# self.xbmc_window.show()
self.init_global_controls()
self.load_settings()
self.init_cycle_controls()
self.stack_cycle_controls()
#self.log('__init__ end')
def init_cycle_controls(self):
#self.log(' init_cycle_controls start')
for _ in xrange(self.IMAGE_CONTROL_COUNT):
img_control = ControlImage(0, 0, 0, 0, '', aspectRatio=2) #(values 0 = stretch (default), 1 = scale up (crops), 2 = scale down (black bars)
txt_control = ControlTextBox(0, 0, 0, 0, font='font16')
# xbfont_left = 0x00000000
# xbfont_right = 0x00000001
# xbfont_center_x = 0x00000002
# xbfont_center_y = 0x00000004
# xbfont_truncated = 0x00000008
#ControlLabel(x, y, width, height, label, font=None, textColor=None, disabledColor=None, alignment=0, hasPath=False, angle=0)
#txt_control = ControlLabel(0, 0, 0, 0, '', font='font30', textColor='', disabledColor='', alignment=6, hasPath=False, angle=0)
#self.image_controls.append(img_control)
self.tni_controls.append([txt_control,img_control])
#self.log(' init_cycle_controls end')
def get_description_and_images(self, source):
#self.log('get_images2')
self.image_aspect_ratio = 16.0 / 9.0
images = []
if source == 'image_folder':
#image folder source not used
path = '' #SlideshowCacheFolder #addon.getSetting('image_path')
if path:
images = self._get_folder_images(path)
elif source == 'q':
#implement width & height extract here.
#images=[[item[0], item[1],item[2], item[3], ] for item in q.queue]
#[title,media_url, width, height, len(entries), description])
images=[ [i.get('li_label'), i.get('DirectoryItem_url'),i.get('width'), i.get('height'), i.get('description') ] for i in q.queue]
log( "queue size:%d" %q.qsize() )
#texts=[item[0] for item in q.queue]
#for i in images: self.log(' image: %s' %i)
#self.log(' %d images' % len(images))
return images
def _get_folder_images(self, path):
self.log('_get_folder_images started with path: %s' % repr(path))
_, files = xbmcvfs.listdir(path)
images = [
xbmc.validatePath(path + f) for f in files
if f.lower()[-3:] in ('jpg', 'png')
]
#if addon.getSetting('recursive') == 'true':
# for directory in dirs:
# if directory.startswith('.'):
# continue
# images.extend(
# self._get_folder_images(
# xbmc.validatePath('/'.join((path, directory, '')))
# )
# )
self.log('_get_folder_images ends')
return images
def wait(self):
# wait in chunks of 500ms to react earlier on exit request
chunk_wait_time = int(CHUNK_WAIT_TIME)
remaining_wait_time = int(self.NEXT_IMAGE_TIME)
while remaining_wait_time > 0:
if self.exit_requested:
self.log('wait aborted')
return
if self.toggle_info_display_requested: #this value is set on specific keypress in action_id_handler
#self.log('toggle_info_display_requested')
self.toggle_info_display_requested=False
self.toggle_info_display_handler()
if remaining_wait_time < chunk_wait_time:
chunk_wait_time = remaining_wait_time
remaining_wait_time -= chunk_wait_time
xbmc.sleep(chunk_wait_time)
def del_controls(self):
#self.log('del_controls start')
#self.xbmc_window.removeControls(self.img_controls)
try: self.xbmc_window.removeControls(self.tni_controls[0]) #imageControls
except: pass
try: self.xbmc_window.removeControls(self.tni_controls[1]) #textBoxes
except: pass
self.xbmc_window.removeControls(self.global_controls)
self.preload_control = None
self.background_control = None
self.loading_control = None
self.tni_controls = []
self.global_controls = []
self.xbmc_window.close()
self.xbmc_window = None
#self.log('del_controls end')
def populate_subreddits_pickle():
from guis import progressBG
loading_indicator=progressBG(translation(32023)) #Gathering icons..
with open(subredditsFile, 'r') as fh:
subreddit_settings = fh.readlines()
#xbmc_notify("initializing", "Building icons cache", 5000)
loading_indicator.set_tick_total(len(subreddit_settings))
for entry in subreddit_settings:
entry=entry.strip()
loading_indicator.tick(1,entry)
s=convert_settings_entry_into_subreddits_list_or_domain(entry)
if s:
#t = threading.Thread(target=get_subreddit_entry_info_thread, args=(s,) )
log('processing saved entry:'+repr(entry))
get_subreddit_entry_info_thread(s)
xbmc.sleep(2000)
loading_indicator.end()
def listAlbum(album_url, name, type_):
from slideshow import slideshowAlbum
from domains import sitesManager
log(" listAlbum:"+album_url)
hoster = sitesManager( album_url )
#log( ' %s %s ' %(hoster.__class__.__name__, album_url ) )
if hoster:
dictlist=hoster.ret_album_list(album_url)
if type_=='return_dictlist': #used in autoSlideshow
return dictlist
if not dictlist:
xbmc_notify(translation(32200), translation(32055)) #slideshow, no playable items
return
#log(pprint.pformat(dictlist))
if addon.getSetting('use_slideshow_for_album') == 'true':
slideshowAlbum( dictlist, name )
else:
display_album_from( dictlist, name )
def playVideo(url, name, type_):
xbmc_busy(False)
pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
pl.clear()
if url : #sometimes url is a list of url or just a single string
if isinstance(url, basestring):
pl.add(url, xbmcgui.ListItem(name))
xbmc.Player().play(pl, windowed=False) #scripts play video like this.
#listitem = xbmcgui.ListItem(path=url) #plugins play video like this.
#xbmcplugin.setResolvedUrl(pluginhandle, True, listitem)
else:
for u in url:
#log('u='+ repr(u))
#pl.add(u)
pl.add(u, xbmcgui.ListItem(name))
xbmc.Player().play(pl, windowed=False)
else:
log("playVideo(url) url is blank")
def parse_web_url_from(recently_played_url):
# builds the youtube url from plugin://plugin.video.youtube/play/?video_id=dIgSKPzLC9g
# grabs the youtube url from plugin://plugin.video.reddit_viewer/?mode=play&url=https%3A%2F%2Fyoutu.be%2FUhOx-FpEAQk
# excludes googlevideo.com/videoplayback
from domains import ClassYoutube
ret_url=recently_played_url.split("|", 1)[0] #remove |Useragent:...
link_components=urlparse.urlparse( recently_played_url )
#log("*****{0} scheme[{1}]**".format( recently_played_url, link_components.scheme ) )
if link_components.scheme=="plugin":
query = urlparse.parse_qs(link_components.query)
netloc=link_components.netloc
if netloc=="plugin.video.reddit_viewer":
ret_url=''.join(query.get("url"))
elif netloc=="plugin.video.youtube":
video_id=query.get("video_id")
ret_url=ClassYoutube.build_youtube_url_with_video_id(''.join(video_id)) #''.join(video_id) <-- list to string
#log("***** video ID="+''.join(video_id)) #ClassYoutube
elif link_components.scheme=="https":
#log(link_components.path)
if link_components.path.startswith('/videoplayback'): #youtube videos parsed by youtube_dl are unplayable from history, we exclude it here
ret_url=None
return ret_url
def build_reddit_search_context_menu_entries(hasmultiplesubreddit,subreddit,link_url ):
cxm_list=[]
colored_subreddit_full=colored_subreddit( subreddit )
label_search=translation(32520)
parts_of_link_url=urlparse.urlparse(link_url)
if cxm_show_search:
if GCXM_hasmultiplesubreddit:
cxm_list.append( (label_search , build_script("search", '', '') ) )
else:
label_search+=' {0}'.format(colored_subreddit_full)
cxm_list.append( (label_search , build_script("search", '', subreddit) ) )
#NOTE: can't use the entire link_url because it will work for www.reddit.com but not for oauth.reddit.com
part_to_search="{0} {1}".format(parts_of_link_url.path,parts_of_link_url.query)
if part_to_search.startswith('/'): part_to_search=part_to_search[1:] #remove starting '/'
remove_these_words=['.mp4','.webm','/v/','.jpg','.png'] #mainly to match imgur links where we want to catch the imageID not "imageID.mp4"
part_to_search=re.sub('|'.join(re.escape(word) for word in remove_these_words), '', part_to_search)
#log('parts to search='+part_to_search)
cxm_list.append( (translation(32531) , build_script("listSubReddit", assemble_reddit_filter_string(part_to_search,'','',''), name=translation(32531)) ) ) #"Other posts with this link"
return cxm_list
def send_msgs():
with sqlite3.connect('events.db') as db:
cur=db.cursor()
cur.execute('select msgid,content from push_msgs')
res=cur.fetchall()
for msgid,content in res:
if itchat.send_msg(content,toUserName=group_name):
cur=db.cursor()
cur.execute('delete from push_msgs where msgid=?',[msgid])
db.commit()
print(' -> sent msg:',content)
else:
if msgid not in logged_errors:
print('!!! send failed:',content)
log('error','?????????#%d??%s'%(msgid,content))
logged_errors.add(msgid)
time.sleep(.5)
def get_unity_version(self, response):
content = json.loads(response.body)
utils.log('content:%s' % response.body)
self.unity_version = content.get('kharma_version', '')
self.headers['X-Kharma-Version'] = self.unity_version
# unity asset store ????? json ??
url = 'https://www.assetstore.unity3d.com/api/en-US/home/categories.json'
yield Request(
url = url,
method = 'GET',
headers = self.headers,
meta = {
'download_timeout': 20,
'is_proxy': False,
},
callback = self.get_categories,
)
# ?????? json ???????? unity ???????
# ????????????????
def get_proxy(self):
if get_project_settings().get('IS_USE_PROXY', True):
if len(self.proxys) <= 10:
self.update_proxy()
if len(self.proxys) > 0:
self.index = self.index + 1
self.index = self.index % len(self.proxys)
proxy = 'http://%s:%s' % (self.proxys[self.index].get('ip'), self.proxys[self.index].get('port'))
utils.log('++++++++++proxy:%s++++++++++' % proxy)
return proxy
return None
else:
return None
def delete_proxy(self, proxy):
if proxy == None:
return
try:
rets = proxy.split(':')
ip = rets[1]
ip = ip[2:]
for item in self.proxys:
if item.get('ip') == ip:
self.proxys.remove(item)
break
if len(self.proxys) < 3:
self.update_proxy()
utils.log('--------------delete ip:%s-----------' % ip)
r = requests.get(url = '%s/delete?name=%s&ip=%s' % (self.address, self.name, ip))
return r.text
except:
return False
def register_text_handler(self, callback, allow_edited=False):
"""Registers text message handler
Args:
callback(function): callable object to execute
allow_edited(Optional[bool]): pass edited messages
"""
@utils.log(logger, print_ret=False)
def process_update(bot, update):
lang = utils.get_lang(self._storage, update.effective_user)
callback(update.effective_message, lang)
self._dispatcher.add_handler(MessageHandler(Filters.text, process_update,
edited_updates=allow_edited))