Esempio n. 1
0
    def __listen_for_dgram(self, addr, port, sock, owner):
    
        # table: src_addr -> data
        datas = {}
        
        while ((addr, port) in self.__listeners):
            data, src_addr = sock.recvfrom(4096)

            #print len(data), data


            if (not src_addr in datas):
                datas[src_addr] = ""

            if (data):
                datas[src_addr] += data
                
            req = HTTPRequest()
            req.set_source(src_addr)
            req.feed(data)
            logging.debug("[httpserv] received %s dgram from: %s",
                          req.get_method(), str(src_addr))
            
            
            if (req.finished()):
                self.__emit_dgram(owner, sock, req)
                
                del datas[src_addr]
Esempio n. 2
0
    def __connect(self, host, port):
        """
        Opens an asynchronous connection to the given host and port.
        """

        logging.debug("[conn %s] new HTTP connection: %s",
                      self._get_id(), "http://%s:%d" % (host, port))

        if (self.__sock):
            self.__sock.close()

        now = time.time()
        _connection_resource.acquire()
        self.__finished.clear()
            
        try:
            self.__sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        except:
            #import traceback; traceback.print_exc()
            return

        try:
            self.__sock.connect((host, port or 80))
        except:
            #import traceback; traceback.print_exc()
            self.__emit(self.__abort, "Could not resolve hostname")
            return
            
        logging.profile(now, "[conn %s] connected to: %s",
                        self._get_id(), "http://%s:%d" % (host, port))
        self.__socket_connected = True
Esempio n. 3
0
    def __process_event_body(self, event_instance, body, uuid):

        if (not uuid in self.__handlers):
            event_instance.send_answer("HTTP/1.1 412 Precondition Failed")
            return

        #print "BODY", body
        prop_set = MiniXML(body).get_dom()
        prop = prop_set.get_child()

        for change in prop.get_children():
            signal_name = "changed::" + change.get_name().lower()

            # notify all subscribers
            for cb in self.__handlers[uuid]:
                try:
                    signal_value = change.get_child().get_value()
                except:
                    import traceback; traceback.print_exc()
                    signal_value = ""

                try:
                    cb(signal_name, signal_value)
                except:
                    logging.error(logging.stacktrace())
            #end for

            logging.debug("[upnp gena] signal emitted: %s = %s",
                          signal_name, signal_value)

        event_instance.send_answer("HTTP/1.1 200 OK")
Esempio n. 4
0
    def __init__(self, url, cb, *args):

        # location history for avoiding redirect loops
        self.__location_history = []

        addr = network.URL(url)
        HTTPConnection.__init__(self, addr.host, addr.port)

        logging.debug("[downloader] retrieving: %s", url)

        if (url.startswith("/")):
            t = threading.Thread(target=self.__get_local_file,
                                 args=[url, cb, args])
            t.setDaemon(True)
            t.start()

        else:
            if (addr.query_string):
                path = addr.path + "?" + addr.query_string
            else:
                path = addr.path
            self.putrequest("GET", path, "HTTP/1.1")
            self.putheader("Host", "%s:%d" % (addr.host, addr.port))
            self.putheader("User-Agent", "MediaBox")
            self.putheader("Connection", "close")
            self.endheaders()
            self.send("", self.__on_receive_data, cb, args)
Esempio n. 5
0
    def __on_receive_description_xml(self, data, a, t, location, uuid, xml):
        """
        Callback for checking the given UPnP device by parsing its
        description XML. Announces the availability of new devices.
        """

        if (data):
            xml[0] += data
        else:
            # if the device is not in the processing table, it has said
            # "bye bye" while processing the initialization; in that case
            # simply ignore it
            if (not uuid in self.__processing):
                return
    
            del self.__processing[uuid]
            
            
            if (xml[0]):
                dom = MiniXML(xml[0], _NS_DESCR).get_dom()
                descr = DeviceDescription(location, dom)
            
                # announce availability of device
                logging.info("[ssdp monitor] device discovered: %s (%s)" \
                             % (descr.get_friendly_name(), descr.get_device_type()))
                logging.debug("[ssdp monitor] propagating device: %s" % uuid)
                self.emit_message(msgs.SSDP_EV_DEVICE_DISCOVERED, uuid, descr)
Esempio n. 6
0
    def __on_enter_playing(self, sm):
    
        logging.debug("[mediaplayer] entering state PLAYING")
    
        # resume from suspension point and invalidate it
        susp = sm.get_property("suspension point")
        if (susp):
            uri, pos = susp
            sm.set_property("suspension point", None)
            print "seek from", pos
            self._seek(pos)
        else:
            self._play()
    
        sm.set_property("position", -1)
    
        # start playloop
        if (not self.__position_handler):
            t = time.time()
            logging.debug("[mediaplayer] starting position handler at %d",
                          int(t))
            self.__position_handler = \
                  gobject.timeout_add(0, self.__update_position, 0, t)

        # notify
        gobject.timeout_add(0, self.emit_event, self.EVENT_STATUS_CHANGED,
                        sm.get_property("context id"), self.STATUS_PLAYING)
