Esempio n. 1
0
    def run(self):
        with socket.create_connection((self.host, self.port)) as s:
            # Skip "OK MPD ..."
            s.recv(8192)

            fdict = {}

            status = self._mpd_command(s, "status")
            currentsong = self._mpd_command(s, "currentsong")

            fdict = {
                "pos": int(status.get("song", 0)) + 1,
                "len": int(status["playlistlength"]),
                "status": self.status[status["state"]],
                "volume": int(status["volume"]),
                "title": currentsong.get("Title", ""),
                "album": currentsong.get("Album", ""),
                "artist": currentsong.get("Artist", ""),
                "song_length": TimeWrapper(currentsong.get("Time", 0)),
                "song_elapsed": TimeWrapper(float(status.get("elapsed", 0))),
                "bitrate": int(status.get("bitrate", 0)),
            }

            self.output = {
                "full_text": formatp(self.format, **fdict).strip(),
            }
Esempio n. 2
0
 def run(self):
     try:
         status = self._mpd_command(self.s, "status")
         currentsong = self._mpd_command(self.s, "currentsong")
         fdict = {
             "pos": int(status.get("song", 0)) + 1,
             "len": int(status["playlistlength"]),
             "status": self.status[status["state"]],
             "volume": int(status["volume"]),
             "title": currentsong.get("Title", ""),
             "album": currentsong.get("Album", ""),
             "artist": currentsong.get("Artist", ""),
             "song_length": TimeWrapper(currentsong.get("Time", 0)),
             "song_elapsed": TimeWrapper(float(status.get("elapsed", 0))),
             "bitrate": int(status.get("bitrate", 0)),
         }
         if not fdict["title"]:
             fdict["filename"] = '.'.join(
                 basename(currentsong["file"]).split('.')[:-1])
         else:
             fdict["filename"] = ""
         self.output = {
             "full_text": formatp(self.format, **fdict).strip(),
             "color": self.color,
         }
     except Exception as e:
         self.output = {
             "full_text": "error connecting MPD",
             "color": self.color
         }
Esempio n. 3
0
    def run(self):
        response = self._query_cmus()
        if response:
            fdict = {
                'file': response.get('file', ''),
                'status': self.status[response['status']],
                'title': response.get('tag_title', ''),
                'stream': response.get('stream', ''),
                'album': response.get('tag_album', ''),
                'artist': response.get('tag_artist', ''),
                'tracknumber': response.get('tag_tracknumber', 0),
                'song_length': TimeWrapper(response.get('duration', 0)),
                'song_elapsed': TimeWrapper(response.get('position', 0)),
                'bitrate': int(response.get('bitrate', 0)),
            }

            if fdict['stream']:
                fdict['artist'], fdict['title'] = _extract_artist_title(
                    fdict['stream'])
            elif not fdict['title']:
                filename = os.path.basename(fdict['file'])
                filebase, _ = os.path.splitext(filename)
                fdict['artist'], fdict['title'] = _extract_artist_title(
                    filebase)
            self.output = {
                "full_text": formatp(self.format, **fdict),
                "color": self.color
            }

        else:
            self.output = {
                "full_text": self.format_not_running,
                "color": self.color_not_running
            }
Esempio n. 4
0
    def run(self):
        status = self._mpd_command(self.s, "status")
        currentsong = self._mpd_command(self.s, "currentsong")
        fdict = {
            "pos": int(status.get("song", 0)) + 1,
            "len": int(status["playlistlength"]),
            "status": self.status[status["state"]],
            "volume": int(status["volume"]),

            "title": currentsong.get("Title", ""),
            "album": currentsong.get("Album", ""),
            "artist": currentsong.get("Artist", ""),
            "song_length": TimeWrapper(currentsong.get("Time", 0)),
            "song_elapsed": TimeWrapper(float(status.get("elapsed", 0))),
            "bitrate": int(status.get("bitrate", 0)),

        }

        for key in self.truncate_fields:
            if len(fdict[key]) > self.text_len:
                fdict[key] = fdict[key][:self.text_len - 1] + "…"

        if not fdict["title"] and "filename" in fdict:
            fdict["filename"] = '.'.join(
                basename(currentsong["file"]).split('.')[:-1])
        else:
            fdict["filename"] = ""
        self.output = {
            "full_text": formatp(self.format, **fdict).strip(),
            "color": self.color,
        }
