Exemplo n.º 1
0
    def _status_playing(self):
        text = self.do_format(self.fmt_playing)

        if (self.do_color_progress and self.status and self.status.get(
                'time', None)):
            elapsed, total = self.status['time'].split(':')
            percent = float(elapsed) / float(total)
            progress = int(percent * len(text))

            is_pause = self.status['state'] == 'pause'

            if is_pause:
                color = self.pause_color
                color_progress = self.pause_progress_color
            else:
                color = self.foreground
                color_progress = self.foreground_progress

            s = '<span color="%s">%s</span>' % (
                utils.hex(color_progress),
                pangocffi.markup_escape_text(text[:progress])
            )
            rest = pangocffi.markup_escape_text(text[progress:])
            s += '<span color="%s">%s</span>' % (
                    utils.hex(color),
                    rest
            )

            return s

        else:
            return pangocffi.markup_escape_text(text)
Exemplo n.º 2
0
    def _status_playing(self):
        text = self.do_format(self.fmt_playing)

        if (self.do_color_progress and self.status
                and self.status.get('time', None)):
            elapsed, total = self.status['time'].split(':')
            percent = float(elapsed) / float(total)
            progress = int(percent * len(text))

            is_pause = self.status['state'] == 'pause'

            if is_pause:
                color = self.pause_color
                color_progress = self.pause_progress_color
            else:
                color = self.foreground
                color_progress = self.foreground_progress

            s = '<span color="%s">%s</span>' % (utils.hex(color_progress),
                                                pangocffi.markup_escape_text(
                                                    text[:progress]))
            rest = pangocffi.markup_escape_text(text[progress:])
            s += '<span color="%s">%s</span>' % (utils.hex(color), rest)

            return s

        else:
            return pangocffi.markup_escape_text(text)
Exemplo n.º 3
0
    def poll(self):
        # if we don't have valid credentials, update them
        if not hasattr(self, 'credentials') or self.credentials.invalid:
            self.cred_init()
            return 'Credentials updating'

        access_token = self.credentials.access_token['token']
        yammer = Yammer(access_token=access_token)
        contents = yammer.messages.from_my_feed()
        p_contents = yammer.messages.private()

        content_keys = [
            "unseen_message_count_following", "unseen_thread_count_following",
            "unseen_message_count_received", "unseen_thread_count_received",
            "unseen_message_count_algo", "unseen_thread_count_algo",
            "unseen_message_count_my_all", "unseen_thread_count_my_all"
        ]
        p_content_keys = ["unseen_thread_count"]
        data = {}
        for p_content_key in p_content_keys:
            data["private_" + p_content_key] = p_contents.meta[p_content_key]
        for content_key in content_keys:
            data[content_key] = contents.meta[content_key]

        for key in data.keys():
            if data[key] == 0:
                continue
            data[key] = '<span color="%s">%s</span>' % (utils.hex(
                self.reminder_color), data[key])
        return self.format % data
Exemplo n.º 4
0
    def _get_status(self):
        playing = self.msg_nc

        try:
            self.status = self.client.status()
            self.song = self.client.currentsong()
            if self.status['state'] != 'stop':
                text = self.do_format(self.fmt_playing)

                if self.do_color_progress and self.status.get('time'):
                    try:
                        elapsed, total = self.status['time'].split(':')
                        percent = float(elapsed) / float(total)
                        progress = int(percent * len(text))
                    except (ZeroDivisionError, ValueError):
                        playing = pangocffi.markup_escape_text(text)
                    else:
                        playing = '<span color="{0}">{1}</span>{2}'.format(
                            utils.hex(self.foreground_progress),
                            pangocffi.markup_escape_text(text[:progress]),
                            pangocffi.markup_escape_text(text[progress:])
                        )
                else:
                    playing = pangocffi.markup_escape_text(text)
            else:
                playing = self.do_format(self.fmt_stopped)

        except Exception:
            logger.exception('Mpd error on update')

        return playing
