def initialize(self):

        self.ptr_name = self.config['pointer']
        self.stream_table_names = {}
        self.checked_tables = {}

        if not readconf.check_db_config(self.config):
            return False

        if readconf.is_missing(self.config, 'port'):
            self.config['port'] = 3306

        self.sql_file = self.config['sql']
        if not self.check_pointer_table():
            utils.log_error("Couldn't create read pointers table")
            return False

        row = self.fetch_row(
            "SELECT file, pos FROM pointers WHERE pointer=%s;",
            (self.ptr_name, ))

        if row is None:
            return False

        self.pointer = (0, 0)
        if len(row) > 0:
            self.pointer = (row[0], row[1])

        return True
    def event_stream_offchain_purged(self, event):
        if not self.check_stream_table(event):
            return False

        document = self.fetch_document(event.table, {"id": event.id})

        if document is None:
            utils.log_error("Item with this id not found")
            return False

        if "flags" not in document:
            utils.log_error("Cannot find flags field for purged document")
            return False

        return self.execute_update(
            event.table, {"id": event.id},
            {"flags": (document["flags"] & 254)}) and self.execute_unset(
                event.table,
                {"id": event.id},
                {
                    "binary_data": None,
                    "text_data": None,
                    "json_data": None,
                    "dataref": None
                },
            )
Beispiel #3
0
def play(url):
	# Show a dialog
	d = xbmcgui.DialogProgress()
	d.create(config.NAME, '')
	d.update(20, 'Fetching video parameters...')

	v = classes.Video()
	v.parse_xbmc_url(url)

	try:
		d.update(40, 'Fetching video URL...')
		base_url = get_url(v.id)

		d.update(60, 'Fetching video URL...')
		video_url = quality_url(base_url)

		d.update(80, 'Building playlist...')
		listitem = xbmcgui.ListItem(label=v.get_title(), iconImage=v.get_thumbnail(), thumbnailImage=v.get_thumbnail())
		listitem.setInfo('video', v.get_xbmc_list_item())
	
		d.update(99, 'Starting video...')
		xbmc.Player().play(video_url, listitem)
	except:
		# user cancelled dialog or an error occurred
		d = xbmcgui.Dialog()
		message = utils.dialog_error("Unable to play video")
		d.ok(*message)
		utils.log_error();
def make_series_list(url):
	params = utils.get_url(url)

	try:
		iview_config = comm.get_config()
		series_list = comm.get_programme(iview_config, params["category_id"])
		series_list.sort()

		ok = True
		for s in series_list:
			url = "%s?series_id=%s" % (sys.argv[0], s.id)
			thumbnail = s.get_thumbnail()

			listitem = xbmcgui.ListItem(s.get_list_title(), iconImage=thumbnail, thumbnailImage=thumbnail)
			listitem.setInfo('video', { 'plot' : s.get_description() })

			# add the item to the media list
			ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=True)

		xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
		xbmcplugin.setContent(handle=int(sys.argv[1]), content='tvshows')
	except:
		d = xbmcgui.Dialog()
		message = utils.dialog_error("Unable to fetch listing")
		d.ok(*message)
		utils.log_error();
Beispiel #5
0
def GetDateTimeAt(Buffer, Pos):
    Year = BCDtoByte(Buffer[Pos])
    if Year < 90:
        Year += 2000
    else:
        Year += 1900

    Month = BCDtoByte(Buffer[Pos + 1])
    Day = BCDtoByte(Buffer[Pos + 2])
    Hour = BCDtoByte(Buffer[Pos + 3])
    Min = BCDtoByte(Buffer[Pos + 4])
    Sec = BCDtoByte(Buffer[Pos + 5])
    MSec = (BCDtoByte(Buffer[Pos + 6]) * 10) + (BCDtoByte(Buffer[Pos + 7]) /
                                                10)

    try:
        return datetime.datetime(year=Year,
                                 month=Month,
                                 day=Day,
                                 hour=Hour,
                                 minute=Min,
                                 second=Sec,
                                 microsecond=int(MSec * 1000))
    except Exception as e:
        utils.log_error(e)
def make_channel_list():
    utils.log("url-make-channel" + sys.argv[0])

    try:
        channels = api.get_channels()

        ok = True
        for c in channels:
            listitem = xbmcgui.ListItem(label=c['name'])
            listitem.setInfo('video', {'title': c['name']})
            listitem.setIconImage('https://manstv.lattelecom.tv/' + c['logo'])
            listitem.setThumbnailImage('https://manstv.lattelecom.tv/' + c['thumb'])
            listitem.setProperty('IsPlayable', "true")

            # Build the URL for the program, including the list_info
            url = "%s?play=true&data_url=%s" % (sys.argv[0], c['id'])

            # Add the program item to the list
            ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=False,
                                             totalItems=len(channels))

        xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
        xbmcplugin.setContent(handle=int(sys.argv[1]), content='episodes')
    except:
        d = xbmcgui.Dialog()
        msg = utils.dialog_error("Unable to fetch listing")
        d.ok(*msg)
        utils.log_error()
Beispiel #7
0
def play(params):
	__addon__ = xbmcaddon.Addon()

	p = utils.get_url(params)

	# Show a dialog
	d = xbmcgui.DialogProgress()
	d.create(config.NAME, "Starting %s..." % p['name'])

	try:
		thumb = os.path.join(__addon__.getAddonInfo('path'), "resources", "img", "%s.jpg" % p['id'])
		labels = {
			"title": p['name'],
			"artist": "AFL Radio",
			"genre": "Sport"
		}
		listitem = xbmcgui.ListItem(p['name'])
		listitem.setInfo(type='music', infoLabels=labels)
		listitem.setThumbnailImage(thumb)

		# PAPlayer or AUTO fails here for some absurd reason
		xbmc.Player(xbmc.PLAYER_CORE_DVDPLAYER).play(p['url'], listitem)
	except:
		# user cancelled dialog or an error occurred
		d = xbmcgui.Dialog()
		message = utils.dialog_error("Unable to play %s" % p['name'])
		d.ok(*message)
		utils.log_error();
Beispiel #8
0
    def get(self):
        t0 = datetime.now()
        self.set_plaintext()

        successes = []
        for geo_point in geo_points:
            try:
                ghash = geohash.encode(geo_point[0], geo_point[1],
                                       classes.GHash._precision)

                geo_hash_entity = classes.GHash.get_or_insert(ghash)
                # 				geo_hash_entity = classes.GHash.get_or_insert('drt2zp')
                # tile = osm.Osm(geo_hash_entity)
                # 				tile.get_nature()
                # 				tile.get_roads()
                # 				tile.get_buildings()
                # 				tile.get_leisure()
                geo_hash_entity.populate()
                self.view_geohash(geo_hash_entity.name)

            except Exception, e:
                utils.log_error(e)
            else:
                logging.info('fetch success for ' + str(geo_point))
                successes.append(geo_point)