Esempio n. 5
0
    def run(self):
        status = self._query_cmus()
        if not status:
            self.output = {"full_text": 'Not running', "color": self.color}
            return
        fdict = {
            'file': status.get('file', ''),
            'status': self.status[status["status"]],
            'title': status.get('tag_title', ''),
            'stream': status.get('stream', ''),
            'album': status.get('tag_album', ''),
            'artist': status.get('tag_artist', ''),
            'tracknumber': status.get('tag_tracknumber', 0),
            'song_length': TimeWrapper(status.get('duration', 0)),
            'song_elapsed': TimeWrapper(status.get('position', 0)),
            'bitrate': int(status.get("bitrate", 0)),
        }

        if fdict['stream']:
            fdict['artist'], fdict['title'] = _extract_artist_title(
                fdict['stream'])

        elif not fdict['title']:
            _, filename = os.path.split(fdict['file'])
            filebase, _ = os.path.splitext(filename)
            fdict['artist'], fdict['title'] = _extract_artist_title(filebase)

        fdict['title'] = fdict['title'].strip()
        fdict['artist'] = fdict['artist'].strip()

        self.output = {
            "full_text": formatp(self.format, **fdict),
            "color": self.color
        }
Esempio n. 6
0
    def run(self):
        try:
            status = self._mpd_command(self.s, "status")
            playback_state = status["state"]
            currentsong = self._mpd_command(self.s, "currentsong")
        except Exception:
            if self.hide_inactive:
                self.output = {
                    "full_text": ""
                }
            if hasattr(self, "data"):
                del self.data
            return

        fdict = {
            "pos": int(status.get("song", 0)) + 1,
            "len": int(status.get("playlistlength", 0)),
            "status": self.status[playback_state],
            "volume": int(status.get("volume", 0)),

            "title": currentsong.get("Title", ""),
            "album": currentsong.get("Album", ""),
            "artist": currentsong.get("Artist", ""),
            "album_artist": currentsong.get("AlbumArtist", ""),
            "song_length": TimeWrapper(currentsong.get("Time", 0)),
            "song_elapsed": TimeWrapper(float(status.get("elapsed", 0))),
            "bitrate": int(status.get("bitrate", 0)),
        }

        if not fdict["title"] and "file" in currentsong:
            fdict["filename"] = '.'.join(
                basename(currentsong["file"]).split('.')[:-1])
        else:
            fdict["filename"] = ""

        if self.max_field_len > 0:
            for key in self.truncate_fields:
                if len(fdict[key]) > self.max_field_len:
                    fdict[key] = fdict[key][:self.max_field_len - 1] + "…"

        self.data = fdict
        full_text = formatp(self.format, **fdict).strip()
        full_text_len = len(full_text)
        if full_text_len > self.max_len and self.max_len > 0:
            shrink = floor((self.max_len - full_text_len)
                           / len(self.truncate_fields)) - 1

            for key in self.truncate_fields:
                fdict[key] = fdict[key][:shrink] + "…"

            full_text = formatp(self.format, **fdict).strip()
        color_map = defaultdict(lambda: self.color, self.color_map)
        self.output = {
            "full_text": full_text,
            "color": color_map[playback_state],
        }
Esempio n. 7
0
    def run(self):
        urgent = False
        color = self.color

        try:
            battery = Battery.create(self.path)
        except FileNotFoundError:
            self.output = {
                "full_text": self.not_present_text,
                "color": self.not_present_color,
            }
            return

        fdict = {
            "battery_ident": self.battery_ident,
            "percentage": battery.percentage(),
            "percentage_design": battery.percentage(design=True),
            "consumption": battery.consumption(),
            "remaining": TimeWrapper(0, "%E%h:%M"),
            "bar": make_bar(battery.percentage()),
        }

        status = battery.status()
        if status in ["Charging", "Discharging"]:
            remaining = battery.remaining()
            fdict["remaining"] = TimeWrapper(remaining * 60, "%E%h:%M")
            if status == "Discharging":
                fdict["status"] = "DIS"
                if battery.percentage() <= self.alert_percentage:
                    urgent = True
                    color = self.critical_color
            else:
                fdict["status"] = "CHR"
                color = self.charging_color
        else:
            fdict["status"] = "FULL"
            color = self.full_color

        if self.alert and fdict["status"] == "DIS" and fdict[
                "percentage"] <= self.alert_percentage:
            DesktopNotification(
                title=formatp(self.alert_format_title, **fdict),
                body=formatp(self.alert_format_body, **fdict),
                icon="battery-caution",
                urgency=2,
                timeout=60,
            ).display()

        fdict["status"] = self.status[fdict["status"]]

        self.output = {
            "full_text": formatp(self.format, **fdict),
            "instance": self.battery_ident,
            "urgent": urgent,
            "color": color,
        }