Exemplo n.º 5
0
    def poll(self):
        # if we don't have valid credentials, update them
        if not hasattr(self, 'credentials') or self.credentials.invalid:
            self.cred_init()
            return 'Credentials updating'

        access_token = self.credentials.access_token['token']
        yammer = Yammer(access_token=access_token)
        contents = yammer.messages.from_my_feed()
        p_contents = yammer.messages.private()

        content_keys = [
            "unseen_message_count_following",
            "unseen_thread_count_following",
            "unseen_message_count_received",
            "unseen_thread_count_received",
            "unseen_message_count_algo",
            "unseen_thread_count_algo",
            "unseen_message_count_my_all",
            "unseen_thread_count_my_all"]
        p_content_keys = [
            "unseen_thread_count"]
        data = {}
        for p_content_key in p_content_keys:
            data["private_" + p_content_key] = p_contents.meta[p_content_key]
        for content_key in content_keys:
            data[content_key] = contents.meta[content_key]

        for key in data.keys():
            if data[key] == 0:
              continue
            data[key] = '<span color="%s">%s</span>' % (
                utils.hex(self.reminder_color),
                data[key])
        return self.format % data
Exemplo n.º 6
0
    def poll(self):
        # if we don't have valid credentials, update them
        if not hasattr(self, 'credentials') or self.credentials.invalid:
            self.cred_init()

        # Create an httplib2.Http object to handle our HTTP requests and
        # authorize it with our credentials from self.cred_init
        http = self.credentials.authorize(httplib2.Http())
        service = discovery.build('calendar', 'v3', http=http)

        # current timestamp
        now = datetime.datetime.utcnow().isoformat('T') + 'Z'
        data = {}

        # grab the next event
        events = service.events().list(
            calendarId=self.calendar,
            singleEvents=True,
            timeMin=now,
            maxResults='1',
            orderBy='startTime'
        ).execute()
        self.qtile.log.info('calendar json data: %s' % str(events))

        # get items list
        try:
            event = events.get('items', [])[0]
        except IndexError:
            return 'No appointments scheduled'

        # get reminder time
        try:
            remindertime = datetime.timedelta(
                0,
                int(
                    event['reminders']['overrides'][0]['minutes']
                ) * 60
            )
        except (IndexError, ValueError, AttributeError, KeyError):
            remindertime = datetime.timedelta(0, 0)

        time = re.sub(
            ':.{2}-.*$',
            '',
            event['start']['dateTime'].replace('T', ' ')
        )

        data = event['summary'] + ' ' + time

        # colorize the event if it is upcoming
        parse_result = dateutil.parser.parse(event['start']['dateTime'], ignoretz=True)
        if parse_result - remindertime <= datetime.datetime.now():
            self.foreground = utils.hex(self.reminder_color)
        else:
            self.foreground = self.default_foreground

        # XXX: FIXME: qtile dies completely silently if we return unicode here
        # in python2.
        return str(data)
Exemplo n.º 7
0
    def poll(self):
        # if we don't have valid credentials, update them
        if not hasattr(self, 'credentials') or self.credentials.invalid:
            self.cred_init()
            data = {'next_event': 'Credentials updating'}
            return data

        # Create an httplib2.Http object to handle our HTTP requests and
        # authorize it with our credentials from self.cred_init
        http = httplib2.Http()
        http = self.credentials.authorize(http)

        service = build('calendar', 'v3', http=http)

        # current timestamp
        now = datetime.datetime.utcnow().isoformat('T') + 'Z'
        data = {}

        # grab the next event
        events = service.events().list(calendarId=self.calendar,
                                       singleEvents=True,
                                       timeMin=now,
                                       maxResults='1',
                                       orderBy='startTime').execute()

        # get items list
        try:
            event = events.get('items', [])[0]
        except IndexError:
            data = {'next_event': 'No appointments scheduled'}
            return data

        # get reminder time
        try:
            remindertime = datetime.timedelta(
                0,
                int(event.get('reminders').get('overrides')[0].get('minutes'))
                * 60)
        except:
            remindertime = datetime.timedelta(0, 0)

        # format the data
        data = {
            'next_event':
            event['summary'] + ' ' + re.sub(
                ':.{2}-.*$', '', event['start']['dateTime'].replace('T', ' '))
        }
        parse_result = dateutil.parser.parse(event['start']['dateTime'],
                                             ignoretz=True)
        if parse_result - remindertime <= datetime.datetime.now():
            data = {
                'next_event':
                '<span color="' + utils.hex(self.reminder_color) + '">' +
                data['next_event'] + '</span>'
            }

        # return the data
        return data