Beispiel #9
0
def redirect_url():
    try:
        response = authorization_handler.handle_redirect_request(client=client, db=DB.get_instance(consts.db_path))
        return response
    except Exception as err:
        utils.log_error(err)
        return SERVER_ERROR_MESSAGE.format(error=err)
Beispiel #10
0
def make_programs_list(url):

    try:
        params = utils.get_url(url)
        iview_config = comm.get_config()
        programs = comm.get_series_items(iview_config, params["series_id"])

        ok = True
        for p in programs:
            listitem = xbmcgui.ListItem(label=p.get_list_title(), iconImage=p.get_thumbnail(), thumbnailImage=p.get_thumbnail())
            listitem.setInfo('video', p.get_xbmc_list_item())

            if hasattr(listitem, 'addStreamInfo'):
                listitem.addStreamInfo('audio', p.get_xbmc_audio_stream_info())
                listitem.addStreamInfo('video', p.get_xbmc_video_stream_info())

            # Build the URL for the program, including the list_info
            url = "%s?play=true&%s" % (sys.argv[0], p.make_xbmc_url())

            # Add the program item to the list
            ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=False, totalItems=len(programs))

        xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
        xbmcplugin.setContent(handle=int(sys.argv[1]), content='episodes')
    except:
        d = xbmcgui.Dialog()
        msg = utils.dialog_error("Unable to fetch listing")
        d.ok(*msg)
        utils.log_error();
Beispiel #11
0
def logout():
    try:
        response = handle_logout(db=DB.get_instance(consts.db_path))
        return response
    except Exception as err:
        utils.log_error(err)
        return make_response(SERVER_ERROR_MESSAGE.format(error=err), HTTP_SERVER_ERROR)
Beispiel #12
0
def authorize():
    try:
        response = authorization_handler.handle_authorization_request(client=client)
        return response
    except Exception as err:
        utils.log_error(err)
        return SERVER_ERROR_MESSAGE.format(error=err)
Beispiel #13
0
def webhook():
    try:
        handle_web_hook(db=DB.get_instance(consts.db_path))
    except Exception as err:
        utils.log_error(err)

    return make_response("", 200)
    def initialize(self):

        self.ptr_name = self.config['pointer']
        self.stream_table_names = {}
        self.checked_tables = {}

        if not readconf.check_db_config(self.config):
            return False

        self.sql_file = self.config['sql']
        self.conn_str = "host=" + self.config[
            'host'] + " dbname=" + self.config[
                'dbname'] + " user="******" password="******"Couldn't create read pointers table")
            return False

        row = self.fetch_row(
            "SELECT file, pos FROM pointers WHERE pointer=%s;",
            (self.ptr_name, ))

        if row is None:
            return False

        self.pointer = (0, 0)
        if len(row) > 0:
            self.pointer = (row[0], row[1])

        return True
Beispiel #15
0
def fill_video_list(videos):
    try:
        ok = True
        for v in videos:
            listitem = xbmcgui.ListItem(label=v.get_title(),
                                        iconImage=v.get_thumbnail(),
                                        thumbnailImage=v.get_thumbnail())
            listitem.setInfo('video', v.get_xbmc_list_item())

            # Build the URL for the program, including the list_info
            url = "%s?%s" % (sys.argv[0], v.make_xbmc_url())

            # Add the program item to the list
            ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                             url=url,
                                             listitem=listitem,
                                             isFolder=False)
        xbmcplugin.setContent(handle=int(sys.argv[1]), content='episodes')
    except:
        # user cancelled dialog or an error occurred
        d = xbmcgui.Dialog()
        msg = utils.dialog_error("Unable to fetch video list")
        d.ok(*msg)
        utils.log_error()
    return ok
Beispiel #16
0
def play_channel():
    utils.log("url play channel: " + sys.argv[0])

    try:
        handle = int(sys.argv[1])
        params_str = sys.argv[2]
        params = utils.get_url(params_str)

        data_url = params['data_url']
        rtmp_url = api.get_stream_url(data_url)

        playitem = xbmcgui.ListItem(path=rtmp_url)
        playitem.setProperty('inputstreamaddon', 'inputstream.adaptive')
        playitem.setProperty('inputstream.adaptive.manifest_type', 'hls')
        playitem.setContentLookup(False)
        xbmcplugin.setResolvedUrl(handle, True, playitem)

    except Exception as e:
        d = xbmcgui.Dialog()
        d.ok("Shortcut Error", str(e))
        utils.log_error()
    except:
        d = xbmcgui.Dialog()
        d.ok("Shortcut Error", "Unable to fetch listing")
        utils.log_error()
Beispiel #17
0
def play(url):

	iview_config = comm.get_config()
	auth = comm.get_auth(iview_config)

	p = classes.Program()
	p.parse_xbmc_url(url)

	try:
		# Playpath shoud look like this:
		# 	Akamai: mp4:flash/playback/_definst_/itcrowd_10_03_02
		playpath = auth['playpath_prefix'] + p.url
		if playpath.split('.')[-1] == 'mp4':
			playpath = 'mp4:' + playpath
	
		# Strip off the .flv or .mp4
		playpath = playpath.split('.')[0]
	
		# rtmp://cp53909.edgefcs.net/ondemand?auth=daEbjbeaCbGcgb6bedYacdWcsdXc7cWbDda-bmt0Pk-8-slp_zFtpL&aifp=v001 
		# playpath=mp4:flash/playback/_definst_/kids/astroboy_10_01_22 swfurl=http://www.abc.net.au/iview/images/iview.jpg swfvfy=true
		rtmp_url = "%s?auth=%s playpath=%s swfurl=%s swfvfy=true" % (auth['rtmp_url'], auth['token'], playpath, config.swf_url)
	
		listitem=xbmcgui.ListItem(label=p.get_list_title(), iconImage=p.thumbnail, thumbnailImage=p.thumbnail)
		listitem.setInfo('video', p.get_xbmc_list_item())
	
		xbmc.Player().play(rtmp_url, listitem)
	except:
		# oops print error message
		d = xbmcgui.Dialog()
		message = utils.dialog_error("Unable to play video")
		d.ok(*message)
		utils.log_error();