Esempio n. 8
0
    def run(self):
        if self.state is not TimerState.stopped:
            diff = self.compare - time.time()

            if diff < 0 and self.state is TimerState.running:
                self.state = TimerState.overflow
                if self.on_overflow:
                    if callable(self.on_overflow):
                        self.on_overflow()
                    else:
                        execute(self.on_overflow)

            fmt = self.format
            color = self.color
            for rule in self.format_custom:
                if diff < rule[0]:
                    fmt = rule[1]
                    color = rule[2]
                    break
            urgent = self.overflow_urgent and self.state is TimerState.overflow

            self.output = {
                "full_text": format(TimeWrapper(abs(diff), fmt)),
                "color": color,
                "urgent": urgent,
            }
        else:
            self.output = {
                "full_text": self.format_stopped,
                "color": self.color_stopped,
            }
Esempio n. 9
0
    def run(self):
        if self.travis is None:
            self.travis = TravisPy.github_auth(self.github_token)
        repo = self.travis.repo(self.repo_slug)

        self.repo_status = self.repo_status_map.get(repo.last_build_state, repo.last_build_state)

        self.last_build_id = repo.last_build_id

        if repo.last_build_state == 'started':
            self.last_build_finished = None
            self.last_build_duration = None

        elif repo.last_build_state in ('failed', 'errored', 'cancelled', 'passed'):
            self.last_build_finished = self._format_time(repo.last_build_finished_at)
            self.last_build_duration = TimeWrapper(repo.last_build_duration, default_format=self.duration_format)

        self.output = dict(
            full_text=formatp(self.format, **vars(self)),
            short_text=self.short_format.format(**vars(self)),
        )
        if self.status_color_map:
            self.output['color'] = self.status_color_map.get(repo.last_build_state, self.color)
        else:
            self.output['color'] = self.color
Esempio n. 10
0
    def run(self):
        try:
            player = self.get_player()
        except dbus.exceptions.DBusException:
            self.output = {
                "full_text": "now_playing: d-bus error",
                "color": "#ff0000",
            }
            return

        properties = dbus.Interface(player, "org.freedesktop.DBus.Properties")
        get_prop = functools.partial(properties.Get,
                                     "org.mpris.MediaPlayer2.Player")
        currentsong = get_prop("Metadata")

        fdict = {
            "status":
            self.status[self.statusmap[get_prop("PlaybackStatus")]],
            "len":
            0,  # TODO: Use optional(!) TrackList interface for this to gain 100 % mpd<->now_playing compat
            "pos":
            0,
            "volume":
            int(get_prop("Volume") * 100),
            "title":
            currentsong.get("xesam:title", ""),
            "album":
            currentsong.get("xesam:album", ""),
            "artist":
            ", ".join(currentsong.get("xesam:artist", "")),
            "song_length":
            TimeWrapper((currentsong.get("mpris:length") or 0) / 1000**2),
            "song_elapsed":
            TimeWrapper((get_prop("Position") or 0) / 1000**2),
            "filename":
            "",
        }

        if not fdict["title"]:
            fdict["filename"] = '.'.join(
                basename((currentsong.get("xesam:url") or "")).split('.')[:-1])

        self.output = {
            "full_text": formatp(self.format, **fdict).strip(),
            "color": self.color,
        }