Exemplo n.º 8
0
    def poll(self):
        # if we don't have valid credentials, update them
        if not hasattr(self, 'credentials') or self.credentials.invalid:
            self.cred_init()
            return 'Credentials updating'

        # Create an httplib2.Http object to handle our HTTP requests and
        # authorize it with our credentials from self.cred_init
        http = httplib2.Http()
        http = self.credentials.authorize(http)

        service = build('calendar', 'v3', http=http)

        # current timestamp
        now = datetime.datetime.utcnow().isoformat('T') + 'Z'
        data = {}

        # grab the next event
        events = service.events().list(
            calendarId=self.calendar,
            singleEvents=True,
            timeMin=now,
            maxResults='1',
            orderBy='startTime'
        ).execute()

        # get items list
        try:
            event = events.get('items', [])[0]
        except IndexError:
            return 'No appointments scheduled'

        # get reminder time
        try:
            remindertime = datetime.timedelta(
                0,
                int(
                    event.get('reminders').get('overrides')[0].get('minutes')
                ) * 60
            )
        except (IndexError, ValueError, AttributeError):
            remindertime = datetime.timedelta(0, 0)

        time = re.sub(
            ':.{2}-.*$',
            '',
            event['start']['dateTime'].replace('T', ' ')
        )

        data = event['summary'] + ' ' + time

        # colorize the event if it is upcoming
        parse_result = dateutil.parser.parse(event['start']['dateTime'], ignoretz=True)
        if parse_result - remindertime <= datetime.datetime.now():
            data = '<span color="%s">%s</span>' % (utils.hex(self.reminder_color), data)

        return data
Exemplo n.º 9
0
    def __init__(self, **config):
        """Constructor."""
        super().__init__(None, **config)

        self.add_defaults(Mpd2.defaults)
        self.client = MPDClient()
        self.client.timeout = self.timeout
        self.client.idletimeout = self.idletimeout
        if self.color_progress:
            self.color_progress = utils.hex(self.color_progress)
Exemplo n.º 10
0
    def poll(self):
        # get today and tomorrow
        now = datetime.datetime.now()
        tomorrow = now + datetime.timedelta(days=1)
        # get reminder time in datetime format
        remtime = datetime.timedelta(minutes=self.remindertime)

        # parse khal output for the next seven days
        # and get the next event
        args = ['khal', 'agenda', '--days', str(self.lookahead)]
        cal = subprocess.Popen(args, stdout=subprocess.PIPE)
        output = cal.communicate()[0].decode('utf-8')
        output = output.split('\n')
        if len(output) < 2:
            return 'No appointments scheduled'
        date = 'unknown'
        endtime = None
        for i in range(len(output)):  # pylint: disable=consider-using-enumerate
            if output[i].strip() == '':
                continue
            try:
                starttime = dateutil.parser.parse(date + ' ' + output[i][:5],
                                                  ignoretz=True)
                endtime = dateutil.parser.parse(date + ' ' + output[i][6:11],
                                                ignoretz=True)
            except ValueError:
                try:
                    if output[i] == 'Today:':
                        date = str(now.month) + '/' + str(now.day) + '/' + \
                            str(now.year)
                    elif output[i] == 'Tomorrow:':
                        date = str(tomorrow.month) + '/' + str(tomorrow.day) + \
                            '/' + str(tomorrow.year)
                    else:
                        dateutil.parser.parse(output[i])
                        date = output[i]
                        continue
                except ValueError:
                    pass  # no date.
            if endtime is not None and endtime > now:
                data = date.replace(':', '') + ' ' + output[i]
                break
            else:
                data = 'No appointments in next ' + \
                    str(self.lookahead) + ' days'

        # get rid of any garbage in appointment added by khal
        data = ''.join(filter(lambda x: x in string.printable, data))
        # colorize the event if it is within reminder time
        if (starttime - remtime <= now) and (endtime > now):
            self.foreground = utils.hex(self.reminder_color)
        else:
            self.foreground = self.default_foreground

        return data