Beispiel #18
0
def play(url):
    # Show a dialog
    d = xbmcgui.DialogProgress()
    d.create(config.NAME, '')
    d.update(20, 'Fetching video parameters...')

    v = classes.Video()
    v.parse_xbmc_url(url)

    try:
        d.update(40, 'Fetching video URL...')
        base_url = get_url(v.id)

        d.update(60, 'Fetching video URL...')
        video_url = quality_url(base_url)

        d.update(80, 'Building playlist...')
        listitem = xbmcgui.ListItem(label=v.get_title(),
                                    iconImage=v.get_thumbnail(),
                                    thumbnailImage=v.get_thumbnail())
        listitem.setInfo('video', v.get_xbmc_list_item())

        d.update(99, 'Starting video...')
        xbmc.Player().play(video_url, listitem)
    except:
        # user cancelled dialog or an error occurred
        d = xbmcgui.Dialog()
        message = utils.dialog_error("Unable to play video")
        d.ok(*message)
        utils.log_error()
Beispiel #19
0
def get_history(org: str, repo: str,
                target: str):  # instead of these two use one 'repo_url'?
    if target == 'issues':
        return _get_issues(org, repo)
    else:
        check_dir_exist(org, repo)
        print(f'Getting {target}...')
        url = API_MAIN_URL + REPO_END.format(org, repo) + f'/{target}'
        events = requests.get(url, auth=AUTH_PARAMS)
        if events.status_code == 200:
            events_json = events.json()
            if 'Link' in events.headers:
                p = re.compile('page=([0-9]+)>; rel="last"')
                last_page = int(p.search(events.headers['Link']).group(1))
                for page in tqdm(range(2, last_page + 1),
                                 desc='Parsing pages'):
                    events = requests.get(url,
                                          params={'page': page},
                                          auth=AUTH_PARAMS)
                    try:
                        events.raise_for_status()
                    except HTTPError as e:
                        process_http_error(e)
                        events = requests.get(url,
                                              params={'page': page},
                                              auth=AUTH_PARAMS)
                        if events.status_code != 200:
                            print(events.json())
                            exit(1)

                    events_json.extend(events.json())
        else:
            log_error(events.json())
            exit(1)
        return events_json
Beispiel #20
0
def fill_programs_list(programs):
    try:
        ok = True
        for prog in programs:

            p = prog
            #p = comm.get_program(prog.url_path)
            item_info = p.get_xbmc_list_item()
            item_url = p.make_xbmc_url()

            listitem = xbmcgui.ListItem(label=p.get_list_title(),
                                        iconImage=p.get_thumbnail(),
                                        thumbnailImage=p.get_thumbnail())
            listitem.setInfo('video', item_info)

            # Build the URL for the program, including the list_info
            url = "%s?play=true&%s" % (sys.argv[0], item_url)

            # Add the program item to the list
            ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                             url=url,
                                             listitem=listitem,
                                             isFolder=False,
                                             totalItems=len(programs))
    except:
        # user cancelled dialog or an error occurred
        d = xbmcgui.Dialog()
        title = "%s Error" % config.NAME
        msg = utils.dialog_error("Unable to fetch listing")
        d.ok(*msg)
        utils.log_error()
        ok = False
    return ok
Beispiel #21
0
def call_lvm(command, debug=False):
	"""
	Call an executable and return a tuple of exitcode, stdout, stderr
	:param command:     Command to execute
	:param debug:       Dump debug to stdout
	"""
	# print 'STACK:'
	# for line in traceback.format_stack():
	#    print line.strip()

	# Prepend the full lvm executable so that we can run different versions
	# in different locations on the same box
	command.insert(0, cfg.LVM_CMD)

	process = Popen(command, stdout=PIPE, stderr=PIPE, close_fds=True)
	out = process.communicate()

	stdout_text = bytes(out[0]).decode("utf-8")
	stderr_text = bytes(out[1]).decode("utf-8")

	if debug or process.returncode != 0:
		_debug_c(command, process.returncode, (stdout_text, stderr_text))

	if process.returncode == 0:
		if cfg.DEBUG and out[1] and len(out[1]):
			log_error('WARNING: lvm is out-putting text to STDERR on success!')
			_debug_c(command, process.returncode, (stdout_text, stderr_text))

	return process.returncode, stdout_text, stderr_text
def make_category_list():

    try:
        iview_config = comm.get_config()
        categories = comm.get_categories(iview_config)
        categories = sorted(categories, key=lambda k: k['name'].lower())
        categories.insert(0, {'name': 'All', 'keyword': '0-z'})

        ok = True
        for g in categories:
            url = "%s?category_id=%s" % (sys.argv[0], g['keyword'])
            listitem = xbmcgui.ListItem(g['name'])

            # Add the program item to the list
            ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                             url=url,
                                             listitem=listitem,
                                             isFolder=True)

        xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
        xbmcplugin.setContent(handle=int(sys.argv[1]), content='episodes')
    except:
        d = xbmcgui.Dialog()
        message = utils.dialog_error("Unable to fetch listing")
        d.ok(*message)
        utils.log_error()
Beispiel #23
0
def fill_series_list(series_list):
	iview_config = comm.get_config()
	try:
		ok = True
		# enumerate through the list of categories and add the item to the media list
		for s in series_list:
			url = "%s?series_id=%s" % (sys.argv[0], s.id)
			thumbnail = s.get_thumbnail()

			listitem = xbmcgui.ListItem(s.get_list_title(), iconImage=thumbnail, thumbnailImage=thumbnail)
			listitem.setInfo('video', { 'plot' : s.get_description() })

			# add the item to the media list
			ok = xbmcplugin.addDirectoryItem(
				handle=int(sys.argv[1]), 
				url=url, 
				listitem=listitem, 
				isFolder=True, 
				totalItems=len(series_list)
			)

			# if user cancels, call raise to exit loop
			if (not ok): 
				raise

		xbmcplugin.setContent(handle=int(sys.argv[1]), content='tvshows')
	except:
		# user cancelled dialog or an error occurred
		utils.log_error()
		ok = False
	return ok
Beispiel #24
0
def play(url):

    try:
        params = utils.get_url(url)

        if params.has_key('id'):
            video_id = params['id']
            v = comm.get_video(video_id)
        elif params.has_key('url'):
            # New style
            v = classes.Video()
            v.parse_xbmc_url(url)

        # Show a dialog
        d = xbmcgui.DialogProgress()
        d.create(config.NAME, '')
        d.update(50, 'Starting video...')

        listitem = xbmcgui.ListItem(label=v.get_title(),
                                    iconImage=v.get_thumbnail(),
                                    thumbnailImage=v.get_thumbnail())
        listitem.addStreamInfo('video', v.get_xbmc_stream_info())
        listitem.setInfo('video', v.get_xbmc_list_item())

        xbmc.Player().play(v.get_url(), listitem)
    except:
        # user cancelled dialog or an error occurred
        d = xbmcgui.Dialog()
        message = utils.dialog_error("Unable to play video")
        d.ok(*message)
        utils.log_error()