Esempio n. 7
0
 def __on_leave_paused(self, sm):
 
     logging.debug("[mediaplayer] leaving state PAUSED")
 
     # stop idle timeout
     if (self.__idle_handler):
         gobject.source_remove(self.__idle_handler)
Esempio n. 8
0
    async def on_guild_join(self, guild: Guild):
        if guild.id not in self.join_locks:
            self.join_locks[guild.id] = Event()

        debug(f"Setting up Configuration for guild {guild.name}")

        if not self.permission_check(guild):
            await guild.text_channels[0].send(
                "I don't have the correct permissions, make sure manage_channels and"
                " manage_messages are enabled.")
            await guild.leave()
            return

        overwrites = {
            guild.default_role: PermissionOverwrite(read_messages=False),
            guild.me: PermissionOverwrite(read_messages=True,
                                          manage_messages=True),
            **{
                role: PermissionOverwrite(read_messages=True)
                for role in guild.roles if role.permissions.manage_channels
            }
        }

        channel = await guild.create_text_channel(
            self.bot.channel_name,
            overwrites=overwrites,
            topic=
            "This is the configuration channel for f-lute, please do NOT delete this, or the bot will leave"
        )

        self.join_locks[guild.id].set()
Esempio n. 9
0
    def __on_send_header(self, sock, cond, filepath, data):

        http = data[0]
        length = sock.send(http)
        data[0] = http[length:]
        logging.debug("FileServer sent:\n%s" % http)
        if (data[0]):
            return True

        else:
            if (not filepath):
                sock.close()
                self.__remove_client()
                return False

            try:
                partial = filepath + ".partial"
                fd = open(filepath, "r")
            except:
                import traceback
                traceback.print_exc()
                sock.close()
                self.__remove_client()
                return False

            self.__io_watch = gobject.io_add_watch(
                sock, gobject.IO_OUT | gobject.IO_HUP, self.__on_send_data, fd,
                partial, [""], [False])
            return False
Esempio n. 10
0
 def handle_COM_EV_APP_SHUTDOWN(self):
 
     logging.debug("[httpserv] closing sockets")
     for listener in self.__listeners.values():
         if (listener.iowatch):
             gobject.source_remove(listener.iowatch)
         listener.sock.close()
Esempio n. 11
0
 def __on_expire(self, uuid):
     """
     Timer for removing UPnP devices that expire.
     """
     
     logging.debug("[ssdp monitor] device expired: %s", uuid)
     del self.__expiration_handlers[uuid]
     self.__handle_ssdp_byebye(uuid)
Esempio n. 12
0
 def __handle_ssdp_byebye(self, uuid):
 
     logging.debug("[ssdp monitor] BYE-BYE from: %s", uuid)
     if (uuid in self.__servers):
         del self.__servers[uuid]
         if (uuid in self.__processing):
             del self.__processing[uuid]
         self.emit_message(msgs.SSDP_EV_DEVICE_GONE, uuid)
Esempio n. 13
0
 def __send_cmd(self, data):
 
     logging.debug("mplayer command:\n%s" % data)
     try:
         self.__stdin.write(data + "\n")
         self.__stdin.flush()
     except:
         self.__needs_restart = True
Esempio n. 14
0
    def __on_new_client(self, sock, cond):

        cnx, addr = sock.accept()
        self.__add_client()
        gobject.io_add_watch(cnx, gobject.IO_IN | gobject.IO_HUP,
                             self.__on_receive_request, [""])
        logging.debug("FileServer accepted new client")
        return True
Esempio n. 15
0
def dequeue_item(queue_name):
    item = redis.spop(queue_name)
    if item:
        item = item.decode('utf-8')
        if item.startswith("{") and item.endswith("}"):
            item = json.loads(item)
    logging.debug(u"Dequeuing item from {}:\t{}".format(queue_name, item))
    return item
Esempio n. 16
0
 def __get_mem_size(self):
 
     import os
     pid = os.getpid()
     size = int(open("/proc/%d/status" % pid, "r").read().splitlines()[15].split()[1])
     size /= 1024.0
     logging.debug("current Resident Set Size: %0.02f MB", size)
     return size
Esempio n. 17
0
 def __on_enter_error(self, sm):
 
     logging.debug("[mediaplayer] entering state ERROR")
 
     ctx_id = sm.get_property("context id")
     err = sm.get_property("error")
     sm.set_property("error", self.NO_ERROR)
     self.emit_event(self.EVENT_ERROR, ctx_id, err)