Exemplo n.º 11
0
    def poll(self):
        # get today and tomorrow
        now = datetime.datetime.now()
        tomorrow = now + datetime.timedelta(days=1)
        # get reminder time in datetime format
        remtime = datetime.timedelta(minutes=self.remindertime)

        # parse khal output for the next seven days
        # and get the next event
        args = ['khal', 'agenda', '--days', str(self.lookahead)]
        cal = subprocess.Popen(args, stdout=subprocess.PIPE)
        output = cal.communicate()[0].decode('utf-8')
        output = output.split('\n')
        if len(output) < 2:
            return 'No appointments scheduled'
        date = 'unknown'
        endtime = None
        for i in range(len(output)):  # pylint: disable=consider-using-enumerate
            if output[i].strip() == '':
                continue
            try:
                starttime = dateutil.parser.parse(date + ' ' + output[i][:5],
                                                  ignoretz=True)
                endtime = dateutil.parser.parse(date + ' ' + output[i][6:11],
                                                ignoretz=True)
            except ValueError:
                try:
                    if output[i] == 'Today:':
                        date = str(now.month) + '/' + str(now.day) + '/' + \
                            str(now.year)
                    elif output[i] == 'Tomorrow:':
                        date = str(tomorrow.month) + '/' + str(tomorrow.day) + \
                            '/' + str(tomorrow.year)
                    else:
                        dateutil.parser.parse(output[i])
                        date = output[i]
                        continue
                except ValueError:
                    pass  # no date.
            if endtime is not None and endtime > now:
                data = date.replace(':', '') + ' ' + output[i]
                break
            else:
                data = 'No appointments in next ' + \
                    str(self.lookahead) + ' days'

        # get rid of any garbage in appointment added by khal
        data = ''.join(filter(lambda x: x in string.printable, data))
        # colorize the event if it is within reminder time
        if (starttime - remtime <= now) and (endtime > now):
            self.foreground = utils.hex(self.reminder_color)
        else:
            self.foreground = self.default_foreground

        return data
Exemplo n.º 12
0
    def poll(self):
        # if we don't have valid credentials, update them
        if not hasattr(self, 'credentials') or self.credentials.invalid:
            self.cred_init()

        # Create an httplib2.Http object to handle our HTTP requests and
        # authorize it with our credentials from self.cred_init
        http = self.credentials.authorize(httplib2.Http())
        service = discovery.build('calendar', 'v3', http=http)

        # current timestamp
        now = datetime.datetime.utcnow().isoformat('T') + 'Z'
        data = {}

        # grab the next event
        events = service.events().list(calendarId=self.calendar,
                                       singleEvents=True,
                                       timeMin=now,
                                       maxResults='1',
                                       orderBy='startTime').execute()
        logger.info('calendar json data: %s', events)

        # get items list
        try:
            event = events.get('items', [])[0]
        except IndexError:
            return 'No appointments scheduled'

        # get reminder time
        try:
            remindertime = datetime.timedelta(
                0,
                int(event['reminders']['overrides'][0]['minutes']) * 60)
        except (IndexError, ValueError, AttributeError, KeyError):
            remindertime = datetime.timedelta(0, 0)

        time = re.sub(':.{2}-.*$', '',
                      event['start']['dateTime'].replace('T', ' '))

        try:
            data = event['summary'] + ' ' + time
        except KeyError:
            data = 'Event summary not specified in calendar ' + time

        # colorize the event if it is upcoming
        parse_result = dateutil.parser.parse(event['start']['dateTime'],
                                             ignoretz=True)
        if parse_result - remindertime <= datetime.datetime.now():
            self.foreground = utils.hex(self.reminder_color)
        else:
            self.foreground = self.default_foreground

        # XXX: FIXME: qtile dies completely silently if we return unicode here
        # in python2.
        return str(data)