Beispiel #25
0
def process_command(firebase_connection, command):
    utils.print_with_timestamp('Processing command: {}'.format(command))
    if command == ValidCommands.checkDoorStatus.name:
        utils.print_with_timestamp('checkDoorStatus command')
        status = check_door_status()
        firebase_utils.update_status(firebase_connection, utils.get_serial(), status.name)
        print('Door is {}'.format(status.name))
    elif command == ValidCommands.openDoor.name:
        utils.print_with_timestamp('openDoor command')
        open_door()
    elif command == ValidCommands.closeDoor.name:
        utils.print_with_timestamp('closeDoor command')
        close_door()
    elif command == ValidCommands.calibrate.name:
        utils.print_with_timestamp('calibrate command')
        calibrate(firebase_connection)
    elif command.split('-')[0] == ValidCommands.updateLogFile.name:
        # Proper structure of this firebase command is "udateLogFile-YYY_MM_DD"
        # If the date poriton is omittied ("updateLogFile"), today's file will be uploaded
        # as was previously the case
        if len(command.split('-')) > 1:
            date = command.split('-')[1]
        else:
            # Create today's date
            date = datetime.datetime.strftime(datetime.datetime.now(), '%Y_%m_%d')
        utils.print_with_timestamp('updateLogFile command')
        utils.upload_log_files(DRIVE_AUTH, desired_date=date)
    else:
        utils.print_with_timestamp('invalid command')
        utils.log_error('processed-invalid-command', data=command)
Beispiel #26
0
def make_programs_list(url):

    try:
        params = utils.get_url(url)
        iview_config = comm.get_config()
        programs = comm.get_series_items(iview_config, params["series_id"])

        ok = True
        for p in programs:
            listitem = xbmcgui.ListItem(label=p.get_list_title(),
                                        iconImage=p.get_thumbnail(),
                                        thumbnailImage=p.get_thumbnail())
            listitem.setInfo('video', p.get_xbmc_list_item())

            if hasattr(listitem, 'addStreamInfo'):
                listitem.addStreamInfo('audio', p.get_xbmc_audio_stream_info())
                listitem.addStreamInfo('video', p.get_xbmc_video_stream_info())

            # Build the URL for the program, including the list_info
            url = "%s?play=true&%s" % (sys.argv[0], p.make_xbmc_url())

            # Add the program item to the list
            ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                             url=url,
                                             listitem=listitem,
                                             isFolder=False,
                                             totalItems=len(programs))

        xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
        xbmcplugin.setContent(handle=int(sys.argv[1]), content='episodes')
    except:
        d = xbmcgui.Dialog()
        msg = utils.dialog_error("Unable to fetch listing")
        d.ok(*msg)
        utils.log_error()
Beispiel #27
0
def perform_sync(sp):
    # print(f'[{current_time()}] Checking playlists for differences...')

    items_jam = get_playlist_tracks(sp, '3KAGyeFZK1uDfet9hOd6gU')
    items_jelly = get_playlist_tracks(sp, '6cHhVGOS9UBamBzw53SQZL')
    if items_jam and items_jelly:
        # list of all track IDs in jam
        tracks_jam = [item['track']['id'] for item in items_jam]
        # all tracks that are in jelly but not tracks_jam
        # dict of id:name so i can also print names
        unsynced_tracks = {
            item['track']['id']: item['track']['name']
            for item in items_jelly if item['track']['id'] not in tracks_jam
        }

        # add jelly songs not in jams to jams
        if len(unsynced_tracks) >= 1:
            try:
                sp.playlist_add_items(playlist_id='3KAGyeFZK1uDfet9hOd6gU',
                                      items=list(unsynced_tracks.keys()))

                log(f'Synced tracks: {list(unsynced_tracks.values())}')
            except RequestException as e:
                log_error(f'Caught exception while syncing tracks: {e}')
            except SpotifyException as e:
                log_error(f'Caught exception while syncing tracks: {e}')
Beispiel #28
0
def make_channel_list():
    utils.log("url-make-channel" + sys.argv[0])

    try:
        channels = api.get_channels()

        ok = True
        for c in channels:
            listitem = xbmcgui.ListItem(label=c['name'])
            listitem.setInfo('video', {'title': c['name']})
            listitem.setIconImage(api.API_BASEURL + "/" + c['logo'])
            listitem.setThumbnailImage(api.API_BASEURL + "/" + c['thumb'])
            listitem.setProperty('IsPlayable', "true")

            # Build the URL for the program, including the list_info
            url = "%s?play=true&data_url=%s" % (sys.argv[0], c['id'])

            # Add the program item to the list
            ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                             url=url,
                                             listitem=listitem,
                                             isFolder=False,
                                             totalItems=len(channels))

        xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
        xbmcplugin.setContent(handle=int(sys.argv[1]), content='episodes')
    except:
        d = xbmcgui.Dialog()
        msg = utils.dialog_error("Unable to fetch listing")
        d.ok(*msg)
        utils.log_error()
Beispiel #29
0
def make_series_list():
    try:
        series_list = comm.get_index()
        series_list.sort()

        ok = True
        for s in series_list:
            url = "%s?series_id=%s" % (sys.argv[0], s.id)
            thumbnail = s.get_thumbnail()

            listitem = xbmcgui.ListItem(s.get_title(),
                                        iconImage=thumbnail,
                                        thumbnailImage=thumbnail)
            listitem.setInfo('video', {'plot': s.get_description()})

            # add the item to the media list
            ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                             url=url,
                                             listitem=listitem,
                                             isFolder=True)

        xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
        xbmcplugin.setContent(handle=int(sys.argv[1]), content='tvshows')
    except:
        d = xbmcgui.Dialog()
        message = utils.dialog_error("Unable to fetch listing")
        d.ok(*message)
        utils.log_error()
Beispiel #30
0
def make_list():

    try:
        # Show a dialog
        pDialog = xbmcgui.DialogProgress()
        pDialog.create('AFL Video', 'Getting Round List')
        pDialog.update(50)

        for r in config.ROUNDS_2014:
            listitem = xbmcgui.ListItem(label=r['name'])
            url = "%s?round_id=%s" % (sys.argv[0], r['id'])

            # Add the item to the list
            ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                             url=url,
                                             listitem=listitem,
                                             isFolder=True,
                                             totalItems=len(
                                                 config.ROUNDS_2014))

        # send notification we're finished, successfully or unsuccessfully
        xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
    except:
        # user cancelled dialog or an error occurred
        d = xbmcgui.Dialog()
        message = utils.dialog_error("Unable to fetch round list")
        d.ok(*message)
        utils.log_error()