Esempio n. 11
0
    def run(self):
        urgent = False
        color = "#ffffff"

        battery = Battery.create(self.path)

        fdict = {
            "battery_ident": self.battery_ident,
            "percentage": battery.percentage(),
            "percentage_design": battery.percentage(design=True),
            "consumption": battery.consumption(),
            "remaining": TimeWrapper(0, "%E%h:%M"),
        }

        status = battery.status()
        if status in ["Charging", "Discharging"]:
            remaining = battery.remaining()
            fdict["remaining"] = TimeWrapper(remaining * 60, "%E%h:%M")
            if status == "Discharging":
                fdict["status"] = "DIS"
                if battery.percentage() <= self.alert_percentage:
                    urgent = True
                    color = "#ff0000"
            else:
                fdict["status"] = "CHR"
        else:
            fdict["status"] = "FULL"

        if self.alert and fdict["status"] == "DIS" and fdict[
                "percentage"] <= self.alert_percentage:
            DesktopNotification(
                title=formatp(self.alert_format_title, **fdict),
                body=formatp(self.alert_format_body, **fdict),
                icon="battery-caution",
                urgency=2,
                timeout=60,
            ).display()

        fdict["status"] = self.status[fdict["status"]]

        self.output = {
            "full_text": formatp(self.format, **fdict).strip(),
            "instance": self.battery_ident,
            "urgent": urgent,
            "color": color
        }
Esempio n. 12
0
 def run(self):
     try:
         status = self._mpd_command(self.s, "status")
         currentsong = self._mpd_command(self.s, "currentsong")
         fdict = {
             "pos": int(status.get("song", 0)) + 1,
             "len": int(status["playlistlength"]),
             "status": self.status[status["state"]],
             "volume": int(status["volume"]),
             "title": currentsong.get("Title", ""),
             "album": currentsong.get("Album", ""),
             "artist": currentsong.get("Artist", ""),
             "song_length": TimeWrapper(currentsong.get("Time", 0)),
             "song_elapsed": TimeWrapper(float(status.get("elapsed", 0))),
             "bitrate": int(status.get("bitrate", 0)),
         }
         self.output = {
             "full_text": formatp(self.format, **fdict).strip(),
         }
     except Exception as e:
         self.output = {"full_text": "error connecting MPD"}
Esempio n. 13
0
    def run(self):
        if self.circleci is None:
            self.circleci = Api(self.circleci_token)

        if self.workflows:
            if self.workflow_branch and not self.workflow_name:
                self.output = dict(
                    full_text='workflow_name must be specified!'
                )
                return

            project = {p['reponame']: p for p in self.circleci.get_projects()}.get(self.repo_name)
            if not self.workflow_branch:
                self.workflow_branch = project.get('default_branch')

            workflow_info = project['branches'].get(self.workflow_branch)['latest_workflows'].get(self.workflow_name)

            self.last_build_started = self._format_time(workflow_info.get('created_at'))
            self.repo_status = workflow_info.get('status')

            self.last_build_duration = ''  # TODO: gather this information once circleCI exposes it

        else:
            self.repo_summary = self.circleci.get_project_build_summary(
                self.repo_owner,
                self.repo_name,
                limit=1)
            if len(self.repo_summary) != 1:
                return
            self.repo_summary = self.repo_summary[0]

            self.repo_status = self.repo_summary.get('status')

            self.last_build_started = self._format_time(self.repo_summary.get('queued_at'))
            try:
                self.last_build_duration = TimeWrapper(
                    self.repo_summary.get('build_time_millis') / 1000,
                    default_format=self.duration_format)
            except TypeError:
                self.last_build_duration = 0

        if self.repo_status_map:
            self.repo_status = self.repo_status_map.get(self.repo_status, self.repo_status)

        self.output = dict(
            full_text=formatp(self.format, **vars(self)),
            short_text=self.short_format.format(**vars(self)),
        )
        if self.status_color_map:
            self.output['color'] = self.status_color_map.get(self.repo_status, self.color)
        else:
            self.output['color'] = self.color
Esempio n. 14
0
    def run(self):
        with open(self.file,'r') as f:
            seconds = float(f.read().split()[0])
            fdict = {
                "uptime" : TimeWrapper(seconds, "%h:%m"),
            }

        if self.alert:
            if seconds > self.seconds_alert:
                self.color = self.color_alert
        self.output = {
            "full_text": formatp(self.format, **fdict),
            "color": self.color
        }