Exemplo n.º 13
0
 def set_notif_text(self, notif):
     self.text = pangocffi.markup_escape_text(notif.summary)
     urgency = getattr(notif.hints.get('urgency'), "value", 1)
     if urgency != 1:
         self.text = '<span color="%s">%s</span>' % (
             utils.hex(self.foreground_urgent if urgency ==
                       2 else self.foreground_low), self.text)
     if notif.body:
         self.text = '<span weight="bold">%s</span> - %s' % (
             self.text, pangocffi.markup_escape_text(notif.body))
     if self.audiofile and path.exists(self.audiofile):
         self.qtile.cmd_spawn("aplay -q '%s'" % self.audiofile)
Exemplo n.º 14
0
    def poll(self):
        # if we don't have valid credentials, update them
        if not hasattr(self, "credentials") or self.credentials.invalid:
            self.cred_init()

        # Create an httplib2.Http object to handle our HTTP requests and
        # authorize it with our credentials from self.cred_init
        http = self.credentials.authorize(httplib2.Http())
        service = discovery.build("calendar", "v3", http=http)

        # current timestamp
        now = datetime.datetime.utcnow().isoformat("T") + "Z"
        data = {}

        # grab the next event
        events = (
            service.events()
            .list(calendarId=self.calendar, singleEvents=True, timeMin=now, maxResults="1", orderBy="startTime")
            .execute()
        )
        logger.info("calendar json data: %s", events)

        # get items list
        try:
            event = events.get("items", [])[0]
        except IndexError:
            return "No appointments scheduled"

        # get reminder time
        try:
            remindertime = datetime.timedelta(0, int(event["reminders"]["overrides"][0]["minutes"]) * 60)
        except (IndexError, ValueError, AttributeError, KeyError):
            remindertime = datetime.timedelta(0, 0)

        time = re.sub(":.{2}-.*$", "", event["start"]["dateTime"].replace("T", " "))

        try:
            data = event["summary"] + " " + time
        except KeyError:
            data = "Event summary not specified in calendar " + time

        # colorize the event if it is upcoming
        parse_result = dateutil.parser.parse(event["start"]["dateTime"], ignoretz=True)
        if parse_result - remindertime <= datetime.datetime.now():
            self.foreground = utils.hex(self.reminder_color)
        else:
            self.foreground = self.default_foreground

        # XXX: FIXME: qtile dies completely silently if we return unicode here
        # in python2.
        return str(data)
Exemplo n.º 15
0
    def poll(self):
        # if we don't have valid credentials, update them
        if not hasattr(self, "credentials") or self.credentials.invalid:
            self.cred_init()
            data = {"next_event": "Credentials updating"}
            return data

        # Create an httplib2.Http object to handle our HTTP requests and
        # authorize it with our credentials from self.cred_init
        http = httplib2.Http()
        http = self.credentials.authorize(http)

        service = build("calendar", "v3", http=http)

        # current timestamp
        now = datetime.datetime.utcnow().isoformat("T") + "Z"
        data = {}

        # grab the next event
        events = (
            service.events()
            .list(calendarId=self.calendar, singleEvents=True, timeMin=now, maxResults="1", orderBy="startTime")
            .execute()
        )

        # get items list
        try:
            event = events.get("items", [])[0]
        except IndexError:
            data = {"next_event": "No appointments scheduled"}
            return data

        # get reminder time
        try:
            remindertime = datetime.timedelta(0, int(event.get("reminders").get("overrides")[0].get("minutes")) * 60)
        except:
            remindertime = datetime.timedelta(0, 0)

        # format the data
        data = {
            "next_event": event["summary"] + " " + re.sub(":.{2}-.*$", "", event["start"]["dateTime"].replace("T", " "))
        }
        parse_result = dateutil.parser.parse(event["start"]["dateTime"], ignoretz=True)
        if parse_result - remindertime <= datetime.datetime.now():
            data = {
                "next_event": '<span color="' + utils.hex(self.reminder_color) + '">' + data["next_event"] + "</span>"
            }

        # return the data
        return data