def fill_category_list(category_list):
	iview_config = comm.get_config()
	try:
		ok = True
		# enumerate through the list of categories and add the item to the media list
		for g in category_list:
			url = "%s?category_id=%s" % (sys.argv[0], g['keyword'])
			listitem = xbmcgui.ListItem(g['name'])

			# add the item to the media list
			ok = xbmcplugin.addDirectoryItem(
				handle=int(sys.argv[1]),
				url=url,
				listitem=listitem,
				isFolder=True,
				totalItems=len(category_list)
			)

			# if user cancels, call raise to exit loop
			if (not ok):
				raise

	except:
		# user cancelled dialog or an error occurred
		utils.log_error()
		ok = False
	return ok
Beispiel #32
0
    async def prompt_task(self):
        """Once a day, grabs a prompt from google sheets and posts it to the defined prompts chat, if enabled."""
        if self.service is None:
            raise dutils.StopEventLoop("No google service, prompt task quitting")
        prompt_sheet_id = "1bL0mSDGK4ypn8wioQCBqkZH47HmYp6GnmJbXkIOg2fA"
        values = self.get_spreadsheet(prompt_sheet_id, "Form Responses 1!B:E")
        possibilities = []
        values = list(values)
        for item in values:
            if len(item[3:]) == 0:
                possibilities.append(item)
        prompt = random.choice(possibilities)

        log.debug(prompt)
        out = f"__Daily Prompt {dt.date.today().strftime('%m/%d')}__\n\n"
        prompt[0] = prompt[0].strip("\"")
        out += f"{prompt[0]}\n\n"
        original = "Original prompt" if prompt[1].upper() == "YES" else "Submitted"
        out += f"({original} by {prompt[2]})"
        for guild in self.bot.guilds:
            options = self.database.get_guild_options(guild.id)
            if not options.writing_prompts:
                continue
            for channel in guild.channels:
                if channel.name == options.prompts_channel:
                    try:
                        await channel.send(out)
                    except Exception as e:
                        utils.log_error(log, logging.WARNING, e, "Error while attempting to send daily prompt")

        prompt.append("POSTED")
        self.set_spreadsheet(prompt_sheet_id, [prompt],
                             f"Form Responses 1!B{values.index(prompt) + 1}:E{values.index(prompt) + 1}")
Beispiel #33
0
def play(params):
    __addon__ = xbmcaddon.Addon()

    p = utils.get_url(params)

    # Show a dialog
    d = xbmcgui.DialogProgress()
    d.create(config.NAME, "Starting %s..." % p['name'])

    try:
        thumb = os.path.join(__addon__.getAddonInfo('path'), "resources",
                             "img", "%s.jpg" % p['id'])
        labels = {"title": p['name'], "artist": "AFL Radio", "genre": "Sport"}
        listitem = xbmcgui.ListItem(p['name'])
        listitem.setInfo(type='music', infoLabels=labels)
        listitem.setThumbnailImage(thumb)

        # PAPlayer or AUTO fails here for some absurd reason
        xbmc.Player(xbmc.PLAYER_CORE_DVDPLAYER).play(p['url'], listitem)
    except:
        # user cancelled dialog or an error occurred
        d = xbmcgui.Dialog()
        message = utils.dialog_error("Unable to play %s" % p['name'])
        d.ok(*message)
        utils.log_error()
def fill_series_list(series_list):
    iview_config = comm.get_config()
    try:
        ok = True
        # enumerate through the list of categories and add the item to the media list
        for s in series_list:
            url = "%s?series_id=%s" % (sys.argv[0], s.id)
            thumbnail = s.get_thumbnail()

            listitem = xbmcgui.ListItem(s.get_list_title(),
                                        iconImage=thumbnail,
                                        thumbnailImage=thumbnail)
            listitem.setInfo('video', {'plot': s.get_description()})

            # add the item to the media list
            ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                             url=url,
                                             listitem=listitem,
                                             isFolder=True,
                                             totalItems=len(series_list))

            # if user cancels, call raise to exit loop
            if (not ok):
                raise

        xbmcplugin.setContent(handle=int(sys.argv[1]), content='tvshows')
    except:
        # user cancelled dialog or an error occurred
        utils.log_error()
        ok = False
    return ok
def notify_users(firebase_connection, raspi_id, api_key, status):
    utils.print_with_timestamp('Sending notification to user')
    push_service = pyfcm.FCMNotification(api_key=api_key)

    utils.log_usage(status)

    # Loop until we get a device ID.
    phone_ids = None
    while not phone_ids:
        phone_ids = firebase_connection.get('devices/{}/phone_IDs'.format(raspi_id), None)
        if not phone_ids:
            time.sleep(1)

    results = []
    for phone in phone_ids.keys():
        if status == 'open':
            status = 'opened'

        timestamp = datetime.datetime.now().strftime('%I:%M %p on %A %b %d, %Y')
        msg = 'Your door was {} at {}'.format(status, timestamp)
        result = push_service.notify_single_device(registration_id=phone,
            message_title='Garage door update', message_body=msg, sound="Default")

        # TO-DO: Try to send notifications multiple times if there is a failure
        if not result['success']:
            utils.print_with_timestamp('notification failed to send')
            utils.log_error('notification-failure', data=result)

        results.append(result)

    return results
Beispiel #36
0
def make_list(round_id):

	utils.log("Fetching match list for round %s..." % round_id)

	# Show a dialog
	pDialog = xbmcgui.DialogProgress()
	pDialog.create(config.NAME, 'Fetching match list...')

	try:
		matches = comm.get_round(round_id)
		utils.log("Found %s matches" % len(matches))

		ok = True
		for m in matches:

			listitem = xbmcgui.ListItem(label=m['name'])
			url = "%s?round_id=%s&match_id=%s" % (sys.argv[0], m['round_id'], m['id'])

			# Add the item to the list
			ok = xbmcplugin.addDirectoryItem(
						handle = int(sys.argv[1]),
						url = url,
						listitem = listitem,
						isFolder = True,
						totalItems = len(matches)
					)

		# send notification we're finished, successfully or unsuccessfully
		xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
	except:
		# user cancelled dialog or an error occurred
		d = xbmcgui.Dialog()
		msg = utils.dialog_error("Unable to fetch match list")
		d.ok(*msg)
		utils.log_error();
def fill_category_list(category_list):
    iview_config = comm.get_config()
    try:
        ok = True
        # enumerate through the list of categories and add the item to the media list
        for g in category_list:
            url = "%s?category_id=%s" % (sys.argv[0], g['keyword'])
            listitem = xbmcgui.ListItem(g['name'])

            # add the item to the media list
            ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                             url=url,
                                             listitem=listitem,
                                             isFolder=True,
                                             totalItems=len(category_list))

            # if user cancels, call raise to exit loop
            if (not ok):
                raise

    except:
        # user cancelled dialog or an error occurred
        utils.log_error()
        ok = False
    return ok
