def magic_func(self, args=''): args = args.split() if (mpd_command_dict[command_name][0] is not None and len(args) not in mpd_command_dict[command_name][0]): raise TypeError(_("%s takes one of %r arguments (%d given)") % ( command_name, mpd_command_dict[command_name][0], len(args))) # Convert them to correct type typ = mpd_command_dict[command_name][1] if typ is not None: index = 0 while index < len(args): try: args[index] = typ[index](args[index]) except ValueError: raise ValueError(_("%r is not %s") % (args[index], typ)) index += 1 if args: self.api.ex("_ret = getattr(_mpc, '%s')(*%r)" % (command_name, args)) else: self.api.ex("_ret = getattr(_mpc, '%s')()" % command_name) if getattr(self.api.user_ns["config"], "ret"): return self.api.user_ns["_ret"]
def connect(self, args=''): """Connect to mpd server. usage: %connect [<string host>] [<int port>]""" if not args: host = port = None else: split_args = args.split() if len(split) != 2: raise TypeError(_("%s takes %d or %d arguments (%d given)" %\ ("connect()", 0, 2, len(split_args)))) else: host = split[0] port = int(split[1]) self.api.ex(""" import time as _time import thread as _thread _disconnecting = False _ret = _mpc.connect(%s, %s) _connected = True def _pinger(): while not _disconnecting: if config.ping: _mpc.mpc.ping() _time.sleep(config.ping_interval) _thread.start_new_thread(_pinger, ())""" % (host, port)) return self.api.user_ns["_ret"]
def asHuman(seconds, highest=3): """Convert seconds to human readable form. highest determines the highest time unit to return 1 : minutes 2 : hours 3 : days """ seconds = int(seconds) if highest > 3 or highest < 1: raise TypeError("highest must be a number between 1 and 3") if highest == 3: days = seconds / SECSPERDAY seconds %= SECSPERDAY if highest >= 2: hours = seconds / SECSPERHOUR seconds %= SECSPERHOUR if highest >= 1: minutes = seconds / SECSPERMIN seconds %= SECSPERMIN else: raise TypeError("highest must be a number between 1 and 3") if highest == 1: return "%02d:%02d" % (minutes, seconds) elif highest == 2: return "%d:%02d:%02d" % (hours, minutes, seconds) elif highest == 3: return str(days) + " " + _("days") + ", " + "%d:%02d:%02d" % (hours, minutes, seconds)
def authenticate(self, funcname): """authenticate with the server if not allowed to execute funcname.""" if funcname in self.mpd_notcommands: authfunc = self.__super.__getattr__("password") if config_data.has_option("mpd", "password"): authfunc(config_data.get("mpd", "password")) else: import getpass printByName("askpass", command=funcname) authfunc(getpass.getpass(_("Password: "******"notcommands")()
def disconnect(self, args=''): """Disconnect from mpd server.""" if args: raise TypeError(_("%s takes exactly %d arguments (%d given)") %\ ("disconnect()", 0, len(args.split()))) self.api.ex(""" _disconnecting = True _ret = _mpc.disconnect() _connected = False""") if getattr(self.api.user_ns["config"], "ret"): return self.api.user_ns["_ret"]
def mpdshell(conn): cwd = os.getcwd() # Change dir so we can load the mpd profile and copy files profiledir = os.path.join(boogie.__path__[0], "console") os.chdir(profiledir) if not os.path.exists(os.path.join(console_dir, "ipythonrc")): shutil.copy("ipythonrc", os.path.join(console_dir, "ipythonrc")) if not os.path.exists(os.path.join(console_dir, "ipy_user_conf.py")): shutil.copy("ipy_user_conf.py", os.path.join(console_dir, "ipy_user_conf.py")) args = "-profile mpd -ipythondir %s" % console_dir args = args.split() banner = _("mpd console") + ", boogie %s ipy %s" % ( boogie.__version__, Release.version) exit_msg = _("leaving mpd console") namespace = { "_config_data": config_data, "_mpc":conn, "config":config() } ipshell = IPShellEmbed(args, banner=banner, exit_msg=_("leaving mpd console"), user_ns=namespace) os.chdir(cwd) ipshell()
def exc_handler(cls, etype, value, tb): """Exception handler for mpd console.""" print((bold(red(_("error:"))) + " " +\ bold(green(etype.__name__ + ":")) + " " + bold(str(value))))
from boogie import mpd from boogie.config import config_data from boogie.templates import printByName, printError from boogie.util import parseTimeSpec, parseTimeStatus from boogie.i18n import _ BOOLEAN_TRUE = ("1", "on", "true", "yes") BOOLEAN_FALSE = ("0", "off", "false", "no") # MPD commands, format is: # command_name : # ((number of args), type conversion, group, since, usage, explanation) mpd_command_dict = { # Admin Commands "disableoutput":((1,), (lambda a: int(a)-1,) ,"admin", _("Admin Commands"), "0", _("<output #>"), _("Turn an output off")), "enableoutput":((1,), (lambda a: int(a)-1,), "admin", _("Admin Commands"), "0", _("<output #>"), _("Turn an output on")), "kill":((0,), None, "admin", _("Admin Commands"), "0", "", "Stop MPD from running, in a safe way"), "update":(None, None, "admin", _("Admin Commands"), "0", _("[<path>]"), _("Scan path for updates, path defaults to music_directory")), # Informational commands "status":((0,), None, "read", _("Informational Commands"), "0", "", _("Report the current status of mpd")), "stats":((0,), None, "read", _("Informational Commands"), "0", "", _("Display statistics")), "outputs":((0,), None, "read", _("Informational Commands"), "0", "", _("Show information about all outputs")), "commands":((0,), None, "read", _("Informational Commands"), "0", "",
def parseTimeSpec(timespec, elapsedtime, totaltime): """Parse a timespec in format [+-][HH:MM:SS]|<0-100>% Returns seconds which can be passed to seek() and seekid(). Raises TimeSpecError if the format isn't valid.""" # Check if it's a relative seek relative = 0 if timespec.startswith("+"): relative = 1 elif timespec.startswith("-"): relative = -1 # Check if seeking by percent if timespec.endswith("%"): perc = float(timespec[:-1]) if (not relative and (perc < 0 or perc > 100)) or (relative and perc > 100): raise TimeSpecError(_("'%s' is not a number between 0 and 100") % timespec[-1] ) seekchange = perc * totaltime / 100 + 0.5 else: # Seeking by absolute time if ":" in timespec: timespec_split = timespec.split(":") if len(timespec_split) == 3: hours, minutes, seconds = timespec_split # Hours exist, check if minutes is more than two digits if len(minutes) > 2: raise TimeSpecError(_("'%s' is not two digits") % minutes) hours = int(hours) elif len(timespec_split) == 2: hours = 0 minutes, seconds = timespec_split # Minutes exist, check if seconds is more than two digits if len(seconds) > 2: raise TimeSpecError(_("'%s' is not two digits") % seconds) minutes = int(minutes) seconds = int(seconds) elif len(timespec_split) == 1: hours = minutes = 0 seconds = timespec_split else: raise TimeSpecError(_("More than two colons in timespec")) # Make sure they're not above 60 if higher unit exists. if minutes != 0 and seconds > 60: raise TimeSpecError(_("%d is greater than 60") % seconds) elif hours != 0 and minutes > 60: raise TimeSpecError(_("%d is greater than 60") % minutes) totalseconds = ( hours * 3600 ) + ( minutes * 60 ) + seconds else: # Absolute seek in seconds totalseconds = float(timespec) if not relative and totalseconds < 0: raise TimeSpecError(_("'%s' is not a positive number") % timespec) seekchange = totalseconds if relative == 1: seekto = elapsedtime + seekchange elif relative == -1: seekto = elapsedtime + seekchange else: seekto = seekchange if seekto > totaltime: raise TimeSpecError(_("Seek amount would seek past the end of the song")) return int(seekto)