Exemplo n.º 16
0
    def alloc_color(self, color):
        """
        Flexible color allocation.
        """
        try:
            return self.conn.conn.core.AllocNamedColor(self.cid, len(color), color).reply()
        except xcffib.xproto.NameError:

            def x8to16(i):
                return 0xFFFF * (i & 0xFF) // 0xFF

            color = hex(color)
            r = x8to16(int(color[-6] + color[-5], 16))
            g = x8to16(int(color[-4] + color[-3], 16))
            b = x8to16(int(color[-2] + color[-1], 16))
            return self.conn.conn.core.AllocColor(self.cid, r, g, b).reply()
Exemplo n.º 17
0
    def poll(self):
        # get today and tomorrow
        now = datetime.datetime.now()
        # get reminder time in datetime format
        remtime = datetime.timedelta(minutes=self.remindertime)

        # parse khal output for the next seven days
        # and get the next event
        args = ['khal', 'list', 'now', str(self.lookahead) + 'd']
        cal = subprocess.Popen(args, stdout=subprocess.PIPE)
        output = cal.communicate()[0].decode('utf-8')
        if output == 'No events\n':
            return 'No appointments in next ' + \
                    str(self.lookahead) + ' days'
        output = output.split('\n')

        date = 'unknown'
        starttime = None
        endtime = None

        # output[0] = 'Friday, 15/04/1976'
        outputsplitted = output[0].split(' ')
        date = outputsplitted[1]

        # output[1] = '[ ][12:00-13:00] dentist'
        try:
            output_nb = output[1].strip(' ')
            starttime = dateutil.parser.parse(date + ' ' + output_nb[:5],
                                              ignoretz=True)
            endtime = dateutil.parser.parse(date + ' ' + output_nb[6:11],
                                            ignoretz=True)
        except ValueError:
            # all day event output contains no start nor end time.
            starttime = dateutil.parser.parse(date + ' 00:00', ignoretz=True)
            endtime = starttime + datetime.timedelta(hours=23, minutes=59)

        data = output[0].replace(',', '') + ' ' + output[1]

        # get rid of any garbage in appointment added by khal
        data = ''.join(filter(lambda x: x in string.printable, data))
        # colorize the event if it is within reminder time
        if (starttime - remtime <= now) and (endtime > now):
            self.foreground = utils.hex(self.reminder_color)
        else:
            self.foreground = self.default_foreground

        return data
Exemplo n.º 18
0
    def __init__(self, **config):
        """Constructor."""
        super().__init__(None, **config)

        self.add_defaults(Mpd2.defaults)
        self.client = MPDClient()
        self.client.timeout = self.timeout
        self.client.idletimeout = self.idletimeout
        if self.color_progress:
            self.color_progress = utils.hex(self.color_progress)

        # remap self.keys as mouse_buttons for new button_press functionality.
        # so we don't break existing configurations.
        # TODO: phase out use of self.keys in favor of self.mouse_buttons
        if self.mouse_buttons == {}:
            for k in self.keys:
                if self.keys[k] is not None:
                    self.mouse_buttons[self.keys[k]] = k
Exemplo n.º 19
0
 def set_notif_text(self, notif):
     self.text = pangocffi.markup_escape_text(notif.summary)
     urgency = getattr(notif.hints.get("urgency"), "value", 1)
     if urgency != 1:
         self.text = '<span color="%s">%s</span>' % (
             utils.hex(self.foreground_urgent if urgency == 2 else self.foreground_low),
             self.text,
         )
     if notif.body:
         self.text = '<span weight="bold">%s</span> - %s' % (
             self.text,
             pangocffi.markup_escape_text(notif.body),
         )
     if callable(self.parse_text):
         try:
             self.text = self.parse_text(self.text)
         except:  # noqa: E722
             logger.exception("parse_text function failed:")
     if self.audiofile and path.exists(self.audiofile):
         self.qtile.cmd_spawn("aplay -q '%s'" % self.audiofile)
Exemplo n.º 20
0
 def _highlight_text(self, text) -> str:
     color = utils.hex(self.cursor_color)
     text = '<span foreground="{0}">{1}</span>'.format(color, text)
     if self.show_cursor:
         text = "<u>{}</u>".format(text)
     return text