def __init__(self, cfg): # set attributes based on config self.__dict__.update(cfg) # if name not set in config file use the directory name if not cfg.has_key('name'): self.name = cfg.dir.split(os.sep)[-1] # default nick to gozerbot if not cfg.has_key('nick'): self.nick = 'gozerbot' # default port to 0 (use default port) if not cfg.has_key('port'): self.port = 0 # make sure bot name is not a directory if '..' in self.name or '/' in self.name: raise Exception('wrong bot name %s' % self.name) # set datadir to datadir/fleet/<botname> self.datadir = datadir + os.sep + 'fleet' + os.sep + self.name # bot state self.state = Pdod(self.datadir + os.sep + 'state') # bot state # joined channels list .. used to join channels if not self.state.has_key('joinedchannels'): self.state['joinedchannels'] = [] # allowed commands on the bot if not self.state.has_key('allowed'): self.state['allowed'] = [] # channels we dont want ops in if not self.state.has_key('no-op'): self.state['no-op'] = [] # channels we are op in if not self.state.has_key('opchan'): self.state['opchan'] = [] self.cfg = cfg # the bots config self.orignick = "" # original nick self.blocking = True # use blocking sockets self.lastoutput = 0 # time of last output self.stopped = False # flag to set when bot is to be stopped self.connected = False # conencted flag self.connecting = False # connecting flag self.connectok = threading.Event() # event set when bot has connected self.waitingforconnect = False # flag to indicate we are waiting for connect self.starttime = time.time() # start time of the bot self.nrevents = 0 # number of events processed self.gcevents = 0 # number of garbage collected events self.less = Less(5) # output buffering self.userchannels = Dol() # list of channels a user is in self.channels = Channels(self.datadir + os.sep + 'channels') # channels self.userhosts = PersistState(self.datadir + os.sep + 'userhosts') # userhosts cache self.splitted = [] # list of splitted nicks self.throttle = [] # list of nicks that need to be throttled self.jabber = False # flag is set on jabber bots self.google = False # flag is set on google bots # start runners runners_start()
def post(self, channel_id): self.response.headers["Content-Type"] = "application/json" try: rating = self.request.POST["rating"] user_id = self.request.POST["user"] channel = Channels() channel.rate_channel(channel_id, rating, user_id) except Exception: logging.exception("Failed to rate channel %s" % channel_id) out = {"success": 0} self.response.write(json.dumps(out)) else: logging.info("Channel rated successfully") out = {"success": 1} self.response.write(json.dumps(out))
def get(self): self.response.headers["Content-Type"] = "application/json" try: user_id = self.request.GET["user"] sort = self.request.GET["sort"] channels = Channels() channels_list = channels.get_channels(user_id, sort) except Exception: logging.exception("Failed looking for channels") out = {"success": 0} self.response.write(json.dumps(out)) else: logging.info("Channels retrieved successfully") out = {"success": 1, "channels": channels_list} self.response.write(json.dumps(out))
def post(self): self.response.headers["Content-Type"] = "application/json" try: user_id = self.request.POST["user"] channel_name = self.request.POST["channel"] if "nsfw" not in self.request.POST: nsfw = 0 else: nsfw = self.request.POST["nsfw"] channels = Channels() channels.add_channel(channel_name, user_id, nsfw) except Exception: logging.exception("Failed to add a channel") out = {"success": 0} self.response.write(json.dumps(out)) else: logging.info("Channel added successfully") out = {"success": 1} self.response.write(json.dumps(out))
def channel(data): from channels import Channels if data.get('PlayerObj', []): obj = data['PlayerObj'] for i in obj: if i.get('streams', None): items.add(Channels(i).item) items.add({'mode':'epg', 'title':getString(30103), 'plot':getString(30103)}) items.add({'mode':'sports', 'title':getString(30101), 'plot':getString(30102)}) items.list()
def __init__(self): self.conf = Config() self.channels = Channels() self.delay = __delay__ self.version = __version__ self.ENCODING = "utf-8" self._replacer, self._endreplacer = utils._replacer, utils._endreplacer self.chan = [] self.startdir = os.getcwd() + "/" self.disconnection = False self.connect() os.chdir(self.startdir)
def startservice(openetv_config, logging): # set startup defaults bouquet_id = 0 bouquet_name = None bouquet_ref = None max_bouquets = 1000 max_channels = 1000 vlc_quality = "good" # create the bouquets and channels objects r_bouquets = Bouquets(openetv_config, logging) r_channels = Channels(openetv_config, logging, max_channels) # refresh bouquet list rb_res = r_bouquets.refresh_bouquet_list() # check if the bouquet list is successfully fetched if rb_res: # get bouquet list html_bouquets = r_bouquets.list_bouquets() # get bouquet name and ref bouquet = r_bouquets.set_active_bouquet(bouquet_id) bouquet_name = bouquet[0] bouquet_ref = bouquet[1] # refresh the channel list rc_res = r_channels.refresh_channel_list(bouquet_name, bouquet_ref) # socket/bind/listen setup s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((openetv_config['openetv']['bind_host'], int(openetv_config['openetv']['bind_port']))) s.listen(5) while True: c, addr = s.accept() logging.debug("[App::run] debug: incomming connection from: " + addr[0] + ":%d" % addr[1]) # recieve HTTP command cmd = c.recv(1024).split('\n')[0] logging.debug("[App::run] debug: command [" + cmd + "]") if cmd[:3] == "GET": page = cmd.split(' ')[1] logging.debug("[App::run] debug: page request [" + page + "]") # get current active channels active_channel = r_channels.get_active_channel() active_channel_name = r_channels.get_active_channel_name() if page == "/" or page == "/index.htm" or page == "index.html": """ Expected parameters: none """ html = html_header(openetv_config) if rb_res: html += r_bouquets.list_bouquets() else: html += "<b>Error: could not get bouquet list!</b>" if rc_res: html += r_channels.list_channels() html += html_menu(openetv_config, vlc_quality, active_channel, active_channel_name, max_channels) html += html_footer(openetv_config) write_data = "HTTP/1.1 200 OK\n" write_data += "Content-Length: %d\n" % len(html) write_data += "Content-Type: text/html\n\n" write_data += html c.send(write_data) elif page[:8] == "/quality": """ Expected parameters: /quality=<poor|medium|good> """ q_str = page.split('=')[1] if q_str == "poor": vlc_quality = "poor" elif q_str == "medium": vlc_quality = "medium" else: vlc_quality = "good" logging.debug("[App::run] debug: quality changed to [" + q_str + "]") html = html_header(openetv_config) if rb_res: html += r_bouquets.list_bouquets() else: html += "<b>Error: could not get bouquet list!</b>" if rc_res: html += r_channels.list_channels() html += html_menu(openetv_config, vlc_quality, active_channel, active_channel_name, max_channels) html += html_footer(openetv_config) write_data = "HTTP/1.1 200 OK\n" write_data += "Content-Length: %d\n" % len(html) write_data += "Content-Type: text/html\n\n" write_data += html c.send(write_data) elif page[:8] == "/bouquet": """ Expected parameters: /bouquet=<bouquet-id> """ bid = page.split('=')[1] logging.debug( "[App::run] debug: changing bouquet list to [" + bid + "]") try: id = int(bid) except ValueError: html = html_header(openetv_config) if rb_res: html += r_bouquets.list_bouquets() else: html += "<b>Error: could not get bouquet list!</b>" html += html_menu(openetv_config, vlc_quality, active_channel, active_channel_name, max_channels) html += "<b>Error: bouquet id is invalid!</b><br>" html += html_footer(openetv_config) write_data = "HTTP/1.1 200 OK\n" write_data += "Content-Length: %d\n" % len(html) write_data += "Content-Type: text/html\n\n" write_data += html c.send(write_data) c.close() if not 0 <= int(bid) < max_bouquets: html = html_header(openetv_config) if rb_res: html += r_bouquets.list_bouquets() else: html += "<b>Error: could not get bouquet list!</b>" html += html_menu(openetv_config, vlc_quality, active_channel, active_channel_name, max_channels) html += "<b>Error: bouquetplaylist id is not in range between 0 and 999!</b><br>" html += html_footer(openetv_config) write_data = "HTTP/1.1 200 OK\n" write_data += "Content-Length: %d\n" % len(html) write_data += "Content-Type: text/html\n\n" write_data += html c.send(write_data) c.close() if rb_res: # select bouquet bouquet_id = id bouquet = r_bouquets.set_active_bouquet(bouquet_id) bouquet_name = bouquet[0] bouquet_ref = bouquet[1] html = html_header(openetv_config) if rb_res: html += r_bouquets.list_bouquets() else: html += "<b>Error: could not get bouquet list!</b>" # refresh the channels rc_res = r_channels.refresh_channel_list( bouquet_name, bouquet_ref) if rc_res: html += r_channels.list_channels() html += html_menu(openetv_config, vlc_quality, active_channel, active_channel_name, max_channels) html += html_footer(openetv_config) write_data = "HTTP/1.1 200 OK\n" write_data += "Content-Length: %d\n" % len(html) write_data += "Content-Type: text/html\n\n" write_data += html c.send(write_data) elif page[:6] == "/start": """ Expected parameters: /start=<channel-id> """ cid = page.split('=')[1] logging.debug("[App::run] debug: start channel id [" + cid + "]") try: id = int(cid) except ValueError: html = html_header(openetv_config) if rb_res: html += r_bouquets.list_bouquets() else: html += "<b>Error: could not get bouquet list!</b>" html += html_menu(openetv_config, vlc_quality, active_channel, active_channel_name, max_channels) html += "<b>Error: playlist id is invalid!</b><br>" html += html_footer(openetv_config) write_data = "HTTP/1.1 200 OK\n" write_data += "Content-Length: %d\n" % len(html) write_data += "Content-Type: text/html\n\n" write_data += html c.send(write_data) c.close() if not 0 <= int(id) < max_channels: html = html_header(openetv_config) if rb_res: html += r_bouquets.list_bouquets() else: html += "<b>Error: could not get bouquet list!</b>" html += html_menu(openetv_config, vlc_quality, active_channel, active_channel_name, max_channels) html += "<b>Error: playlist id is not in range between 0 and 999!</b><br>" html += html_footer(openetv_config) write_data = "HTTP/1.1 200 OK\n" write_data += "Content-Length: %d\n" % len(html) write_data += "Content-Type: text/html\n\n" write_data += html c.send(write_data) c.close() html = html_header(openetv_config) if rb_res: html += r_bouquets.list_bouquets() else: html += "<b>Error: could not get bouquet list!</b>" # play the selected channel r_channels.play_channel(id, vlc_quality) # get current active channels active_channel = r_channels.get_active_channel() active_channel_name = r_channels.get_active_channel_name() if rc_res: html += r_channels.list_channels() html += html_menu(openetv_config, vlc_quality, active_channel, active_channel_name, max_channels) html += html_footer(openetv_config) write_data = "HTTP/1.1 200 OK\n" write_data += "Content-Length: %d\n" % len(html) write_data += "Content-Type: text/html\n\n" write_data += html c.send(write_data) # shutdown the socket, otherwise the client still thinks it recieves data c.shutdown(socket.SHUT_RDWR) elif page[:5] == "/stop": """ Expected parameters: none """ logging.debug("[App::run] debug: stop channel id [%d" % active_channel + "]") if active_channel < max_channels: html = html_header(openetv_config) if rb_res: html += r_bouquets.list_bouquets() else: html += "<b>Error: could not get bouquet list!</b>" # stop the transcoding process stop_res = r_channels.stop_channel() # get current active channels active_channel = r_channels.get_active_channel() active_channel_name = r_channels.get_active_channel_name( ) if rc_res: html += r_channels.list_channels() html += html_menu(openetv_config, vlc_quality, active_channel, active_channel_name, max_channels) if not stop_res: html += "<b>Error: unable to stop stream, nothing is playing!</b><br>\n" html += html_footer(openetv_config) else: html = html_header(openetv_config) if rb_res: html += r_bouquets.list_bouquets() else: html += "<b>Error: could not get bouquet list!</b>" if rc_res: html += r_channels.list_channels() html += html_menu(openetv_config, vlc_quality, active_channel, active_channel_name, max_channels) html += html_footer(openetv_config) write_data = "HTTP/1.1 200 OK\n" write_data += "Content-Length: %d\n" % len(html) write_data += "Content-Type: text/html\n\n" write_data += html c.send(write_data) elif page[:8] == "/refresh": """ Expected parameters: "bouquet" or "channel" """ type = page.split('=')[1] html = html_header(openetv_config) # refresh bouquets if type == "bouquet": rb_res = r_bouquets.refresh_bouquet_list() if rb_res: html += r_bouquets.list_bouquets() # refresh the channel list if type == "channel": rc_res = r_channels.refresh_channel_list( bouquet_name, bouquet_ref) if rc_res: html += r_channels.list_channels() else: html += "<b>Error: could not get bouquet list!</b>" html += html_menu(openetv_config, vlc_quality, active_channel, active_channel_name, max_channels) html += html_footer(openetv_config) write_data = "HTTP/1.1 200 OK\n" write_data += "Content-Length: %d\n" % len(html) write_data += "Content-Type: text/html\n\n" write_data += html c.send(write_data) logging.debug("[App::run] closing connection") c.close()
socketio = SocketIO(app) # Compile scss assets = Environment(app) assets.url = app.static_url_path scss = Bundle( 'sass/main.scss', filters='pyscss', depends=('**/*.scss'), output='styles.css') assets.register('scss_all', scss) # Globals users = {} rooms = Channels() # Initalize channels rooms.add_channel('general') msg = {'text': 'Welcome to channel #general', 'name': 'FlackBot', 'stamp': now_stamp(), 'color': cObj('#888888')} rooms.add_message('general', msg) @app.route("/") def index(): """Show chat app""" return render_template('index.html') @app.route('/new_room', methods=['POST'])
class BotBase(object): def __init__(self, cfg): # set attributes based on config self.__dict__.update(cfg) # if name not set in config file use the directory name if not cfg.has_key('name'): self.name = cfg.dir.split(os.sep)[-1] # default nick to gozerbot if not cfg.has_key('nick'): self.nick = 'gozerbot' # default port to 0 (use default port) if not cfg.has_key('port'): self.port = 0 # make sure bot name is not a directory if '..' in self.name or '/' in self.name: raise Exception('wrong bot name %s' % self.name) # set datadir to datadir/fleet/<botname> self.datadir = datadir + os.sep + 'fleet' + os.sep + self.name # bot state self.state = Pdod(self.datadir + os.sep + 'state') # bot state # joined channels list .. used to join channels if not self.state.has_key('joinedchannels'): self.state['joinedchannels'] = [] # allowed commands on the bot if not self.state.has_key('allowed'): self.state['allowed'] = [] # channels we dont want ops in if not self.state.has_key('no-op'): self.state['no-op'] = [] # channels we are op in if not self.state.has_key('opchan'): self.state['opchan'] = [] self.cfg = cfg # the bots config self.orignick = "" # original nick self.blocking = True # use blocking sockets self.lastoutput = 0 # time of last output self.stopped = False # flag to set when bot is to be stopped self.connected = False # conencted flag self.connecting = False # connecting flag self.connectok = threading.Event() # event set when bot has connected self.waitingforconnect = False # flag to indicate we are waiting for connect self.starttime = time.time() # start time of the bot self.nrevents = 0 # number of events processed self.gcevents = 0 # number of garbage collected events self.less = Less(5) # output buffering self.userchannels = Dol() # list of channels a user is in self.channels = Channels(self.datadir + os.sep + 'channels') # channels self.userhosts = PersistState(self.datadir + os.sep + 'userhosts') # userhosts cache self.splitted = [] # list of splitted nicks self.throttle = [] # list of nicks that need to be throttled self.jabber = False # flag is set on jabber bots self.google = False # flag is set on google bots # start runners runners_start() def ownercheck(self, ievent, txt=None): """ check whether an event originated from the bot owner. """ # use owner set in bot's config or else in global config owner = self.cfg['owner'] or config['owner'] # check if event userhost in in owner .. check lists and string values if type(owner) == types.ListType: if ievent.userhost in owner: return 1 elif owner == ievent.userhost: return 1 else: rlog( 100, self.name, 'failed owner check %s should be in %s' % (ievent.userhost, owner)) if not txt: ievent.reply( "only owner (see config file) is allowed to perform this command" ) else: ievent.reply("only owner (see config file) %s" % txt) return 0 def save(self): """ save bot state. """ self.channels.save() self.userhosts.save() self.state.save() def stop(self): """ stop the bot. """ self.stopped = True rlog(10, self.name, 'stopped') def exit(self): """ shutdown the bot. overload this. """ pass def connect(self, reconnect=True): """ connect the bot to the server. reconnects in the default case. """ pass def joinchannels(self): """ join all registered channels. overload this. """ pass def connectwithjoin(self, reconnect=True): """ connect to the server and join channels. """ self.connect(reconnect) self.connectok.wait() self.joinchannels() def broadcast(self): """ announce a message to all channels. overload this""" pass def send(self, txt): """ send txt to the server. overload this""" pass def shutdown(self): """ close sockets of the bot. overload this""" pass def domsg(self, msg): """ excecute a message (txt line) on the bot. """ plugins.trydispatch(self, msg)
def _pay_too_fast(self, paytype): if self._is_in_pay_review(): return False min_interval = Channels.get_min_interval(paytype) return self._is_user_pay_too_fast(paytype, min_interval) \ or self._is_device_pay_too_fast(paytype, min_interval)
def _volume_capped(self, paytype): limit_month = Channels.get_personal_monthly_cap(paytype) limit_day = Channels.get_personal_daily_cap(paytype) return self._is_user_volume_capped(paytype, limit_month, limit_day) \ or self._is_device_volume_capped(paytype, limit_month, limit_day)
class BotBase(object): def __init__(self, cfg): # set attributes based on config self.__dict__.update(cfg) # if name not set in config file use the directory name if not cfg.has_key('name'): self.name = cfg.dir.split(os.sep)[-1] # default nick to gozerbot if not cfg.has_key('nick'): self.nick = 'gozerbot' # default port to 0 (use default port) if not cfg.has_key('port'): self.port = 0 # make sure bot name is not a directory if '..' in self.name or '/' in self.name: raise Exception('wrong bot name %s' % self.name) # set datadir to datadir/fleet/<botname> self.datadir = datadir + os.sep + 'fleet' + os.sep + self.name # bot state self.state = Pdod(self.datadir + os.sep + 'state') # bot state # joined channels list .. used to join channels if not self.state.has_key('joinedchannels'): self.state['joinedchannels'] = [] # allowed commands on the bot if not self.state.has_key('allowed'): self.state['allowed'] = [] # channels we dont want ops in if not self.state.has_key('no-op'): self.state['no-op'] = [] # channels we are op in if not self.state.has_key('opchan'): self.state['opchan'] = [] self.cfg = cfg # the bots config self.orignick = "" # original nick self.blocking = True # use blocking sockets self.lastoutput = 0 # time of last output self.stopped = False # flag to set when bot is to be stopped self.connected = False # conencted flag self.connecting = False # connecting flag self.connectok = threading.Event() # event set when bot has connected self.waitingforconnect = False # flag to indicate we are waiting for connect self.starttime = time.time() # start time of the bot self.nrevents = 0 # number of events processed self.gcevents = 0 # number of garbage collected events self.less = Less(5) # output buffering self.userchannels = Dol() # list of channels a user is in self.channels = Channels(self.datadir + os.sep + 'channels') # channels self.userhosts = PersistState(self.datadir + os.sep + 'userhosts') # userhosts cache self.splitted = [] # list of splitted nicks self.throttle = [] # list of nicks that need to be throttled self.jabber = False # flag is set on jabber bots self.google = False # flag is set on google bots # start runners runners_start() def ownercheck(self, ievent, txt=None): """ check whether an event originated from the bot owner. """ # use owner set in bot's config or else in global config owner = self.cfg['owner'] or config['owner'] # check if event userhost in in owner .. check lists and string values if type(owner) == types.ListType: if ievent.userhost in owner: return 1 elif owner == ievent.userhost: return 1 else: rlog(100, self.name, 'failed owner check %s should be in %s' % (ievent.userhost, owner)) if not txt: ievent.reply("only owner (see config file) is allowed to perform this command") else: ievent.reply("only owner (see config file) %s" % txt) return 0 def save(self): """ save bot state. """ self.channels.save() self.userhosts.save() self.state.save() def stop(self): """ stop the bot. """ self.stopped = True rlog(10, self.name, 'stopped') def exit(self): """ shutdown the bot. overload this. """ pass def connect(self, reconnect=True): """ connect the bot to the server. reconnects in the default case. """ pass def joinchannels(self): """ join all registered channels. overload this. """ pass def connectwithjoin(self, reconnect=True): """ connect to the server and join channels. """ self.connect(reconnect) self.connectok.wait() self.joinchannels() def broadcast(self): """ announce a message to all channels. overload this""" pass def send(self, txt): """ send txt to the server. overload this""" pass def shutdown(self): """ close sockets of the bot. overload this""" pass def domsg(self, msg): """ excecute a message (txt line) on the bot. """ plugins.trydispatch(self, msg)
def handle(self): # self.request is the TCP socket connected to the client self.data = str(self.request.recv(1024),"utf-8") self.argv = self.data.rstrip().split(',') if self.argv[0] == "get_active_log": log_path = self.argv[1] length = os.path.getsize(log_path) self.request.send(Server.convert_to_bytes(length)) infile = open(log_path, 'r') self.log = infile.read() self.log = self.log.encode(encoding='UTF-8') self.log = struct.pack('>I',len(self.log)) + self.log self.request.sendall(self.log) elif self.argv[0] == "get_all_logs": self.time_stamps = "" for i in range(1,len(self.argv)): self.temp = "" if not os.path.exists(Config.c['LOG PATH'] + self.argv[i]): f = open(Config.c['LOG PATH'] + self.argv[i], 'w') f.write("Fresh Log\n\n") f.close() self.temp = os.stat(Config.c['LOG PATH'] + self.argv[i]) self.time_stamps += str(self.temp.st_mtime) + "," self.time_stamps = self.time_stamps.encode(encoding='UTF-8') self.time_stamps = struct.pack('>I',len(self.time_stamps)) + self.time_stamps self.request.sendall(self.time_stamps) elif self.argv[0] == "get_channels": channels_raw = Channels() self.channels = channels_raw.get_list() self.channel_str = "" for i in range(0,len(self.channels)): self.channel_str += self.channels[i][0] + "/" for j in range(0,len(self.channels[i][1])): self.channel_str += self.channels[i][1][j] + "," if len(self.channels[i][1]) == 0: self.channel_str += "none," self.channel_str = self.channel_str[:-1] self.channel_str += "/" self.channel_str += self.channels[i][2] + "/" for j in range(0,len(self.channels[i][3])): self.channel_str += self.channels[i][3][j] + "," if len(self.channels[i][3]) == 0: self.channel_str += "none," self.channel_str = self.channel_str[:-1] self.channel_str += "//" self.channel_str = self.channel_str[:-2] self.channel_str = self.channel_str.encode(encoding='UTF-8') self.channel_str = struct.pack('>I',len(self.channel_str)) + self.channel_str self.request.sendall(self.channel_str) #self.request.sendall(bytes(self.channel_str + "\n", "utf-8")) elif self.argv[0] == "get_roster": roster = Roster() self.roster_arr = roster.get_roster() self.roster_str = "" for i in range(0,len(self.roster_arr)): self.roster_str += self.roster_arr[i][0] + ',' + self.roster_arr[i][1] + ',' + self.roster_arr[i][2] + '/' self.roster_str = self.roster_str.encode(encoding='UTF-8') self.roster_str = struct.pack('>I',len(self.roster_str)) + self.roster_str self.request.sendall(self.roster_str) #self.request.sendall(bytes(self.roster_str + "\n", "utf-8")) elif self.argv[0] == "new_post": log_path = self.argv[1] log = "" for i in range(2,len(self.argv)): log += self.argv[i] + "," log = log[:-1] ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%m/%d > %H:%M >') log = st + ' ' + log + '\n----------\n\n' f = open(log_path, 'a') f.write(log) f.close() elif self.argv[0] == "whos_online": self.users = Online.add(self.argv[1]) self.online_users = "" for i in range(0,len(self.users)): self.online_users += self.users[i][0] + "," self.request.sendall(bytes(self.online_users + "\n", "utf-8"))
def startservice(openetv_config, logging): # set startup defaults bouquet_id = 0 bouquet_name = None bouquet_ref = None max_bouquets = 1000 max_channels = 1000 vlc_quality = "good" # create the bouquets and channels objects r_bouquets = Bouquets(openetv_config, logging) r_channels = Channels(openetv_config, logging, max_channels) # refresh bouquet list rb_res = r_bouquets.refresh_bouquet_list() # check if the bouquet list is successfully fetched if rb_res: # get bouquet list html_bouquets = r_bouquets.list_bouquets() # get bouquet name and ref bouquet = r_bouquets.set_active_bouquet(bouquet_id) bouquet_name = bouquet[0] bouquet_ref = bouquet[1] # refresh the channel list rc_res = r_channels.refresh_channel_list(bouquet_name, bouquet_ref) # socket/bind/listen setup s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((openetv_config['openetv']['bind_host'], int(openetv_config['openetv']['bind_port']))) s.listen(5) while True: c, addr = s.accept() logging.debug("[App::run] debug: incomming connection from: " + addr[0] + ":%d" % addr[1]) # recieve HTTP command cmd = c.recv(1024).split('\n')[0] logging.debug("[App::run] debug: command [" + cmd + "]") if cmd[:3] == "GET": page = cmd.split(' ')[1] logging.debug("[App::run] debug: page request [" + page + "]") # get current active channels active_channel = r_channels.get_active_channel() active_channel_name = r_channels.get_active_channel_name() if page == "/" or page == "/index.htm" or page == "index.html": """ Expected parameters: none """ html = html_header(openetv_config) if rb_res: html += r_bouquets.list_bouquets() else: html += "<b>Error: could not get bouquet list!</b>" if rc_res: html += r_channels.list_channels() html += html_menu(openetv_config, vlc_quality, active_channel, active_channel_name, max_channels) html += html_footer(openetv_config) write_data = "HTTP/1.1 200 OK\n" write_data += "Content-Length: %d\n" % len(html) write_data += "Content-Type: text/html\n\n" write_data += html c.send(write_data) elif page[:8] == "/quality": """ Expected parameters: /quality=<poor|medium|good> """ q_str = page.split('=')[1] if q_str == "poor": vlc_quality = "poor" elif q_str == "medium": vlc_quality = "medium" else: vlc_quality = "good" logging.debug("[App::run] debug: quality changed to [" + q_str + "]") html = html_header(openetv_config) if rb_res: html += r_bouquets.list_bouquets() else: html += "<b>Error: could not get bouquet list!</b>" if rc_res: html += r_channels.list_channels() html += html_menu(openetv_config, vlc_quality, active_channel, active_channel_name, max_channels) html += html_footer(openetv_config) write_data = "HTTP/1.1 200 OK\n" write_data += "Content-Length: %d\n" % len(html) write_data += "Content-Type: text/html\n\n" write_data += html c.send(write_data) elif page[:8] == "/bouquet": """ Expected parameters: /bouquet=<bouquet-id> """ bid = page.split('=')[1] logging.debug("[App::run] debug: changing bouquet list to [" + bid + "]") try: id = int(bid) except ValueError: html = html_header(openetv_config) if rb_res: html += r_bouquets.list_bouquets() else: html += "<b>Error: could not get bouquet list!</b>" html += html_menu(openetv_config, vlc_quality, active_channel, active_channel_name, max_channels) html += "<b>Error: bouquet id is invalid!</b><br>" html += html_footer(openetv_config) write_data = "HTTP/1.1 200 OK\n" write_data += "Content-Length: %d\n" % len(html) write_data += "Content-Type: text/html\n\n" write_data += html c.send(write_data) c.close() if not 0 <= int(bid) < max_bouquets: html = html_header(openetv_config) if rb_res: html += r_bouquets.list_bouquets() else: html += "<b>Error: could not get bouquet list!</b>" html += html_menu(openetv_config, vlc_quality, active_channel, active_channel_name, max_channels) html += "<b>Error: bouquetplaylist id is not in range between 0 and 999!</b><br>" html += html_footer(openetv_config) write_data = "HTTP/1.1 200 OK\n" write_data += "Content-Length: %d\n" % len(html) write_data += "Content-Type: text/html\n\n" write_data += html c.send(write_data) c.close() if rb_res: # select bouquet bouquet_id = id bouquet = r_bouquets.set_active_bouquet(bouquet_id) bouquet_name = bouquet[0] bouquet_ref = bouquet[1] html = html_header(openetv_config) if rb_res: html += r_bouquets.list_bouquets() else: html += "<b>Error: could not get bouquet list!</b>" # refresh the channels rc_res = r_channels.refresh_channel_list(bouquet_name, bouquet_ref) if rc_res: html += r_channels.list_channels() html += html_menu(openetv_config, vlc_quality, active_channel, active_channel_name, max_channels) html += html_footer(openetv_config) write_data = "HTTP/1.1 200 OK\n" write_data += "Content-Length: %d\n" % len(html) write_data += "Content-Type: text/html\n\n" write_data += html c.send(write_data) elif page[:6] == "/start": """ Expected parameters: /start=<channel-id> """ cid = page.split('=')[1] logging.debug("[App::run] debug: start channel id [" + cid + "]") try: id = int(cid) except ValueError: html = html_header(openetv_config) if rb_res: html += r_bouquets.list_bouquets() else: html += "<b>Error: could not get bouquet list!</b>" html += html_menu(openetv_config, vlc_quality, active_channel, active_channel_name, max_channels) html += "<b>Error: playlist id is invalid!</b><br>" html += html_footer(openetv_config) write_data = "HTTP/1.1 200 OK\n" write_data += "Content-Length: %d\n" % len(html) write_data += "Content-Type: text/html\n\n" write_data += html c.send(write_data) c.close() if not 0 <= int(id) < max_channels: html = html_header(openetv_config) if rb_res: html += r_bouquets.list_bouquets() else: html += "<b>Error: could not get bouquet list!</b>" html += html_menu(openetv_config, vlc_quality, active_channel, active_channel_name, max_channels) html += "<b>Error: playlist id is not in range between 0 and 999!</b><br>" html += html_footer(openetv_config) write_data = "HTTP/1.1 200 OK\n" write_data += "Content-Length: %d\n" % len(html) write_data += "Content-Type: text/html\n\n" write_data += html c.send(write_data) c.close() html = html_header(openetv_config) if rb_res: html += r_bouquets.list_bouquets() else: html += "<b>Error: could not get bouquet list!</b>" # play the selected channel r_channels.play_channel(id, vlc_quality) # get current active channels active_channel = r_channels.get_active_channel() active_channel_name = r_channels.get_active_channel_name() if rc_res: html += r_channels.list_channels() html += html_menu(openetv_config, vlc_quality, active_channel, active_channel_name, max_channels) html += html_footer(openetv_config) write_data = "HTTP/1.1 200 OK\n" write_data += "Content-Length: %d\n" % len(html) write_data += "Content-Type: text/html\n\n" write_data += html c.send(write_data) # shutdown the socket, otherwise the client still thinks it recieves data c.shutdown(socket.SHUT_RDWR) elif page[:5] == "/stop": """ Expected parameters: none """ logging.debug("[App::run] debug: stop channel id [%d" % active_channel + "]") if active_channel < max_channels: html = html_header(openetv_config) if rb_res: html += r_bouquets.list_bouquets() else: html += "<b>Error: could not get bouquet list!</b>" # stop the transcoding process stop_res = r_channels.stop_channel() # get current active channels active_channel = r_channels.get_active_channel() active_channel_name = r_channels.get_active_channel_name() if rc_res: html += r_channels.list_channels() html += html_menu(openetv_config, vlc_quality, active_channel, active_channel_name, max_channels) if not stop_res: html += "<b>Error: unable to stop stream, nothing is playing!</b><br>\n" html += html_footer(openetv_config) else: html = html_header(openetv_config) if rb_res: html += r_bouquets.list_bouquets() else: html += "<b>Error: could not get bouquet list!</b>" if rc_res: html += r_channels.list_channels() html += html_menu(openetv_config, vlc_quality, active_channel, active_channel_name, max_channels) html += html_footer(openetv_config) write_data = "HTTP/1.1 200 OK\n" write_data += "Content-Length: %d\n" % len(html) write_data += "Content-Type: text/html\n\n" write_data += html c.send(write_data) elif page[:8] == "/refresh": """ Expected parameters: "bouquet" or "channel" """ type = page.split('=')[1] html = html_header(openetv_config) # refresh bouquets if type == "bouquet": rb_res = r_bouquets.refresh_bouquet_list() if rb_res: html += r_bouquets.list_bouquets() # refresh the channel list if type == "channel": rc_res = r_channels.refresh_channel_list(bouquet_name, bouquet_ref) if rc_res: html += r_channels.list_channels() else: html += "<b>Error: could not get bouquet list!</b>" html += html_menu(openetv_config, vlc_quality, active_channel, active_channel_name, max_channels) html += html_footer(openetv_config) write_data = "HTTP/1.1 200 OK\n" write_data += "Content-Length: %d\n" % len(html) write_data += "Content-Type: text/html\n\n" write_data += html c.send(write_data) logging.debug("[App::run] closing connection") c.close()
addon = xbmcaddon.Addon() addonname = addon.getAddonInfo('name') sys.path.insert(0, os.path.join(addon.getAddonInfo('path'), 'resources', 'lib')) from flask import (Flask, render_template, Response, redirect, url_for, request, jsonify, abort) from channels import Channels logging.basicConfig(format=addon.getSetting('log_format'), level=addon.getSetting('log_level'), filename=os.path.join(addon.getAddonInfo('path'), 'addon.log')) logger = logging.getLogger(__name__) app = Flask(__name__) chls = Channels() def jsonloads(value): try: return json.loads(value) except: return value @app.route('/') def home(): return render_template('home.html') @app.route('/api/groups/get')
from flask_instance import FlaskInstance from jwt_controller import JWTController from synchronizer import Synchronizer import logging # Import http methods from clients import Clients from channels import Channels clients = Clients() channels = Channels() logging.basicConfig(level=logging.DEBUG) # Configure logging # Configure flask flask_app = FlaskInstance().__getinstance__ app = flask_app.get_app() # Creating symmetric key for the server jwt = JWTController().__get_instance__ jwt.set_global_key(jwt.generate_new_symmetric_key()) logging.info(f"Use the following key to encrypt the data in order to talk with this server in external connections: {jwt.get_global_key}") syncker = Synchronizer().__get_instance__ # Configure endpoints # Client endpoints flask_app.add_endpoint('/user', "new_user", clients.add_user, ['post']) flask_app.add_endpoint('/user/<user>', 'delete_user', clients.delete_user, ['delete']) flask_app.add_endpoint('/users', 'get_all_users', clients.get_all_users, ['get'])