Esempio n. 18
0
    def _dump_xml(self):
        """
        Dumps the description XML.
        @since: 0.96
        """

        logging.debug("[upnp] Device Description [%s]\n%s" \
                      % (self.__location, self.__dom._dump()))
Esempio n. 19
0
    async def on_guild_join(self, guild: Guild):
        debug(f"Setting up VoiceChannel for guild {guild.name}")

        await self.bot.get_cog('Events').wait_for_join_complete(guild)
        channel = get(guild.text_channels, name=self.bot.channel_name)

        ctx = VoiceChannel(channel, self.bot)
        await ctx.setup()
        self.contexts[guild.id] = ctx
Esempio n. 20
0
 def __register_messages(self, mod):
     """
     Registers the messages of the given module.
     """
     
     if (hasattr(mod, "messages")):
         for msg in mod.messages:
             logging.debug("registering message: %s", msg)
             msgs._register(msg)
Esempio n. 21
0
    async def on_guild_join(self, guild: Guild):
        debug(f"Setting up RoleAccess for guild {guild.name}")

        await self.bot.get_cog('Events').wait_for_join_complete(guild)
        channel = get(guild.text_channels, name="flute-configuration")

        ctx = RoleAccess(channel)
        await ctx.setup()
        self.contexts[guild.id] = ctx
Esempio n. 22
0
 async def daily(self, ctx):
     log.debug("%s issued server command %s" %
               (str(ctx.message.author), str(ctx.message.content)))
     current_time = time.time()
     query = sql.db_query(
         "SELECT dailyRewardClaimed, dailyRewardStreak FROM Members WHERE UserID = %s "
         % (str(ctx.author.id)))
     last_advent = query[0][0]
     streak = query[0][1]
     if last_advent < current_time:
         next_advent = current_time + ((60 * 60) * 20)
         sql.execute_query(
             "UPDATE Members SET dailyRewardClaimed = %s WHERE UserID = %s "
             % (str(next_advent), str(ctx.author.id)))
         reward = random.randint(1, 4)
         if reward == 1:
             reward_name = "5000 Exp"
             add_exp(ctx.author.id, 5000)
         if reward == 2:
             reward_name = "$5.00"
             add_coins(ctx.author, float(5.00))
         if reward == 3:
             reward_name = "2 Crates"
             crates_no = sql.db_query(
                 "SELECT crates FROM Members WHERE UserID = %s" %
                 (str(ctx.author.id)))[0][0]
             crates_no = crates_no + 2
             sql.execute_query(
                 "UPDATE Members SET crates = %s WHERE UserID = %s" %
                 (str(crates_no), str(ctx.author.id)))
         if reward == 4:
             reward_name = "3 Crates"
             crates_no = sql.db_query(
                 "SELECT crates FROM Members WHERE UserID = %s" %
                 (str(ctx.author.id)))[0][0]
             crates_no = crates_no + 3
             sql.execute_query(
                 "UPDATE Members SET crates = %s WHERE UserID = %s" %
                 (str(crates_no), str(ctx.author.id)))
         embed = discord.Embed(title="Easter Reward",
                               description="You Won " + reward_name,
                               color=colour.primary)
         await ctx.send(embed=embed)
         new_streak = streak + 1
         sql.execute_query(
             "UPDATE Members SET dailyRewardStreak = %s WHERE UserID = %s "
             % (str(new_streak), str(ctx.author.id)))
     else:
         next_advent = last_advent
         time_difference = next_advent - current_time
         time_difference_string = time_phaser(time_difference)
         embed = discord.Embed(
             title="Error",
             description="You cannot use that command for another **%s**" %
             (time_difference_string),
             color=colour.reds)
         await ctx.send(embed=embed)
Esempio n. 23
0
 def __on_enter_idle(self, sm):
 
     logging.debug("[mediaplayer] entering state IDLE")
 
     # set suspension point
     pos = sm.get_property("position")
     total = sm.get_property("length")
     uri = self.__state_machine.get_property("uri")
     sm.set_property("suspension point", (uri, pos))
Esempio n. 24
0
def broadcast_byebye(notification_type, unique_service_name):
    """
    Broadcasts a SSDP BYE-BYE notification.
    @since: 2010.10.03
    """

    logging.debug("[ssdp] broadcasting BYE-BYE: %s", unique_service_name)
    data = _SSDP_BYEBYE % (notification_type, unique_service_name)
    network.send_datagram(SSDP_IP, SSDP_PORT, data)
Esempio n. 25
0
 def __on_leave_playing(self, sm):
 
     logging.debug("[mediaplayer] leaving state PLAYING")
 
     # stop playloop
     if (self.__position_handler):
         gobject.source_remove(self.__position_handler)
         logging.debug("[mediaplayer] stopping position handler")
     self.__position_handler = None