Beispiel #38
0
def call_lvm(command, debug=False):
	"""
	Call an executable and return a tuple of exitcode, stdout, stderr
	:param command:     Command to execute
	:param debug:       Dump debug to stdout
	"""
	# print 'STACK:'
	# for line in traceback.format_stack():
	#    print line.strip()

	# Prepend the full lvm executable so that we can run different versions
	# in different locations on the same box
	command.insert(0, cfg.LVM_CMD)

	process = Popen(command, stdout=PIPE, stderr=PIPE, close_fds=True,
					env=os.environ)
	out = process.communicate()

	stdout_text = bytes(out[0]).decode("utf-8")
	stderr_text = bytes(out[1]).decode("utf-8")

	if debug or process.returncode != 0:
		_debug_c(command, process.returncode, (stdout_text, stderr_text))

	if process.returncode == 0:
		if cfg.args and cfg.args.debug and out[1] and len(out[1]) and \
				'help' not in command:
			log_error('WARNING: lvm is out-putting text to STDERR on success!')
			_debug_c(command, process.returncode, (stdout_text, stderr_text))

	return process.returncode, stdout_text, stderr_text
Beispiel #39
0
def fill_programs_list(programs):
	try:	
		ok = True
		for prog in programs:

			p = prog
			#p = comm.get_program(prog.url_path)
			item_info = p.get_xbmc_list_item()
			item_url = p.make_xbmc_url()

			listitem = xbmcgui.ListItem(label=p.get_list_title(), iconImage=p.get_thumbnail(), thumbnailImage=p.get_thumbnail())
			listitem.setInfo('video', item_info)

			# Build the URL for the program, including the list_info
			url = "%s?play=true&%s" % (sys.argv[0], item_url)

			# Add the program item to the list
			ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=False, totalItems=len(programs))
	except:
		# user cancelled dialog or an error occurred
		d = xbmcgui.Dialog()
		title = "%s Error" % config.NAME
		msg = utils.dialog_error("Unable to fetch listing")
		d.ok(*msg)
		utils.log_error()
		ok = False
	return ok
Beispiel #40
0
def make_list(round_id, match_id):

	__addon__ = xbmcaddon.Addon()
	quality = __addon__.getSetting('QUALITY')

	utils.log("Fetching video list for %s..." % match_id)

	# Show a dialog
	pDialog = xbmcgui.DialogProgress()
	pDialog.create(config.NAME, 'Fetching video list...')

	try:
		# fill media list
		videos = comm.get_match_video(round_id, match_id, quality)
		if videos:
			ok = True
			for v in videos:
				listitem = xbmcgui.ListItem(label=v['name'])	
				# I think this might help prevent the stream from closing early
				url = v['url'] + '?start=0'
				xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=False)
			xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
		else:
			d = xbmcgui.Dialog()
			msg = utils.dialog_message("No videos found. Replays are only available 24-48 hours after match has been played. Please try again later.")
			d.ok(*msg)
	except:
		# user cancelled dialog or an error occurred
		d = xbmcgui.Dialog()
		msg = utils.dialog_error("Unable to fetch video list")
		d.ok(*msg)
		utils.log_error();
Beispiel #41
0
 def track_process(self):
     if self.playing:
         # Don't do anything if the engine is busy playing a file
         return None
     
     filename = self._playing_file(self.config['tracker_process'], self.config['searchdir'])
     
     if filename:
         # Do a regex to the filename to get
         # the show title and episode number
         reg = re.compile(r"(\[.+\])?([ \w\d\-,@.:;!\?]+) - ([ \d]+) ")
         show_raw = filename.replace("_"," ").replace("v2","").strip()
         show_match = reg.match(show_raw)
         if not show_match:
             self.msg.warn(self.name, 'Regex error. Check logs.')
             utils.log_error("[Regex error] Tracker: %s / Dir: %s / Processed filename: %s\n" % (self.config['tracker_process'], self.config['searchdir'], show_raw))
             return None
         
         show_title = show_match.group(2).strip()
         show_ep = int(show_match.group(3).strip())
         
         # Use difflib to see if the show title is similar to
         # one we have in the list
         #print "Looking for ep ",show_ep," of show ",show_title
         highest_ratio = (None, 0)
         for show in self.get_list():
             ratio = self.compare_to_titles(show, show_title)
             if ratio > highest_ratio[1]:
                 highest_ratio = (show, ratio)
                         
         playing_show = highest_ratio[0]
         if highest_ratio[1] > 0.7:
             return (playing_show, show_ep)
         else:
             self.msg.warn(self.name, 'Found player but show not in list.')
             
             #Check if we already looked for this.
             if self.data_handler.is_in_failed_searches(show_title):
                 return None
                 
             results = self.search(show_title)
             highest_ratio = (None, 0)
             for show in results:
                 aliases = self.data_handler.get_all_possible_titles(show['id'])
                 ratio = self.compare_to_titles(show, show_title)
                 if ratio > highest_ratio[1]:
                     highest_ratio = (show, ratio)
             
             if highest_ratio[1] > 0.8:
                 show = highest_ratio[0]
                 self.msg.info(self.name, "Show %s is not in list yet, adding it!" % (show['title']) )
                 self.add_show(show)
                 return (show, show_ep)
             else:
                 self.msg.warn(self.name, "Show %s can't be found in online database" % (show_title) )
                 self.data_handler.failed_searches_add(show_title)
     
     return None
Beispiel #42
0
    def send_server_error(self, status_message="Server Error."):
        """
		Special response indicating a server error
		@param status_message: Message to describe what went wrong
		@type status_message: str
		"""
        utils.log_error()
        # 500 == sever error
        return self.send_response(500, status_message)
Beispiel #43
0
 def get_mjpeg_stream(self):
     self.enable_mjpeg()
     try:
         stream = requests.get(self.mjpeg_url, stream=True).raw
         stream.readline()
         return stream
     except requests.RequestException as e:
         utils.log_error(str(e))
         return None
Beispiel #44
0
 def handle(self, user, handler, sent=None):
     if handler.startswith('!'):
         handler = handler[1:]
         params = [user, sent]
     else:
         params = [user]
     if hasattr(self.__class__.Handlers, handler):
         getattr(self.__class__.Handlers, handler)(*params)
     else:
         utils.log_error("No handler %s in zone %s" % (handler, self.id))