Esempio n. 15
0
    def run(self):
        response = self._query_moc()

        if response:
            fdict = {
                'album':
                response.get('Album', ''),
                'artist':
                response.get('Artist', ''),
                'file':
                response.get('File', ''),
                'song_elapsed':
                TimeWrapper(response.get('CurrentSec', 0)),
                'song_length':
                TimeWrapper(response.get('TotalSec', 0)),
                'status':
                self.status[response['State'].lower()],
                'title':
                response.get('SongTitle', ''),
                'tracknumber':
                re.match(r'(\d*).*', response.get('Title', '')).group(1) or 0,
            }

            self.data = fdict

            self.output = {
                'full_text': formatp(self.format, **self.data),
                'color': self.color,
            }
        else:
            if hasattr(self, "data"):
                del self.data

            self.output = {
                'full_text': self.format_not_running,
                'color': self.color_not_running,
            }
Esempio n. 16
0
    def get_formatted_info(self, player):
        """Get player track info from playerctl"""

        result = {
            "status": "",
            "artist": "",
            "title": "",
            "album": "",
            "length": "",
        }

        status = player.props.status
        if status:
            result["status"] = self.status.get(status.lower(), "")
            result["artist"] = player.get_artist()
            result["title"] = player.get_title()
            result["album"] = player.get_album()
            length_in_secs = self._get_length_in_secs(player.props.metadata)
            result["length"] = TimeWrapper(length_in_secs, "%E%l%M:%S")

        return result
Esempio n. 17
0
    def run(self):
        urgent = False
        color = self.color
        batteries = []

        for path in self.paths:
            if self.battery_ident == 'ALL' or path.find(
                    self.battery_ident) >= 0:
                try:
                    batteries.append(Battery.create(path))
                except FileNotFoundError:
                    pass

        if not batteries:
            format_dict = {'battery_ident': self.battery_ident}
            self.output = {
                "full_text": formatp(self.not_present_text, **format_dict),
                "color": self.not_present_color,
            }
            return
        if self.no_text_full:
            if self.battery_status(batteries) == "Full":
                self.output = {"full_text": ""}
                return

        fdict = {
            "battery_ident":
            self.battery_ident,
            "no_of_batteries":
            len(batteries),
            "percentage":
            self.percentage(batteries),
            "percentage_design":
            self.percentage(batteries, design=True),
            "consumption":
            self.consumption(batteries),
            "remaining":
            TimeWrapper(0, "%E%h:%M"),
            "glyph":
            make_glyph(self.percentage(batteries), self.glyphs),
            "bar":
            make_bar(self.percentage(batteries)),
            "bar_design":
            make_bar(self.percentage(batteries, design=True)),
            "vertical_bar":
            make_vertical_bar(self.percentage(batteries)),
            "vertical_bar_design":
            make_vertical_bar(self.percentage(batteries, design=True)),
        }

        status = self.battery_status(batteries)
        if status in ["Charging", "Discharging"]:
            remaining = self.remaining(batteries)
            fdict["remaining"] = TimeWrapper(remaining * 60, "%E%h:%M")
            if status == "Discharging":
                fdict["status"] = "DIS"
                if self.percentage(batteries) <= self.alert_percentage:
                    urgent = True
                    color = self.critical_color
            else:
                fdict["status"] = "CHR"
                color = self.charging_color
        elif status == 'Depleted':
            fdict["status"] = "DPL"
            color = self.critical_color
        else:
            fdict["status"] = "FULL"
            color = self.full_color
        if self.critical_level_command and fdict["status"] == "DIS" and fdict[
                "percentage"] <= self.critical_level_percentage:
            run_through_shell(self.critical_level_command, enable_shell=True)

        self.alert_if_low_battery(fdict)

        if self.levels and fdict['status'] == 'DIS':
            self.levels.setdefault(0, self.status.get('DPL', 'DPL'))
            self.levels.setdefault(100, self.status.get('FULL', 'FULL'))
            keys = sorted(self.levels.keys())
            index = bisect.bisect_left(keys, int(fdict['percentage']))
            fdict["status"] = self.levels[keys[index]]
        else:
            fdict["status"] = self.status[fdict["status"]]

        self.data = fdict
        self.output = {
            "full_text": formatp(self.format, **fdict),
            "instance": self.battery_ident,
            "urgent": urgent,
            "color": color,
        }
