def check_host_reachability(): if not can_check_reachability(current_user): abort(401) urls = [] # Below information is directly from the page and # may not have been saved yet. hostname = request.args.get('hostname') platform = request.args.get('platform') host_or_ip = request.args.get('host_or_ip') username = request.args.get('username') password = request.args.get('password') enable_password = request.args.get('enable_password') connection_type = request.args.get('connection_type') port_number = request.args.get('port_number') jump_host_id = request.args.get('jump_host') # If a jump host exists, create the connection URL if int(jump_host_id) > 0: db_session = DBSession() jump_host = get_jump_host_by_id(db_session=db_session, id=jump_host_id) if jump_host is not None: url = make_url(connection_type=jump_host.connection_type, host_username=jump_host.username, host_password=jump_host.password, host_or_ip=jump_host.host_or_ip, port_number=jump_host.port_number) urls.append(url) db_session = DBSession() # The form is in the edit mode and the user clicks Validate Reachability # If there is no password specified, get it from the database. if is_empty(password) or is_empty(enable_password): host = get_host(db_session, hostname) if host is not None: password = host.connection_param[0].password enable_password = host.connection_param[0].enable_password system_option = SystemOption.get(db_session) if system_option.enable_default_host_authentication: if not is_empty(system_option.default_host_username) and not is_empty( system_option.default_host_password): if system_option.default_host_authentication_choice == DefaultHostAuthenticationChoice.ALL_HOSTS or \ (system_option.default_host_authentication_choice == DefaultHostAuthenticationChoice.HOSTS_WITH_NO_SPECIFIED_USERNAME_AND_PASSWORD and is_empty(username) and is_empty(password)): username = system_option.default_host_username password = system_option.default_host_password url = make_url(connection_type=connection_type, host_username=username, host_password=password, host_or_ip=host_or_ip, port_number=port_number, enable_password=enable_password) urls.append(url) return jsonify({'status': 'OK'}) if is_connection_valid( hostname, urls) else jsonify({'status': 'Failed'})
def make_urls(self, preferred_host_username=None, preferred_host_password=None): urls = [] if len(self.host.connection_param) > 0: connection = self.host.connection_param[0] jump_host_url = '' # Checks if there is a jump server if connection.jump_host_id is not None: try: jump_host = self.db_session.query(JumpHost).filter(JumpHost.id == connection.jump_host_id).first() if jump_host is not None: jump_host_url = make_url( connection_type=jump_host.connection_type, host_username=jump_host.username, host_password=jump_host.password, host_or_ip=jump_host.host_or_ip, port_number=jump_host.port_number) except: pass host_username = connection.username host_password = connection.password if not is_empty(preferred_host_username) and not is_empty(preferred_host_password): host_username = preferred_host_username host_password = preferred_host_password else: system_option = SystemOption.get(self.db_session) if system_option.enable_default_host_authentication: if not is_empty(system_option.default_host_username) and not is_empty(system_option.default_host_password): if system_option.default_host_authentication_choice == DefaultHostAuthenticationChoice.ALL_HOSTS or \ (system_option.default_host_authentication_choice == DefaultHostAuthenticationChoice.HOSTS_WITH_NO_SPECIFIED_USERNAME_AND_PASSWORD and is_empty(host_username) and is_empty(host_password)): host_username = system_option.default_host_username host_password = system_option.default_host_password for host_or_ip in connection.host_or_ip.split(','): for port_number in connection.port_number.split(','): host_urls = [] if not is_empty(jump_host_url): host_urls.append(jump_host_url) host_urls.append(make_url( connection_type=connection.connection_type, host_username=host_username, host_password=host_password, host_or_ip=host_or_ip, port_number=port_number, enable_password=connection.enable_password)) urls.append(host_urls) return urls
def make_urls(self, preferred_host_username=None, preferred_host_password=None): urls = [] if len(self.host.connection_param) > 0: connection = self.host.connection_param[0] jump_host_url = '' # Checks if there is a jump server if connection.jump_host_id is not None: try: jump_host = self.db_session.query(JumpHost).filter(JumpHost.id == connection.jump_host_id).first() if jump_host is not None: jump_host_url = make_url( connection_type=jump_host.connection_type, host_username=jump_host.username, host_password=jump_host.password, host_or_ip=jump_host.host_or_ip, port_number=jump_host.port_number) except: pass host_username = connection.username host_password = connection.password if not is_empty(preferred_host_username) and not is_empty(preferred_host_password): host_username = preferred_host_username host_password = preferred_host_password else: system_option = SystemOption.get(self.db_session) if system_option.enable_default_host_authentication: if not is_empty(system_option.default_host_username) and not is_empty(system_option.default_host_password): if system_option.default_host_authentication_choice == DefaultHostAuthenticationChoice.ALL_HOSTS or \ (system_option.default_host_authentication_choice == DefaultHostAuthenticationChoice.HOSTS_WITH_NO_SPECIFIED_USERNAME_AND_PASSWORD and is_empty(host_username) and is_empty(host_password)): host_username = system_option.default_host_username host_password = system_option.default_host_password for host_or_ip in connection.host_or_ip.split(','): for port_number in connection.port_number.split(','): host_urls = [] if not is_empty(jump_host_url): host_urls.append(jump_host_url) host_urls.append(make_url( connection_type=connection.connection_type, host_username=host_username, host_password=host_password, host_or_ip=host_or_ip, port_number=port_number)) urls.append(host_urls) return urls
def output_batch_upload_html(self, tips=None): d = { 'list_url' : make_url(global_vars.URL_LP_LIST, {'url' : request.path}), 'create_url' : make_url(global_vars.URL_LP_CREATE, {'url' : request.path}), 'tips' : tips or "", } title = 'Massival %s batch upload' % self.table_class.__name__ render = Render(title, self.tmpl_reader, self.session_info) body_tmpl = self.tmpl_reader.read_file('landingpage_batchupload.tmpl') body_str = Template(body_tmpl).render(**d) return render.gen_output(body_str, {'nav_left' : to_links(self.table_class, 'list')})
def make_category_list(url): utils.log("Making category list") try: params = utils.get_url(url) categories = comm.get_category(params['category']) ok = True if 'children' in categories: for c in categories.get('children', []): if 'children' in c: url = "%s?%s" % (sys.argv[0], utils.make_url({ 'category': params['category'], 'section': c['name']})) elif 'url' in c: url = "%s?%s" % (sys.argv[0], utils.make_url({ 'entries_url': c['url']})) else: #utils.log("Skip category due to no entries or url: '%s'" % c['name']) continue # If no thumbnail, make it an empty string as None makes # XBMC v12 with a TypeError must be unicode or str thumbnail = c.get('thumbnail', '') listitem = xbmcgui.ListItem(label=c['name'], thumbnailImage=thumbnail) ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=True) else: # 'Coming soon' has no children jsonurl = categories['url'] programs = comm.get_entries(jsonurl) for p in sorted(programs): thumbnail = p.get_thumbnail() listitem = xbmcgui.ListItem(label=p.get_list_title(), iconImage=thumbnail, thumbnailImage=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: utils.handle_error()
def output_campaign_check(self, args): url = { 'list_url' : make_url(self.list_url, {'url' : request.path}), 'create_url' : make_url(self.create_url, {'url' : request.path}), } args.update(url) title = '2Fly %s List'%self.table_class.__name__ render = Render(title, self.tmpl_reader, self.session_info) body_tmpl = self.tmpl_reader.read_file(self.campaign_check_tmpl) body_str = Template(body_tmpl).render(**args) return render.gen_output(body_str, {'nav_left' : to_links(self.table_class, 'list')})
def make_category_list(url): utils.log("Making category list") try: params = utils.get_url(url) categories = comm.get_category(params["category"]) ok = True if "children" in categories: for c in categories.get("children", []): if "children" in c: url = "%s?%s" % ( sys.argv[0], utils.make_url({"category": params["category"], "section": c["name"]}), ) elif "url" in c: url = "%s?%s" % (sys.argv[0], utils.make_url({"entries_url": c["url"]})) else: # utils.log("Skip category due to no entries or url: '%s'" % c['name']) continue thumbnail = c.get("thumbnail", None) listitem = xbmcgui.ListItem(label=c["name"], iconImage=thumbnail, thumbnailImage=thumbnail) ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=True) else: # 'Coming soon' has no children jsonurl = categories["url"] programs = comm.get_entries(jsonurl) for p in sorted(programs): thumbnail = p.get_thumbnail() listitem = xbmcgui.ListItem(label=p.get_list_title(), iconImage=thumbnail, thumbnailImage=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: utils.handle_error()
def make_series_list(url): params = utils.get_url(url) try: category = params["category"] series_list = comm.get_programme_from_feed(category) series_list.sort() ok = True for s in series_list: url = "%s?%s" % (sys.argv[0], utils.make_url({ 'series': s.title, 'category': category })) 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: utils.handle_error( 'Unable to fetch program list. Please try again later.')
def make_xbmc_url(self): """ Returns a string which represents the program object, but in a format suitable for passing as a URL. """ d = {} if self.id: d['id'] = self.id if self.title: d['title'] = self.title if self.description: d['description'] = self.description if self.genre: d['genre'] = self.genre if self.duration: d['duration'] = self.duration if self.season: d['season'] = self.season if self.date: d['date'] = self.date.strftime("%Y-%m-%d %H:%M:%S") if self.thumbnail: d['thumbnail'] = self.thumbnail if self.url: d['url'] = self.url if self.ooyalaid: d['ooyalaid'] = self.ooyalaid if self.isdummy: d['isdummy'] = self.isdummy return utils.make_url(d)
def make_xbmc_url(self): """ Returns a string which represents the program object, but in a format suitable for passing as a URL. """ d = {} if self.id: d['id'] = self.id if self.title: d['title'] = self.title if self.episode_title: d['episode_title'] = self.episode_title if self.description: d['description'] = self.description if self.duration: d['duration'] = self.duration if self.category: d['category'] = self.category if self.rating: d['rating'] = self.rating if self.date: d['date'] = self.date.strftime("%d/%m/%Y %H:%M:%S") if self.thumbnail: d['thumbnail'] = self.thumbnail if self.url_path: d['url_path'] = self.url_path return utils.make_url(d)
def list_rounds(params): """ create list of rounds for the season. If in current year then only create to current date""" listing = [] params['action'] = 'listrounds' if params['year'] == '2017': no_of_rounds = utils.get_round_no() else: no_of_rounds = 30 for i in range(no_of_rounds, 0, -1): params['rnd'] = str(i) if i <= 26: li = xbmcgui.ListItem('Round ' + str(i)) elif i == 27: li = xbmcgui.ListItem('Finals Week 1') elif i == 28: li = xbmcgui.ListItem('Semi Finals') elif i == 29: li = xbmcgui.ListItem('Preliminary Finals') elif i == 30: li = xbmcgui.ListItem('Grand Final') url = '{0}?{1}'.format(_url, utils.make_url(params)) is_folder = True listing.append((url, li, is_folder)) xbmcplugin.addDirectoryItems(_handle, listing, len(listing)) xbmcplugin.endOfDirectory(_handle)
def popular_messages(messages, cinfo, uinfo): """ given a list of lists where each list is [reaction count, ts, cid, uid] convert to dict with 'count', 'dt', 'channel', 'cid', 'uid', 'user', 'url' """ ret = [] for message in messages: if not isinstance(message, list): continue (reactions, ts, cid, uid) = message ret.append({ 'count': reactions, 'dt': time.strftime("%m/%d/%Y %H:%M", time.localtime(int(float(ts)))), 'channel': cinfo[cid]['name'], 'user': uinfo[uid]['label'], 'uid': uid, 'cid': cid, 'url': utils.make_url(cid, ts) }) return ret
def make_xbmc_url(self): """ Returns a string which represents the program object, but in a format suitable for passing as a URL. """ d = {} if self.id: d["id"] = self.id if self.title: d["title"] = self.title if self.episode_title: d["episode_title"] = self.episode_title if self.description: d["description"] = self.description if self.duration: d["duration"] = self.duration if self.category: d["category"] = self.category if self.rating: d["rating"] = self.rating if self.date: d["date"] = self.date.strftime("%d/%m/%Y %H:%M:%S") if self.thumbnail: d["thumbnail"] = self.thumbnail if self.url_path: d["url_path"] = self.url_path return utils.make_url(d)
def list_stations(): __addon__ = xbmcaddon.Addon() # Show a dialog pDialog = xbmcgui.DialogProgress() pDialog.create(config.NAME, 'Fetching station list...') try: stations = comm.get_stations() if not stations: d = xbmcgui.Dialog() msg = utils.dialog_message( "No stations found. This is usually because no matches are currently being played. Please try again later." ) d.ok(*msg) return utils.log("Found %s stations" % len(stations)) ok = True for s in stations: station_name = utils.get_station_name(s['id']) thumb = os.path.join(__addon__.getAddonInfo('path'), "resources", "img", "%s.jpg" % s['id']) listitem = xbmcgui.ListItem(station_name) labels = {"title": station_name, "genre": "Sport"} listitem.setInfo(type='music', infoLabels=labels) listitem.setThumbnailImage(thumb) params = utils.make_url({ "id": s['id'], "name": station_name, "url": s['streamURL'] }) url = "%s?%s" % (sys.argv[0], params) # Add the item to the list ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=True, totalItems=len(stations)) 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 station list") d.ok(*msg) utils.log_error()
def get(self, key): if key in self.users: return self.users[key] response = self.table.get_item(Key={'slack_uid': key}) item = response.get("Item") if item: item['ts'] = int(item['ts']) item['url'] = utils.make_url(item['slack_cid'], item['message_id']) item['days'] = self.days(item['ts']) item['date'] = self.date(item['ts']) self.users[key] = item return item
def urls(self): _urls = [] if len(self.connection_param) > 0: connection = self.connection_param[0] db_session = DBSession() # Checks if there is a jump server if connection.jump_host_id is not None: try: jump_host = db_session.query(JumpHost).filter( JumpHost.id == connection.jump_host_id).first() if jump_host is not None: _urls.append( make_url(connection_type=jump_host.connection_type, username=jump_host.username, password=jump_host.password, host_or_ip=jump_host.host_or_ip, port_number=jump_host.port_number)) except: logger.exception('Host.urls() hits exception') default_username = None default_password = None system_option = SystemOption.get(db_session) if system_option.enable_default_host_authentication: default_username = system_option.default_host_username default_password = system_option.default_host_password _urls.append( make_url(connection_type=connection.connection_type, username=connection.username, password=connection.password, host_or_ip=connection.host_or_ip, port_number=connection.port_number, default_username=default_username, default_password=default_password)) return _urls
def urls(self): _urls = [] if len(self.connection_param) > 0: connection = self.connection_param[0] db_session = DBSession() # Checks if there is a jump server if connection.jump_host_id is not None: try: jump_host = db_session.query(JumpHost).filter(JumpHost.id == connection.jump_host_id).first() if jump_host is not None: _urls.append(make_url( connection_type=jump_host.connection_type, username=jump_host.username, password=jump_host.password, host_or_ip=jump_host.host_or_ip, port_number=jump_host.port_number)) except: logger.exception('Host.urls() hits exception') default_username=None default_password=None system_option = SystemOption.get(db_session) if system_option.enable_default_host_authentication: default_username=system_option.default_host_username default_password=system_option.default_host_password _urls.append(make_url( connection_type=connection.connection_type, username=connection.username, password=connection.password, host_or_ip=connection.host_or_ip, port_number=connection.port_number, default_username=default_username, default_password=default_password)) return _urls
def list_comps(params): """ make our list of competition categories""" listing = [] params['action'] = 'listcomps' comps = config.COMPS for comp in sorted(comps.keys()): params['comp'] = comps[comp] li = xbmcgui.ListItem(comp[2:]) url = '{0}?{1}'.format(_url, utils.make_url(params)) is_folder = True listing.append((url, li, is_folder)) xbmcplugin.addDirectoryItems(_handle, listing, len(listing)) xbmcplugin.endOfDirectory(_handle)
def list_years(params): """ create a list of the years that match replays are currently available for""" listing = [] params['action'] = 'listyears' for year in config.YEARS: params['year'] = year li = xbmcgui.ListItem(str(year)) url = '{0}?{1}'.format(_url, utils.make_url(params)) is_folder = True listing.append((url, li, is_folder)) xbmcplugin.addDirectoryItems(_handle, sorted(listing, reverse=True), len(listing)) xbmcplugin.endOfDirectory(_handle)
def make_xbmc_url(self): """ Returns a string which represents the program object, but in a format suitable for passing as a URL. """ d = {} if self.id: d['id'] = self.id if self.title: d['title'] = self.title if self.description: d['description'] = self.description if self.genre: d['genre'] = self.genre if self.duration: d['duration'] = self.duration if self.season: d['season'] = self.season if self.date: d['date'] = self.date.strftime("%Y-%m-%d %H:%M:%S") if self.thumbnail: d['thumbnail'] = self.thumbnail if self.url: d['url'] = self.url return utils.make_url(d)
def send_report(self, cid, ur, previous, send=True, override_uid=None, summary=False): enricher.Enricher(fake=self.fake).enrich(ur) enricher.Enricher(fake=self.fake).enrich(previous) blocks = self.make_report(ur, previous, cid) if not send: print("Saving report to slack.json") f = open("slack.json", "w") f.write(json.dumps(blocks, indent=4)) f.close() return # If set to true, this message will be sent as the user who owns the token we use as_user = False if override_uid: cid = override_uid urls = [] for blockset in utils.chunks(blocks, 49): if send: print("Sending report to {}".format(cid)) try: response = self.client.chat_postMessage(channel=cid, blocks=blockset, parse='full', as_user=as_user, unfurl_links=True, link_names=True) # print("Response: {}".format(response)) urls.append( utils.make_url(response['channel'], response['ts'])) except Exception: print(Exception) print(json.dumps(blockset, indent=4)) sys.exit(0) if summary and urls: cid = self.channel.get(config.channel_stats)['slack_cid'] self.client.chat_postMessage(channel=cid, parse='full', as_user=as_user, unfurl_links=True, link_names=True, text=urls[0])
def make_xbmc_url(self): """ Returns a string which represents the program object, but in a format suitable for passing as a URL. """ d = {} if self.id: d['id'] = self.id if self.title: d['title'] = self.title if self.episode_title: d['episode_title'] = self.episode_title if self.description: d['description'] = self.description if self.duration: d['duration'] = self.duration if self.category: d['category'] = self.category if self.rating: d['rating'] = self.rating if self.date: d['date'] = self.date.strftime("%Y-%m-%d %H:%M:%S") if self.thumbnail: d['thumbnail'] = self.thumbnail if self.url: d['url'] = self.url return utils.make_url(d)
def make_index_list(): try: index = comm.get_index() ok = True for i in index: if 'url' in i: url = "%s?%s" % (sys.argv[0], utils.make_url({ 'category': i['name']})) listitem = xbmcgui.ListItem(i['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: utils.handle_error()
def home(): """ If logged in, the user will be shown the link to view their latest tweets. Otherwise a link to authenticate them will be available. """ if not cfg.HOST_URL: cfg.HOST_URL = request.base_url print('home(): Host url set: %s' % cfg.HOST_URL) # Do not call Twitter again if already acquired if not cfg.REQUEST_TOKEN_ACQUIRED: print('home(): cfg.REQUEST_TOKEN_ACQUIRED NOT SET\n') # Step 1 - Get request token reqtoken = utils.get_request_token() if reqtoken: cfg.REQUEST_TOKEN_ACQUIRED = True print('home(): cfg.REQUEST_TOKEN_ACQUIRED NOW SET') cfg.REQUEST_OAUTH_SECRET = reqtoken[0] cfg.REQUEST_OAUTH_TOKEN = reqtoken[1] print("home(): cfg.REQUEST_OAUTH_TOKEN = %s" % cfg.REQUEST_OAUTH_TOKEN) cfg.AUTHORIZE_REDIRECT_URL = utils.make_url( cfg.PROVIDER_BASE_URL, cfg.OAUTH_LOGIN_EP, '?oauth_token=%s' % cfg.REQUEST_OAUTH_TOKEN) print('home(): cfg.AUTHORIZE_REDIRECT_URL = %s' % cfg.AUTHORIZE_REDIRECT_URL) else: print("home(): cfg.REQUEST_TOKEN_ACQUIRED SET") return render_template('home.html', login_url=cfg.AUTHORIZE_REDIRECT_URL, provider=cfg.PROVIDER, success=cfg.REQUEST_TOKEN_ACQUIRED, logged_in=cfg.IS_AUTHENTICATED, logged_in_message=cfg.LOGGED_IN_MESSAGE)
def _output_lp_edit_show(self, ret_dict): # show only new_args, error_args = check_primary_args(self.args, self.table_class, self.name2table, self.db_client, True) has_errors = len(error_args) > 0 assert not has_errors columns = [BaseColumn(col, self.table_class) for col in self.table_class.__table__.columns] filter_dict = {} for col in columns: if col.is_primary: filter_dict[col.name] = new_args[col.name] reload_record = self.db_client.select_one(self.table_class, **filter_dict) rect = self._init_render_args() if reload_record: rect = self._gen_render_args(reload_record) rect['source'] = decode_from_utf8(rect['source']) ret_dict.update(rect) ret_dict["link"] = make_url(ret_dict['tag'], {'url' : request.path, 'id' : ret_dict["id"]}) return ret_dict
def make_series_list(url): params = utils.get_url(url) try: category = params["category"] series_list = comm.get_programme_from_feed(category) series_list.sort() ok = True for s in series_list: url = "%s?%s" % (sys.argv[0], utils.make_url({'series': s.title, 'category': category})) 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: utils.handle_error('Unable to fetch program list. Please try again later.')
def make_url(self, *args, params=None): return make_url(self.base, *args, params=params)
def output_list(self): # select all by sorting lander_domain = self.args.get('lander_domain') track_domain = self.args.get("track_domain") offer_id = self.args.get("offer") d = { 'cur_url' : request.path, 'create_url' : make_url(global_vars.URL_CAMP_CREATE, {'url' : request.path}), 'set_hidden_url' : global_vars.URL_CAMP_SET_HIDDEN, 'get_source_url' : global_vars.URL_TS_FIELD, } if self.check_is_massival_inner_user(): d['get_source_url'] = global_vars.URL_ADMIN_TS_FIELD if lander_domain or track_domain: if lander_domain: main_domain = lander_domain else: main_domain = track_domain tmp_rows = self.db_client.iter_all(self.table_class, uid=self.my_uid) rows = [] for row in tmp_rows: if lander_domain: domains_list = row.lander_domains_dist else: domains_list = row.track_domain domains = [s.split(";")[0].strip() for s in domains_list.split(',') if s.strip()] found = False for _domain in domains: found = is_subdomain(_domain, [main_domain]) if found: break if found: rows.append(row) elif offer_id: paths = self.db_client.iter_all(Path, uid=self.my_uid) swaps = self.db_client.iter_all(SwapRotation, uid=self.my_uid) flows = self.db_client.iter_all(Flow, uid=self.my_uid) camps = self.db_client.iter_all(Campaign, uid=self.my_uid) d['showAll'] = True rows = OfferView.get_camp_by_oid(int(offer_id), camps, flows, swaps, paths) else: rows = self.db_client.iter_all(self.table_class, uid=self.my_uid) columns = [BaseColumn(col, self.table_class) for col in self.table_class.__table__.columns] filter_cols = ['uid', 'ck_cloak', 'ck_cloak_html', 'ck_cloak_ts', 'ck_cloak_ts_html', 'ck_android', 'ck_android_html', 'ck_websiteid_digit', 'ck_websiteid_typo', 'ck_websiteid_html', 'ck_meta_refresh', 'ck_cloak_ts2', 'ck_cloak_ts_html2'] name_filter = ['id', 'uid', 'hidden', 'ck_cloak', 'ck_cloak_html', 'ck_cloak_ts', 'ck_cloak_ts_html', 'ck_android', 'ck_android_html', 'ck_websiteid_digit', 'ck_websiteid_typo', 'ck_websiteid_html', 'ck_meta_refresh', 'ck_cookie', 'ck_cookie_time', 'ck_cookie_html', 'ck_touch', 'ck_touch_html', 'ck_cloak_ts2', 'ck_cloak_ts_html2'] name2title = {} domain_fields = ['lander_domains_dist', 'track_domains'] flows = self.db_client.select_all(Flow, uid=self.my_uid) flow_cache = {} source_cache = {} admin_source_cache = {} for f in flows: flow_cache[f.id] = f.name foreignkey2name = { 'flow_id':{'name':'flow', 'cache':flow_cache}, } if self.is_inner_user: name_filter.append("source_id") filter_cols.append("source_id") admin_sources = self.get_admin_config(AdminTrafficSource) for f in admin_sources: admin_source_cache[f.id] = f.name foreignkey2name['admin_source_id'] = {'name':'admin_source', 'cache':admin_source_cache} else: name_filter.append("admin_source_id") filter_cols.append("admin_source_id") sources = self.db_client.select_all(TrafficSource, uid=self.my_uid) for f in sources: source_cache[f.id] = f.name foreignkey2name['source_id'] = {'name':'source', 'cache':source_cache} field_names = [] extra_name_cols = ["admin_source_id", "source_id"] for col in columns: if col.name in name_filter: continue t = "string" if col.is_foreign or isinstance(col.real_column.type, String) or col.name in extra_name_cols else "number" col_ret = { 'name' :col.name, 'type': t} title = name2title.get(col.name, None) if title is not None: col_ret['title'] = title parse = foreignkey2name.get(col.name, None) if parse is not None: col_ret['name'] = parse['name'] field_names.append(col_ret) d['field_names'] = field_names records = [] for row in rows: tmp_records = {} pk_id = None for column in columns: if column.name in filter_cols: continue if column.is_primary: pk_id = getattr(row, column.name) elif column.is_normal: if column.is_multi: vs = getattr(row, column.name) ids = [int(_id) for _id in vs.split(',')] if vs else [] #ids = [_id for _id in vs.split(',')] options = self.get_multi_options(column.multi_table, column.multi_id, 'name') ret_names = [] for _id in ids: ret_names.append(options.get(_id, 'unknown')) tmp_records[column.name] = ','.join(ret_names) else: if column.is_textarea: tmp_records[column.name] = ('[CONTENT CANNOT READ]') else: val = getattr(row, column.name) if column.name in ["admin_source_id", "source_id"]: _fid = getattr(row, column.name) tmp_records[column.name] = _fid i = foreignkey2name[column.name] cache = i['cache'] v = cache[val] tmp_records[i['name']] = (v) else: if column.name in domain_fields: val = self.domain_handler(val) tmp_records[column.name] = val elif column.is_foreign and column.name not in ['uid']: _fid = getattr(row, column.name) tmp_records[column.name] = _fid if column.name in foreignkey2name: i = foreignkey2name[column.name] cache = i['cache'] source_col = column.foreign_source_key v = cache[_fid] tmp_records[i['name']] = (v) obj_info = {} obj_info['values'] = tmp_records obj_info['edit_url'] = make_url(global_vars.URL_CAMP_EDIT, {'url' : request.path, 'id' : pk_id}) obj_info['id'] = pk_id records.append(obj_info) def _cmp(a, b): return int(b["id"]) - int(a["id"]) records = sorted(records, _cmp) d['records'] = records title = 'Massival %s List'%self.table_class.__name__ render = Render(title, self.tmpl_reader, self.session_info) body_tmpl = self.tmpl_reader.read_file('toolbar_model_list.tmpl') body_str = Template(body_tmpl).render(**d) return render.gen_output(body_str, {'nav_left' : to_links(self.table_class, 'list')})
def make_section_list(url): utils.log("Making section list") try: params = utils.get_url(url) section = comm.get_section(params['category'], params['section']) ok = True if 'children' in section and len(section['children']) > 0: for s in section['children']: entries_url = s.get('url') if entries_url: url = "%s?%s" % (sys.argv[0], utils.make_url({'entries_url': entries_url})) thumbnail = s.get('thumbnail') listitem = xbmcgui.ListItem(s.get('name'), iconImage=thumbnail, thumbnailImage=thumbnail) listitem.setInfo('video', {'title': s.get('name'), 'genre': s.get('genre'), 'plot': s.get('description'), 'plotoutline': s.get('description')}) # Add the program item to the list ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=True) elif 'url' in section: # no children, so fetch children by URL programs = comm.get_entries(section['url']) for p in sorted(programs): thumbnail = p.get_thumbnail() listitem = xbmcgui.ListItem(label=p.get_list_title(), iconImage=thumbnail, thumbnailImage=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)) else: utils.log("No children or url found for %s" % section) xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok) xbmcplugin.setContent(handle=int(sys.argv[1]), content='episodes') except: utils.handle_error()
if __name__ == '__main__': # Parse inputs args = parse_inputs() # Loop on define location keys = list(DEFAULT_LOCALISATIONS.keys()) # begin pdf file doc = SimpleDocTemplate(args.report_name, pagesize=landscape(A4)) story = [] if (args.departement == -1): for key in keys: cp = key ville = DEFAULT_LOCALISATIONS[key] # Set URL if set unset nbr_piece URL = make_url(ville, cp, args) # Print current city and cp print(ville + " " + cp) # Loop on result for city for item in browse(URL, DEFAULT_CATEGORIES): try: item.serialize(args.image) story += item.save(doc, args) print("-----") except: print(item.ad_number()) print("%s: %s" % (sys.exc_info()[0], sys.exc_info()[1])) print("=====") else: cp = None ville = None
reload_record = self.db_client.select_one(self.table_class, **filter_dict) _id = self.args.get("id", 0) rect = self._init_render_args() rect["id"] = _id if has_errors: op_tips = gen_op_tips('Edit Failed! %s'%error_msg) else: op_tips = gen_op_tips('Edit Success!', True) if reload_record: rect = self._gen_render_args(reload_record) ret_dict.update(rect) ret_dict["op_tips"] = op_tips ret_dict['link'] = make_url(ret_dict['tag'], {'url' : request.path, 'id' : _id}) return ret_dict def output_lp_html(self, op): ret_dict = {} ret_dict.update(self._init_render_args()) ret_dict['list_url'] = self.list_url ret_dict['batch_upload_url'] = self.batch_upload_url ret_dict['op_tips'] = '' ret_dict['tag'] = 'normal' ret_dict["link"] = "" self.args["page_source"] = "" func = self._op_func.get(op, None) if func: ret_dict['tag'] = func[0]
def output_list(self): # select all by sorting sort_arg = self.args.get('sort') if sort_arg is None: rows = self.db_client.select_all(self.table_class, uid=self.my_uid) else: idx = int(sort_arg) sort_arg = get_columns(self.table_class)[idx].asc() rows = self.db_client.select_all_sort(self.table_class, sort_arg, uid=self.my_uid) columns = [BaseColumn(col, self.table_class) for col in self.table_class.__table__.columns] filter_cols = ['uid'] field_names = [] for col in columns: t = "string" if isinstance(col.real_column.type, String) else "number" if col.is_normal: field_names.append({ 'name' :col.name, 'is_normal' : True, 'type': t, }) if col.is_foreign and col.name not in filter_cols: field_names.append({ 'name' : col.name, 'is_normal' : False, 'type': "string", }) records = [] for row in rows: tmp_records = {} pk_id = None for column in columns: if column.is_primary: pk_id = getattr(row, column.name) if column.is_normal: if column.is_multi: vs = getattr(row, column.name) ids = [int(_id) for _id in vs.split(',')] if vs else [] #ids = [_id for _id in vs.split(',')] options = self.get_multi_options(column.multi_table, column.multi_id, 'name') ret_names = [] for _id in ids: ret_names.append(options.get(_id, 'unknown')) tmp_records[column.name] = ','.join(ret_names) else: if column.is_textarea: tmp_records[column.name] = ('[CONTENT CANNOT READ]') else: tmp_records[column.name] = (getattr(row, column.name)) if column.is_foreign and column.name not in filter_cols: source_col = column.foreign_source_key options = self.get_options(source_col, 'name') _fid = getattr(row, column.name) v = options.get(_fid, 'UNKNOWN') tmp_records[column.name] = (v) obj_info = {} obj_info['values'] = tmp_records obj_info['edit_url'] = make_url(self.edit_url, {'url' : request.path, 'id' : pk_id}) obj_info['id'] = pk_id records.append(obj_info) d = { 'cur_url' : request.path, 'create_url' : make_url(self.create_url, {'url' : request.path}), 'del_url' : self.del_url, 'field_names' : field_names, 'records' : records, } title = '2Fly %s List'%self.table_class.__name__ render = Render(title, self.tmpl_reader, self.session_info) body_tmpl = self.tmpl_reader.read_file(self.list_tmpl) body_str = Template(body_tmpl).render(**d) return render.gen_output(body_str, {'nav_left' : to_links(self.table_class, 'list')})
def compose_link(text: str): url = make_url('https://lmgtfy.com', params={'q': text}) return url
def output_list(self): rows = self.db_client.iter_all(self.table_class) columns = [BaseColumn(col, self.table_class) for col in self.table_class.__table__.columns] filter_cols = ['uid'] name_filter = ['uid', 'hidden', 'introduction'] field_names = [] for col in columns: if col.name in name_filter: continue t = "string" if isinstance(col.real_column.type, String) else "number" if col.is_normal: field_names.append({ 'name' :col.name, 'is_normal' : True, 'type': t, }) if col.is_foreign and col.name not in filter_cols: field_names.append({ 'name' : col.name, 'is_normal' : False, 'type': "string", }) records = [] for row in rows: tmp_records = {} pk_id = None for column in columns: if column.is_primary: pk_id = getattr(row, column.name) if column.is_normal: if column.is_multi: vs = getattr(row, column.name) ids = [int(_id) for _id in vs.split(',')] if vs else [] options = self.get_multi_options(column.multi_table, column.multi_id, 'name') ret_names = [] for _id in ids: ret_names.append(options.get(_id, 'unknown')) tmp_records[column.name] = ','.join(ret_names) else: if column.is_textarea: tmp_records[column.name] = ('[CONTENT CANNOT READ]') else: tmp_records[column.name] = (getattr(row, column.name)) if column.is_foreign and column.name not in filter_cols: source_col = column.foreign_source_key _fid = getattr(row, column.name) v = self.get_foreign_key_field_data(source_col, 'name', col.name, _fid) tmp_records[column.name] = (v) obj_info = {} obj_info['values'] = tmp_records obj_info['edit_url'] = make_url(global_vars.URL_ADMIN_OFFER_EDIT, {'url' : request.path, 'id' : pk_id}) obj_info['id'] = pk_id records.append(obj_info) def _cmp(a, b): return int(b["id"]) - int(a["id"]) records = sorted(records, _cmp) d = { 'cur_url' : request.path, 'create_url' : make_url(global_vars.URL_ADMIN_OFFER_CREATE, {'url' : request.path}), #'del_url' : self.del_url, 'field_names' : field_names, 'records' : records, 'set_hidden_url' : global_vars.URL_ADMIN_OFFER_SET_HIDDEN, } title = 'Massival %s List'%self.table_class.__name__ render = Render(title, self.tmpl_reader, self.session_info) body_tmpl = self.tmpl_reader.read_file('toolbar_model_list.tmpl') body_str = Template(body_tmpl).render(**d) return render.gen_output(body_str, {'nav_left' : to_links(self.table_class, 'list')})