Best Python code snippet using autotest_python
video.py
Source:video.py
1# -*- coding: utf-8 -*-2# script.module.python.koding.aio3# Python Koding AIO (c) by whufclee (info@totalrevolution.tv)4# Python Koding AIO is licensed under a5# Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License.6# You should have received a copy of the license along with this7# work. If not, see http://creativecommons.org/licenses/by-nc-nd/4.0.8# IMPORTANT: If you choose to use the special noobsandnerds features which hook into their server9# please make sure you give approptiate credit in your add-on description (noobsandnerds.com)10# 11# Please make sure you've read and understood the license, this code can NOT be used commercially12# and it can NOT be modified and redistributed. If you're found to be in breach of this license13# then any affected add-ons will be blacklisted and will not be able to work on the same system14# as any other add-ons which use this code. Thank you for your cooperation.15import os16import shutil17import xbmc18import xbmcgui19from __init__ import dolog20from guitools import Show_Busy21from systemtools import Last_Error22dp = xbmcgui.DialogProgress()23check_started = xbmc.translatePath('special://profile/addon_data/script.module.python.koding.aio/temp/playback_in_progress')24#---------------------------------------------------------------- 25# TUTORIAL #26def Check_Playback(ignore_dp=False,timeout=10):27 """28This function will return true or false based on video playback. Simply start a stream29(whether via an add-on, direct link to URL or local storage doesn't matter), the code will30then work out if playback is successful. This uses a number of checks and should take into31account all potential glitches which can occur during playback. The return should happen32within a second or two of playback being successful (or not).33CODE: Check_Playback()34AVAILABLE PARAMS:35 36 ignore_dp - By default this is set to True but if set to False37 this will ignore the DialogProgress window. If you use a DP while38 waiting for the stream to start then you'll want to set this True.39 Please bare in mind the reason this check is in place and enabled40 by default is because some streams do bring up a DialogProgress41 when initiated (such as f4m proxy links) and disabling this check42 in those circumstances can cause false positives.43 timeout - This is the amount of time you want to allow for playback44 to start before sending back a response of False. Please note if45 ignore_dp is set to True then it will also add a potential 10s extra46 to this amount if a DialogProgress window is open. The default setting47 for this is 10s.48EXAMPLE CODE:49xbmc.Player().play('http://totalrevolution.tv/videos/python_koding/Browse_To_Folder.mov')50isplaying = koding.Check_Playback()51if isplaying:52 dialog.ok('PLAYBACK SUCCESSFUL','Congratulations, playback was successful')53 xbmc.Player().stop()54else:55 dialog.ok('PLAYBACK FAILED','Sorry, playback failed :(')56~"""57 if not os.path.exists(check_started):58 os.makedirs(check_started)59 60 if not ignore_dp:61 isdialog = True62 counter = 163# Check if the progress window is active and wait for playback64 while isdialog:65 dolog('### Current Window: %s' % xbmc.getInfoLabel('System.CurrentWindow'))66 dolog('### Current XML: %s' % xbmc.getInfoLabel('Window.Property(xmlfile)'))67 dolog('### Progress Dialog active, sleeping for %s seconds' % counter)68 xbmc.sleep(1000)69 if xbmc.getCondVisibility('Window.IsActive(progressdialog)') or (xbmc.getInfoLabel('Window.Property(xmlfile)') == 'DialogProgress.xml'):70 isdialog = True71 else:72 isdialog = False73 counter += 174 dolog('counter: %s' % counter)75# Given the DialogProgress 10 seconds to finish and it's still up - time to close it76 if counter == 10:77 try:78 dolog('attempting to send click to close dp')79 xbmc.executebuiltin('SendClick()')80 if dp.iscanceled():81 dp.close()82 except:83 dolog('### FAILED TO CLOSE DP')84 isplaying = xbmc.Player().isPlaying()85 counter = 186 if xbmc.Player().isPlayingAudio():87 return True88# If xbmc player is not yet active give it some time to initialise89 while not isplaying and counter < timeout:90 xbmc.sleep(1000)91 isplaying = xbmc.Player().isPlaying()92 dolog('### XBMC Player not yet active, sleeping for %s seconds' % counter)93 counter += 194 success = 095 counter = 096# If it's playing give it time to physically start streaming then attempt to pull some info97 if isplaying:98 xbmc.sleep(1000)99 while not success and counter < 10:100 try:101 if xbmc.Player().isPlayingVideo():102 infotag = xbmc.Player().getVideoInfoTag()103 vidtime = xbmc.Player().getTime()104 if vidtime > 0:105 success = 1106# If playback doesn't start automatically (buffering) we force it to play107 else:108 dolog('### Playback active but time at zero, trying to unpause')109 xbmc.executebuiltin('PlayerControl(Play)')110 xbmc.sleep(2000)111 vidtime = xbmc.Player().getTime()112 if vidtime > 0:113 success = 1114# If no infotag or time could be pulled then we assume playback failed, try and stop the xbmc.player115 except:116 counter += 1117 xbmc.sleep(1000)118# Check if the busy dialog is still active from previous locked up playback attempt119 isbusy = xbmc.getCondVisibility('Window.IsActive(busydialog)')120 counter = 1121 while isbusy:122 dolog('### Busy dialog active, sleeping for %ss' % counter)123 xbmc.sleep(1000)124 isbusy = xbmc.getCondVisibility('Window.IsActive(busydialog)')125 counter += 1126 if counter == 5:127 xbmc.executebuiltin('Dialog.Close(busydialog)')128 if not success:129 xbmc.executebuiltin('PlayerControl(Stop)')130 dolog('### Failed playback, stopped stream')131 shutil.rmtree(check_started)132 return False133 else:134 shutil.rmtree(check_started)135 return True136#---------------------------------------------------------------- 137# TUTORIAL #138def Play_Video(video,showbusy=True,content='video',ignore_dp=False,timeout=10):139 """140This will attempt to play a video and return True or False on141whether or not playback was successful. This function is similar142to Check_Playback but this actually tries a number of methods to143play the video whereas Check_Playback does not actually try to144play a video - it will just return True/False on whether or not145a video is currently playing.146CODE: Play_Video(video, [showbusy, content])147AVAILABLE PARAMS:148 (*) video - This is the path to the video, this can be a local149 path, online path or a channel number from the PVR.150 showbusy - By default this is set to True which means while the151 function is attempting to playback the video the user will see the152 busy dialog. Set to False if you prefer this not to appear but do153 bare in mind a user may navigate to another section and try playing154 something else if they think this isn't doing anything.155 content - By default this is set to 'video', however if you're156 passing through audio you may want to set this to 'music' so the157 system can correctly set the tags for artist, song etc.158 ignore_dp - By default this is set to True but if set to False159 this will ignore the DialogProgress window. If you use a DP while160 waiting for the stream to start then you'll want to set this True.161 Please bare in mind the reason this check is in place and enabled162 by default is because some streams do bring up a DialogProgress163 when initiated (such as f4m proxy links) and disabling this check164 in those circumstances can cause false positives.165 timeout - This is the amount of time you want to allow for playback166 to start before sending back a response of False. Please note if167 ignore_dp is set to True then it will also add a potential 10s extra168 to this amount if a DialogProgress window is open. The default setting169 for this is 10s.170EXAMPLE CODE:171isplaying = koding.Play_Video('http://totalrevolution.tv/videos/python_koding/Browse_To_Folder.mov')172if isplaying:173 dialog.ok('PLAYBACK SUCCESSFUL','Congratulations, playback was successful')174 xbmc.Player().stop()175else:176 dialog.ok('PLAYBACK FAILED','Sorry, playback failed :(')177~"""178 dolog('### ORIGINAL VIDEO: %s'%video)179 import urlresolver180 try: import simplejson as json181 except: import json182 meta = {}183 for i in ['title', 'originaltitle', 'tvshowtitle', 'year', 'season', 'episode', 'genre', 'rating', 'votes',184 'director', 'writer', 'plot', 'tagline']:185 try:186 meta[i] = xbmc.getInfoLabel('listitem.%s' % i)187 except:188 pass189 meta = dict((k, v) for k, v in meta.iteritems() if not v == '')190 if 'title' not in meta:191 meta['title'] = xbmc.getInfoLabel('listitem.label')192 icon = xbmc.getInfoLabel('listitem.icon')193 icon = xbmc.getInfoLabel('listitem.icon')194 item = xbmcgui.ListItem(path=video, iconImage=icon, thumbnailImage=icon)195 if content == "music":196 try:197 meta['artist'] = xbmc.getInfoLabel('listitem.artist')198 item.setInfo(type='Music', infoLabels={'title': meta['title'], 'artist': meta['artist']})199 except:200 item.setInfo(type='Video', infoLabels=meta)201 else:202 item.setInfo(type='Video', infoLabels=meta)203 playback = False204 if showbusy:205 Show_Busy()206# Play from a db entry - untested207 if video.isdigit():208 dolog('### Video is digit, presuming it\'s a db item')209 command = ('{"jsonrpc": "2.0", "id":"1", "method": "Player.Open","params":{"item":{"channelid":%s}}}' % url)210 xbmc.executeJSONRPC(command)211 playback = Check_Playback(ignore_dp,timeout)212 is_in_progress = True213 progress_count = 0214 while is_in_progress:215 xbmc.sleep(1000)216 progress_count += 1217 dolog('Progress check is active, sleeping %s'%progress_count)218 is_in_progress = os.path.exists(check_started)219# if a plugin path is sent we try activate window220 elif video.startswith('plugin://'):221 try:222 dolog('Attempting to play via XBMC.ActivateWindow(10025, ...) method')223 xbmc.executebuiltin('XBMC.ActivateWindow(10025,%s)' % video)224 playback = Check_Playback(ignore_dp,timeout)225 is_in_progress = True226 progress_count = 0227 while is_in_progress:228 xbmc.sleep(1000)229 progress_count += 1230 dolog('Progress check is active, sleeping %s'%progress_count)231 is_in_progress = os.path.exists(check_started)232 except:233 dolog(Last_Error())234# If an XBMC action has been sent through we do an executebuiltin command235 elif video.startswith('ActivateWindow') or video.startswith('RunAddon') or video.startswith('RunScript') or video.startswith('PlayMedia'):236 try:237 dolog('Attempting to play via xbmc.executebuiltin method')238 xbmc.executebuiltin('%s'%video)239 playback = Check_Playback(ignore_dp,timeout)240 is_in_progress = True241 progress_count = 0242 while is_in_progress:243 xbmc.sleep(1000)244 progress_count += 1245 dolog('Progress check is active, sleeping %s'%progress_count)246 is_in_progress = os.path.exists(check_started)247 except:248 dolog(Last_Error())249 elif ',' in video:250# Standard xbmc.player method (a comma in url seems to throw urlresolver off)251 try:252 dolog('Attempting to play via xbmc.Player.play() method')253 xbmc.Player().play('%s'%video, item)254 playback = Check_Playback(ignore_dp,timeout)255 is_in_progress = True256 progress_count = 0257 while is_in_progress:258 xbmc.sleep(1000)259 progress_count += 1260 dolog('Progress check is active, sleeping %s'%progress_count)261 is_in_progress = os.path.exists(check_started)262# Attempt to resolve via urlresolver263 except:264 try:265 dolog('Attempting to resolve via urlresolver module')266 dolog('video = %s'%video)267 hmf = urlresolver.HostedMediaFile(url=video, include_disabled=False, include_universal=True)268 if hmf.valid_url() == True:269 video = hmf.resolve()270 dolog('### VALID URL, RESOLVED: %s'%video)271 xbmc.Player().play('%s' % video, item)272 playback = Check_Playback(ignore_dp,timeout)273 is_in_progress = True274 progress_count = 0275 while is_in_progress:276 xbmc.sleep(1000)277 progress_count += 1278 dolog('Progress check is active, sleeping %s'%progress_count)279 is_in_progress = os.path.exists(check_started)280 except:281 dolog(Last_Error())282 else:283# Attempt to resolve via urlresolver284 try:285 dolog('Attempting to resolve via urlresolver module')286 dolog('video = %s'%video)287 hmf = urlresolver.HostedMediaFile(url=video, include_disabled=False, include_universal=True)288 if hmf.valid_url() == True:289 video = hmf.resolve()290 dolog('### VALID URL, RESOLVED: %s'%video)291 xbmc.Player().play('%s' % video, item)292 playback = Check_Playback(ignore_dp,timeout)293 is_in_progress = True294 progress_count = 0295 while is_in_progress:296 xbmc.sleep(1000)297 progress_count += 1298 dolog('Progress check is active, sleeping %s'%progress_count)299 is_in_progress = os.path.exists(check_started)300# Standard xbmc.player method301 except:302 try:303 dolog('Attempting to play via xbmc.Player.play() method')304 xbmc.Player().play('%s' % video, item)305 playback = Check_Playback(ignore_dp,timeout)306 is_in_progress = True307 progress_count = 0308 while is_in_progress:309 xbmc.sleep(1000)310 progress_count += 1311 dolog('Progress check is active, sleeping %s'%progress_count)312 is_in_progress = os.path.exists(check_started)313 except:314 dolog(Last_Error())315 dolog('Playback status: %s' % playback)316 Show_Busy(False)317 return playback318#---------------------------------------------------------------- 319# TUTORIAL #320def Sleep_If_Playback_Active():321 """322This will allow you to pause code while kodi is playing audio or video323CODE: Sleep_If_Playback_Active()324EXAMPLE CODE:325dialog.ok('PLAY A VIDEO','We will now attempt to play a video, once you stop this video you should see a dialog.ok message.')326xbmc.Player().play('http://download.blender.org/peach/bigbuckbunny_movies/big_buck_bunny_720p_stereo.avi')327xbmc.sleep(3000) # Give kodi enough time to load up the video328koding.Sleep_If_Playback_Active()329dialog.ok('PLAYBACK FINISHED','The playback has now been finished so this dialog code has now been initiated')330~"""331 isplaying = xbmc.Player().isPlaying()332 while isplaying:333 xbmc.sleep(500)...
cmdfm-console.py
Source:cmdfm-console.py
...20 # --- Internal code ---21 def prepare(self, http, player):22 self.http = http23 self.player = player24 def check_playback(self):25 # If our last song has finished and we still have a genre, repeat it.26 if (self.last_genre != None) and (not self.player.isPlaying()):27 # Let's repeat the last genre.28 self.do_play(self.last_genre)29 else:30 # Just reset our timer.31 self.timer = threading.Timer(CHECK_INTERVAL, self.check_playback)32 self.timer.start()33 # --- Console controls ---34 def emptyline(self):35 return False36 # --- Basic functions ---37 def do_about(self, args):38 print(' * * * * * * * * * * * * * * * * * * * * * * *')39 print(' * *')40 print(' * cmd.fm console *')41 print(' * *')42 print(' * https://github.com/rgsilva/cmdfm-console *')43 print(' * *')44 print(' * * * * * * * * * * * * * * * * * * * * * * *')45 def do_exit(self, args):46 if (self.player.isPlaying()):47 self.player.stop()48 print('Bye!')49 return True50 def do_help(self, args):51 print('Available commands are')52 print('---------------------------------------------------------')53 print('genre list # Lists all genres')54 print('genre search <query> # Search genre')55 print('play <genre name> # Play genre tracks')56 #print('status # Shows track status')57 #print('resume # Resume playback')58 #print('pause # Pause playback')59 print('skip # Skip current track')60 print('about # Hello?')61 print('---------------------------------------------------------')62 # --- cmd.fm functions ---63 # genre list64 # genre search <keyword>65 def do_genre(self, args):66 url = None67 if (args == 'list'):68 url = REQUEST_GENRES_LIST69 elif (args.split()[0] == 'search'):70 keyword = ' '.join(args.split()[1:])71 if (keyword == ''):72 print('- You need to specify a keyword to look for.')73 return False74 url = REQUEST_GENRES_SEARCH + self.http.escape(keyword)75 else:76 print("- Invalid usage.")77 return False78 genres = self.http.json(url)79 for g in genres:80 print("-", g)81 # play <genre>82 def do_play(self, genre):83 if (genre == ''):84 print("- You need to specify a genre.")85 return False86 # Get the stream information.87 info = self.http.json(REQUEST_PLAY + self.http.escape(genre))88 # Just in case.89 if (info == False):90 print("- The genre you specified is invalid.")91 return False92 # We got a song, so let's stop our timer, just in case.93 if (self.timer != None):94 self.timer.cancel()95 # Play it.96 try:97 self.player.play(info['stream_url'] + CLIENT_ID)98 print('+ Playing', info['title'])99 # Save the genre for repeating100 self.last_genre = genre101 # Start the timer.102 self.check_playback()103 except:104 print("- Something went wrong with the playback. Please try again.")105 # stop106 def do_stop(self, args):107 if (self.player.isPlaying()):108 self.last_genre = None109 self.player.stop()110 else:111 print('- Cannot stop a song that\'s not playing!')112 return False113 # skip114 def do_skip(self, args):115 if (self.player.isPlaying()):116 self.player.stop()...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!