Esempio n. 18
0
    def run(self):
        urgent = False
        color = self.color
        batteries = []

        for path in self.paths:
            if self.battery_ident == 'ALL' or path.find(
                    self.battery_ident) >= 0:
                try:
                    batteries.append(Battery.create(path))
                except FileNotFoundError:
                    pass

        if not batteries:
            format_dict = {'battery_ident': self.battery_ident}
            self.output = {
                "full_text": formatp(self.not_present_text, **format_dict),
                "color": self.not_present_color,
            }
            return
        if self.no_text_full:
            if self.battery_status(batteries) == "Full":
                self.output = {"full_text": ""}
                return

        fdict = {
            "battery_ident": self.battery_ident,
            "no_of_batteries": len(batteries),
            "percentage": self.percentage(batteries),
            "percentage_design": self.percentage(batteries, design=True),
            "consumption": self.consumption(batteries),
            "remaining": TimeWrapper(0, "%E%h:%M"),
            "bar": make_bar(self.percentage(batteries)),
        }

        status = self.battery_status(batteries)
        if status in ["Charging", "Discharging"]:
            remaining = self.remaining(batteries)
            fdict["remaining"] = TimeWrapper(remaining * 60, "%E%h:%M")
            if status == "Discharging":
                fdict["status"] = "DIS"
                if self.percentage(batteries) <= self.alert_percentage:
                    urgent = True
                    color = self.critical_color
            else:
                fdict["status"] = "CHR"
                color = self.charging_color
        elif status == 'Depleted':
            fdict["status"] = "DPL"
            color = self.critical_color
        else:
            fdict["status"] = "FULL"
            color = self.full_color

        if self.alert and fdict["status"] == "DIS" and fdict[
                "percentage"] <= self.alert_percentage:
            DesktopNotification(
                title=formatp(self.alert_format_title, **fdict),
                body=formatp(self.alert_format_body, **fdict),
                icon="battery-caution",
                urgency=2,
                timeout=60,
            ).display()

        fdict["status"] = self.status[fdict["status"]]

        self.output = {
            "full_text": formatp(self.format, **fdict),
            "instance": self.battery_ident,
            "urgent": urgent,
            "color": color,
        }
Esempio n. 19
0
    def run(self):
        try:
            currentsong = self.get_player_prop("Metadata")

            fdict = {
                "status": self.status[self.statusmap[
                    self.get_player_prop("PlaybackStatus")]],
                # TODO: Use optional(!) TrackList interface for this to
                # gain 100 % mpd<->now_playing compat
                "len": 0,
                "pos": 0,
                "volume": int(self.get_player_prop("Volume", 0) * 100),

                "title": currentsong.get("xesam:title", ""),
                "album": currentsong.get("xesam:album", ""),
                "artist": ", ".join(currentsong.get("xesam:artist", "")),
                "song_length": TimeWrapper(
                    (currentsong.get("mpris:length") or 0) / 1000 ** 2),
                "song_elapsed": TimeWrapper(
                    (self.get_player_prop("Position") or 0) / 1000 ** 2),
                "filename": "",
            }

            if not fdict["title"]:
                fdict["filename"] = '.'.join(
                    basename((currentsong.get("xesam:url") or "")).
                    split('.')[:-1])

            self.data = fdict
            self.output = {
                "full_text": formatp(self.format, **fdict).strip(),
                "color": self.color,
            }

        except NoPlayerException:
            if self.hide_no_player:
                self.output = None
            else:
                self.output = {
                    "full_text": self.format_no_player,
                    "color": self.color_no_player,
                }
            if hasattr(self, "data"):
                del self.data
            return

        except KeyError:
            self.output = {
                    "full_text": "NINJA",
                    "color": self.color_no_player
                    }

        except dbus.exceptions.DBusException as e:
            if self.hide_no_player:
                self.output = None
            else:
                self.output = {
                    "full_text": "DBus error: " + e.get_dbus_message(),
                    "color": "#ff0000",
                }
            if hasattr(self, "data"):
                del self.data
            return