Esempio n. 26
0
    def handle_MEDIA_ACT_CHANGE_PLAY_FOLDER(self, folder):

        self.__play_folder = folder
        self.__play_files = [
            fl for fl in self.__browser.get_files()
            if not fl.mimetype.endswith("-folder")
        ]
        logging.debug("[navigator] clearing random items")
        self.__random_files = []
Esempio n. 27
0
def insert_db_user(member):
    try:
        sql.execute_query("INSERT INTO Members (UserID) VALUES ('%s')" %
                          (member.id))
    except:
        log.warn("User already exists in Database")
        try:
            log.debug(member.name)
        except:
            pass
Esempio n. 28
0
    def handle_CORE_EV_FOLDER_INVALIDATED(self, folder):

        logging.debug("[navigator] invalidating folder %s", str(folder))

        if (self.is_visible()):
            self.__browser.invalidate_folder(folder)

        if (folder and folder == self.__play_folder):
            self.__invalidate_play_files()
            """
Esempio n. 29
0
    def __on_message(self, bus, message):

        t = message.type
        #print "Message Type", t
        if (t == gst.MESSAGE_STATE_CHANGED):
            prev, new, pend = message.parse_state_changed()
            if (new == gst.STATE_PLAYING and self.__to_seek):
                self._seek(self.__to_seek)
                self.__to_seek = 0

        elif (t == gst.MESSAGE_EOS):
            self.__player.set_state(gst.STATE_NULL)
            self.__is_eof = True

        elif (t == gst.MESSAGE_ELEMENT):
            s = message.structure
            if (s.has_name("redirect")):
                url = s["new-location"]
                logging.debug("GStreamer got redirect: %s", url)
                self.__player.set_state(gst.STATE_NULL)
                self.__player.set_property("uri", url)
                self.__player.set_state(gst.STATE_PLAYING)

        elif (t == gst.MESSAGE_BUFFERING):
            self._report_buffering(0)
            #query = gst.query_new_buffering(gst.FORMAT_PERCENT)
            #if (self.__player.query(query)):
            #    fmt, start, stop, total = query.parse_buffering_range()
            #    print fmt, start, stop, total

        elif (t == gst.MESSAGE_ERROR):
            self.__player.set_state(gst.STATE_READY)
            err, debug = message.parse_error()
            logging.error("GStreamer Error:\n%s\n%s", err, debug)
            self._report_error(self.ERR_INVALID, "")

        elif (t == gst.MESSAGE_TAG):
            tags = message.parse_tag()
            for key in tags.keys():
                #print key #, tags[key]
                if (key == "title"):
                    self._report_tag("TITLE", tags[key])
                elif (key == "artist"):
                    self._report_tag("ARTIST", tags[key])
                elif (key == "album"):
                    self._report_tag("ALBUM", tags[key])
                elif (key == "bitrate"):
                    print "Bitrate: %0.1f kbps" % (tags[key] / 1000.0)
                elif (key == "image"):
                    if (type(tags[key]) == list):
                        self._report_tag("PICTURE", tags[key][0].data)
                    else:
                        self._report_tag("PICTURE", tags[key].data)
                    print "Found cover image"
Esempio n. 30
0
    def __finish(self):

        if (self.__close_connection and self.__sock):
            self.__sock.close()
            self.__sock = None

        self.__finished.set()
        _connection_resource.release()
            
        logging.debug("[conn %s] finished", self._get_id())
        if (not self.__close_connection):
            logging.debug("[conn %s] still alive", self._get_id())
Esempio n. 31
0
def alert():

    global messages
    while True:
        curr_len = len(messages)
        cnt = 0
        if config.debug:
            logging.debug('alerting metrics...(%s messages)' % curr_len)
        while cnt < curr_len:
            do(*messages.popleft())
            cnt += 1
        time.sleep(10)
Esempio n. 32
0
def fetch():

    global ready
    global plugins
    while True:
        if config.debug:
            logging.debug('fetching metrics...')
        for plugin in plugins:
            for target in plugin.targets:
                for metric in target.metrics:
                    update_metric(metric)
        ready = True
        time.sleep(10)
Esempio n. 33
0
def check():

    while True:
        if config.debug:
            logging.debug('checking metrics...')
        for plugin in plugins:
            for target in plugin.targets:
                for metric in target.metrics:
                    if metric.value is None:
                        update_metric(metric)
                    value = metric.value
                    if target.min <= value <= target.max:
                        reset(metric)
                    else:
                        if metric.retry < target.retry:
                            metric.retry += 1
                    if metric.retry == 3:
                        messages.append((target, deepcopy(metric)))
#                        metric.retry = 0 # re-schedule
        time.sleep(10) # check interval