Beispiel #45
0
 def get_text(self, which):
     if which == "triggered":
         return self.text_triggered
     elif which == "escaped":
         return self.text_escaped
     elif which == "disabled":
         return self.text_disabled
     else:
         utils.log_error("Cannot get text for trap %s: %s" % (self.id, which))
         return ""
Beispiel #46
0
	def get(self,oid):
		'''
		The phone is requesting an obituary image
		'''
		try:
			photo_id = self.rget('p', int, True)
			photo_key = ndb.Key(models.Obituary,int(oid),models.Photo,photo_id)
			photo = photo_key.get()
			blob_key = photo.img_key
			blob_info = blobstore.BlobInfo(blob_key)
			self.send_blob(blob_info)
		except Exception,e:
			utils.log_error(e)
			return None
Beispiel #47
0
def check_transaction_status(session_id):
    transaction_status = {}
    try:
        btc_proc = BTCProcessor(True)
        available_coins =  to_btc(float(btc_proc.check_balance()[0]))
        transaction = Transactions.objects.get(session_id=session_id)
        transaction_status['notes_inserted'] = transaction.cash_amount
        transaction_status['btc_amount'] = transaction.btc_amount

    except Transactions.DoesNotExist:
        log_error('check_transaction_status', 'transaction does not exists', session_id=session_id)
    except:
        exc_info = sys.exc_info()
        message = str(exc_info[0]) + ' - ' + str(exc_info[1])
        log_error('check_transaction_status', message, session_id=session_id)
    return transaction_status
def make_category_list():
	try:
		category_list = get_categories()
		category_list = sorted(category_list, key=lambda k: k['name'].lower())
		category_list.insert(0, {'name':'All', 'keyword':'0-z'})

		# fill media list
		ok = fill_category_list(category_list)
	except:
		d = xbmcgui.Dialog()
		message = utils.dialog_error("Unable to fetch listing")
		d.ok(*message)
		utils.log_error();
		ok = False

	# send notification we're finished, successfully or unsuccessfully
	xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
Beispiel #49
0
def make_programs_list(url):
	params = utils.get_url(url)	

	try:
		program_list = comm.get_series(params["series_id"])
		# fill media list
		ok = fill_programs_list(program_list)
	except:
		# oops print error message
		d = xbmcgui.Dialog()
		msg = utils.dialog_error("Unable to fetch listing")
		d.ok(*msg)	
		utils.log_error();
		ok = False

	# send notification we're finished, successfully or unsuccessfully
	xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
Beispiel #50
0
def broadcast_transaction(session_id):
    try:
        transaction = Transactions.objects.get(session_id=session_id)
        transaction.status = Transactions.CASH_INSERTED
        transaction.updated_on = datetime.now()
        transaction.save()

        #TODO: broadcast transaction using BTCProcessor and update transaction in DB
        return {'success': True}
    except Transactions.DoesNotExist:
        log_error('broadcast_transaction', 'transaction does not exists', session_id=session_id)
        raise
    except:
        exc_info = sys.exc_info()
        message = str(exc_info[0]) + ' - ' + str(exc_info[1])
        log_error('broadcast_transaction', message, session_id=session_id)
        raise
Beispiel #51
0
def make_series_list():
	try:
		series_list = comm.get_index()
		series_list.sort()

		# fill media list
		ok = fill_series_list(series_list)
	except:
		# oops print error message
		d = xbmcgui.Dialog()
		message = utils.dialog_error("Unable to fetch listing")
		d.ok(*message)
		utils.log_error();
		ok = False

	# send notification we're finished, successfully or unsuccessfully
	xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
Beispiel #52
0
def make_series_list(url):
	params = utils.get_url(url)

	try:
		series_list = get_series(params["category_id"])
		series_list.sort()

		# fill media list
		ok = fill_series_list(series_list)
	except:
		d = xbmcgui.Dialog()
		message = utils.dialog_error("Unable to fetch listing")
		d.ok(*message)
		utils.log_error();
		ok = False

	# send notification we're finished, successfully or unsuccessfully
	xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
Beispiel #53
0
 async def on_command_error(self, ctx, exception):
     """
         Called upon command error. Handles most things that extend CommandError.
         any un-handled errors it simply logs
     :param ctx: commands.Context object
     :param exception: commands.CommandError child object
     """
     log.debug("OnCommandError Event")
     if isinstance(exception, commands.CommandNotFound):
         if self.database.is_connected() and (ctx.guild is None or
                                              self.database.get_guild_options(ctx.guild.id).fail_message):
             cur_pref = (await self.get_prefix(ctx.message))[0]
             await ctx.send(f"Sorry, I don't understand \"{ctx.invoked_with}\". May I suggest {cur_pref}help?")
     elif isinstance(exception, commands.BotMissingPermissions):
         await ctx.send("I lack the permissions to run that command.")
     elif isinstance(exception, commands.NoPrivateMessage):
         await ctx.send("This command can only be used in a guild. Apologies.")
     elif isinstance(exception, commands.CheckFailure):
         # log.info(f"Woah, {ctx.author} tried to run command {ctx.command} without permissions!")
         await ctx.send("You lack the permission to run that command.")
     elif isinstance(exception, commands.BadArgument):
         await ctx.send(exception)
     elif isinstance(exception, commands.MissingRequiredArgument):
         await ctx.send(f"Missing parameter `{exception.param}`")
     elif isinstance(exception, commands.UserInputError):
         await ctx.send(exception)
     elif isinstance(exception, dutils.NotRegistered):
         await ctx.send(f"User {exception} isn't registered, command could not be executed.")
     elif isinstance(exception, dutils.CustomCommandError):
         await ctx.send(f"Malformed CommandLang syntax: {exception}")
     else:
         timestamp = int(dt.datetime.now().timestamp())
         try:
             if ctx.author.id in self.DEVS:
                 await ctx.send(f"```{exception} | {timestamp}```")
             else:
                 await ctx.send(
                     "Unknown error in command. Please contact devs through `[email protected]` "
                     f"or by posting an issue on the github. Error timestamp: {timestamp}"
                 )
         except Exception as e:
             log.error(e)
         message = f"Ignoring exception `{exception}` in command {ctx.command}. Reference ID: {timestamp}"
         utils.log_error(log, logging.ERROR, exception, message)
def play(url):

	try:
		iview_config = comm.get_config()
		auth = comm.get_auth(iview_config)

		# We don't support Adobe HDS yet, Fallback to RTMP streaming server
		if auth['rtmp_url'].startswith('http://'):
			auth['rtmp_url'] = iview_config['rtmp_url'] or config.akamai_fallback_server
			auth['playpath_prefix'] = config.akamai_playpath_prefix
			utils.log("Adobe HDS Not Supported, using fallback server %s" % auth['rtmp_url'])

		p = classes.Program()
		p.parse_xbmc_url(url)

		# Playpath shoud look like this:
		# 	Akamai: mp4:flash/playback/_definst_/itcrowd_10_03_02
		playpath = auth['playpath_prefix'] + p.url
		if playpath.split('.')[-1] == 'mp4':
			playpath = 'mp4:' + playpath
	
		# Strip off the .flv or .mp4
		playpath = playpath.split('.')[0]
	
		# rtmp://cp53909.edgefcs.net/ondemand?auth=daEbjbeaCbGcgb6bedYacdWcsdXc7cWbDda-bmt0Pk-8-slp_zFtpL&aifp=v001 
		# playpath=mp4:flash/playback/_definst_/kids/astroboy_10_01_22 swfurl=http://www.abc.net.au/iview/images/iview.jpg swfvfy=true
		rtmp_url = "%s?auth=%s playpath=%s swfurl=%s swfvfy=true" % (auth['rtmp_url'], auth['token'], playpath, config.swf_url)
	
		listitem=xbmcgui.ListItem(label=p.get_list_title(), iconImage=p.thumbnail, thumbnailImage=p.thumbnail)
		listitem.setInfo('video', p.get_xbmc_list_item())

		if hasattr(listitem, 'addStreamInfo'):
			listitem.addStreamInfo('audio', p.get_xbmc_audio_stream_info())
			listitem.addStreamInfo('video', p.get_xbmc_video_stream_info())
	
		xbmc.Player().play(rtmp_url, listitem)
	except:
		# oops print error message
		d = xbmcgui.Dialog()
		message = utils.dialog_error("Unable to play video")
		d.ok(*message)
		utils.log_error();
Beispiel #55
0
def fill_video_list(videos):
	try:
		ok = True
		for v in videos:
			listitem = xbmcgui.ListItem(label=v.get_title(), iconImage=v.get_thumbnail(), thumbnailImage=v.get_thumbnail())
			listitem.setInfo('video', v.get_xbmc_list_item())
	
			# Build the URL for the program, including the list_info
			url = "%s?%s" % (sys.argv[0], v.make_xbmc_url())

			# Add the program item to the list
			ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=False)
		xbmcplugin.setContent(handle=int(sys.argv[1]), content='episodes')
	except:
		# user cancelled dialog or an error occurred
		d = xbmcgui.Dialog()
		msg = utils.dialog_error("Unable to fetch video list")
		d.ok(*msg)
		utils.log_error();
	return ok
Beispiel #56
0
 def track_process(self):
     if self.playing:
         # Don't do anything if the engine is busy playing a file
         return None
     
     filename = self._playing_file(self.config['tracker_process'], self.config['searchdir'])
     
     if filename:
         # Do a regex to the filename to get
         # the show title and episode number
         (show_title, show_ep) = utils.analyze(filename)
         if not show_title:
             self.msg.warn(self.name, 'Regex error. Check logs.')
             utils.log_error("[Regex error] Tracker: %s / Dir: %s / Processed filename: %s\n" % (self.config['tracker_process'], self.config['searchdir'], show_raw))
             return None
         
         # Use difflib to see if the show title is similar to
         # one we have in the list
         highest_ratio = (None, 0)
         matcher = difflib.SequenceMatcher()
         matcher.set_seq1(show_title.lower())
         
         # Compare to every show in our list to see which one
         # has the most similar name
         for show in self.get_list():
             titles = self.get_show_titles(show)
             # Make sure to search through all the aliases
             for title in titles:
                 matcher.set_seq2(title.lower())
                 ratio = matcher.ratio()
                 if ratio > highest_ratio[1]:
                     highest_ratio = (show, ratio)
         
         playing_show = highest_ratio[0]
         if highest_ratio[1] > 0.7:
             return (playing_show, show_ep)
         else:
             self.msg.warn(self.name, 'Found player but show not in list.')
     
     return None
def play_channel():
    utils.log("url play channel: " + sys.argv[0])

    try:
        handle = int(sys.argv[1])
        params_str = sys.argv[2]
        params = utils.get_url(params_str)

        data_url = params['data_url']
        rtmp_url = api.get_stream_url(data_url)

        playitem = xbmcgui.ListItem(path=rtmp_url)
        playitem.setProperty('inputstreamaddon', 'inputstream.adaptive')
        playitem.setProperty('inputstream.adaptive.manifest_type', 'hls')
        playitem.setContentLookup(False)
        xbmcplugin.setResolvedUrl(handle, True, playitem)

    except:
        d = xbmcgui.Dialog()
        msg = utils.dialog_error("Unable to fetch listing")
        d.ok(*msg)
        utils.log_error()
Beispiel #58
0
def main():
    config = parse_args()
    _check_filepath(config)

    with BZ2DateSeeker(config.archive, config.date_format) as seeker:
        try:
            block = seeker.seek(config.date)
        except ArchiveError as e:
            log_error(e.message)

        if not block:
            log_error('Cannot find the date into this archive.')

        if not config.offset_only:
            seeker.output_date(config.date, block.start)
        else:
            mask = '%s' if not config.hex else '0x%x'
            start_offset = mask % block.start
            end_offset = mask % block.end

            print 'Start offset of the block in the archive: %s' % start_offset
            print 'End offset of the block in the archive: %s' % end_offset
Beispiel #59
0
def pv_retrieve_with_segs(device=None):
	d = []
	err = ""
	out = ""
	rc = 0

	columns = ['pv_name', 'pv_uuid', 'pv_fmt', 'pv_size', 'pv_free',
				'pv_used', 'dev_size', 'pv_mda_size', 'pv_mda_free',
				'pv_ba_start', 'pv_ba_size', 'pe_start', 'pv_pe_count',
				'pv_pe_alloc_count', 'pv_attr', 'pv_tags', 'vg_name',
				'vg_uuid', 'pv_seg_start', 'pvseg_size', 'segtype']

	# Lvm has some issues where it returns failure when querying pvs when other
	# operations are in process, see:
	# https://bugzilla.redhat.com/show_bug.cgi?id=1274085
	for i in range(0, 10):
		cmd = _dc('pvs', ['-o', ','.join(columns)])

		if device:
			cmd.extend(device)

		rc, out, err = call(cmd)

		if rc == 0:
			d = parse_column_names(out, columns)
			break
		else:
			time.sleep(0.2)
			log_debug("LVM Bug workaround, retrying pvs command...")

	if rc != 0:
		msg = "We were unable to get pvs to return without error after " \
			"trying 10 times, RC=%d, STDERR=(%s), STDOUT=(%s)" % \
			(rc, err, out)
		log_error(msg)
		raise RuntimeError(msg)

	return d