diff --git a/src/controller/__init__.py b/src/controller/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/controller/mainController.py b/src/controller/mainController.py new file mode 100644 index 0000000..6426482 --- /dev/null +++ b/src/controller/mainController.py @@ -0,0 +1,129 @@ +# -*- coding: utf-8 -*- +""" main controller for MusicDL""" +import wx +import logging +import widgetUtils +import utils +from pubsub import pub +from wxUI import mainWindow +from extractors import zaycev +from . import player + +log = logging.getLogger("controller.main") + +class Controller(object): + + def __init__(self): + super(Controller, self).__init__() + log.debug("Starting main controller...") + # Setting up the player object + player.setup() + # Instantiate the only available extractor for now. + self.extractor = zaycev.interface() + # Get main window + self.window = mainWindow.mainWindow() + log.debug("Main window created") + self.window.change_status(_("Ready")) + # Here we will save results for searches as song objects. + self.results = [] + self.connect_events() + # Shows window. + self.window.Show() + + def get_status_info(self): + """ Formatting string for status bar messages """ + if len(self.results) > 0: + results = _("Showing {0} results.").format(len(self.results)) + else: + results = "" + final = results+" " + return final + + def connect_events(self): + """ connects all widgets to their corresponding events.""" + widgetUtils.connect_event(self.window.search, widgetUtils.BUTTON_PRESSED, self.on_search) + widgetUtils.connect_event(self.window.list, widgetUtils.LISTBOX_ITEM_ACTIVATED, self.on_activated) + widgetUtils.connect_event(self.window.list, widgetUtils.KEYPRESS, self.on_keypress) + widgetUtils.connect_event(self.window, widgetUtils.MENU, self.on_play_pause, menuitem=self.window.player_play) + widgetUtils.connect_event(self.window, widgetUtils.MENU, self.on_next, menuitem=self.window.player_next) + widgetUtils.connect_event(self.window, widgetUtils.MENU, self.on_previous, menuitem=self.window.player_previous) + widgetUtils.connect_event(self.window, widgetUtils.MENU, self.on_play_all, menuitem=self.window.player_play_all) + widgetUtils.connect_event(self.window, widgetUtils.MENU, self.on_stop, menuitem=self.window.player_stop) + widgetUtils.connect_event(self.window, widgetUtils.MENU, self.on_volume_down, menuitem=self.window.player_volume_down) + widgetUtils.connect_event(self.window, widgetUtils.MENU, self.on_volume_up, menuitem=self.window.player_volume_up) + widgetUtils.connect_event(self.window, widgetUtils.MENU, self.on_mute, menuitem=self.window.player_mute) + pub.subscribe(self.change_status, "change_status") + + # Event functions. These functions will call other functions in a thread and are bound to widget events. + def on_search(self, *args, **kwargs): + utils.call_threaded(self.search) + + def on_activated(self, *args, **kwargs): + utils.call_threaded(self.play) + + def on_keypress(self, ev): + if ev.GetKeyCode() == wx.WXK_RETURN: + utils.call_threaded(self.play) + ev.Skip() + + def on_play_pause(self, *args, **kwargs): + if player.player.check_is_playing() != False: + return player.player.pause() + return utils.call_threaded(self.play) + + def on_next(self, *args, **kwargs): + item = self.window.get_item() + if item <= len(self.results): + self.window.list.SetSelection(item+1) + else: + self.window.list.SetSelection(0) + return utils.call_threaded(self.play) + + def on_previous(self, *args, **kwargs): + item = self.window.get_item() + if item > 0: + self.window.list.SetSelection(item-1) + else: + self.window.list.SetSelection(len(self.results)-1) + return utils.call_threaded(self.play) + + def on_play_all(self, *args, **kwargs): + pass + + def on_stop(self, *args, **kwargs): + player.player.stop() + + def on_volume_down(self, *args, **kwargs): + player.player.volume = player.player.volume-5 + + def on_volume_up(self, *args, **kwargs): + player.player.volume = player.player.volume+5 + + def on_mute(self, *args, **kwargs): + player.player.volume = 0 + + def change_status(self, status): + """ Function used for changing the status bar from outside the main controller module.""" + self.window.change_status("{0} {1}".format(status, self.get_status_info())) + + # real functions. These functions really are doing the work. + def search(self, *args, **kwargs): + text = self.window.get_text() + if text == "": + return + self.window.list.Clear() + self.change_status(_("Searching {0}... ").format(text,)) + self.extractor.search(text) + self.results = self.extractor.results + for i in self.results: + self.window.list.Append(i.format_track()) + self.change_status("") + + def play(self): + self.change_status(_("Loading song...")) + url = self.extractor.get_download_url(self.results[self.window.get_item()].url) + player.player.play(url) + + def play_audios(self, audios): + player.player.play_all(audios, shuffle=self.window.player_shuffle.IsChecked()) + diff --git a/src/controller/player.py b/src/controller/player.py new file mode 100644 index 0000000..d5f6025 --- /dev/null +++ b/src/controller/player.py @@ -0,0 +1,114 @@ +# -*- coding: utf-8 -*- +import random +import sound_lib +import logging +from sound_lib.stream import URLStream +from sound_lib.main import BassError +from sound_lib.output import Output +from pubsub import pub +from utils import RepeatingTimer + +player = None +log = logging.getLogger("player") + +def setup(): + global player + if player == None: + Output() + player = audioPlayer() + +class audioPlayer(object): + + def __init__(self): + self.is_playing = False + self.stream = None + self.vol = 100 + self.is_working = False + self.queue = [] + self.stopped = True + + def play(self, url): + if self.stream != None and self.stream.is_playing == True: + try: + self.stream.stop() + except BassError: + log.exception("error when stopping the file") + self.stream = None + self.stopped = True + if hasattr(self, "worker") and self.worker != None: + self.worker.cancel() + self.worker = None + self.queue = [] + # Make sure there are no other sounds trying to be played. + if self.is_working == False: + self.is_working = True + try: + self.stream = URLStream(url=url) + except BassError: + log.debug("Error when playing the file {0}".format(url,)) + pub.sendMessage("change_status", status=_("Error playing last file")) + return + self.stream.volume = self.vol/100.0 + self.stream.play() + self.stopped = False + self.is_working = False + + def stop(self): + if self.stream != None and self.stream.is_playing == True: + self.stream.stop() + self.stopped = True + if hasattr(self, "worker") and self.worker != None: + self.worker.cancel() + self.worker = None + self.queue = [] + + def pause(self): + if self.stream != None: + if self.stream.is_playing == True: + self.stream.pause() + self.stopped = True + else: + try: + self.stream.play() + self.stopped = False + except BassError: + pass + + @property + def volume(self): + if self.stream != None: + return self.vol + + @volume.setter + def volume(self, vol): + if vol <= 100 and vol >= 0: + self.vol = vol + if self.stream != None: + self.stream.volume = self.vol/100.0 + + def play_all(self, list_of_urls, shuffle=False): + self.stop() + self.queue = list_of_urls + if shuffle: + random.shuffle(self.queue) + self.play(self.queue[0]) + self.queue.remove(self.queue[0]) + self.worker = RepeatingTimer(5, self.player_function) + self.worker.start() + + def player_function(self): + if self.stream != None and self.stream.is_playing == False and self.stopped == False and len(self.stream) == self.stream.position: + if len(self.queue) == 0: + self.worker.cancel() + return + self.play(self.queue[0]) + self.queue.remove(self.queue[0]) + + def check_is_playing(self): + if self.stream == None: + return False + if self.stream != None and self.stream.is_playing == False: + return False + else: + return True + diff --git a/src/i18n.py b/src/i18n.py new file mode 100644 index 0000000..e896765 --- /dev/null +++ b/src/i18n.py @@ -0,0 +1,8 @@ +# -*- coding: utf-8 -*- +import os +import gettext +import locale +from platform_utils import paths + +def setup(): + gettext.install("music-dl", localedir=os.path.join(paths.app_path(), "locales")) \ No newline at end of file diff --git a/src/main.py b/src/main.py new file mode 100644 index 0000000..6312114 --- /dev/null +++ b/src/main.py @@ -0,0 +1,21 @@ +# -*- coding: utf-8 -*- +import i18n +import widgetUtils +import logging +import application +from platform_utils import paths + +logging.basicConfig() +log = logging.getLogger("main") + +def setup(): + log.debug("Starting music-dl %s" % (application.version,)) + log.debug("Application path is %s" % (paths.app_path(),)) + i18n.setup() + from controller import mainController + app = widgetUtils.mainLoopObject() + log.debug("Created Application mainloop object") + r = mainController.Controller() + app.run() + +setup() diff --git a/src/utils.py b/src/utils.py new file mode 100644 index 0000000..6a6b2d4 --- /dev/null +++ b/src/utils.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +import threading +import logging + +log = logging.getLogger("utils") + +def call_threaded(func, *args, **kwargs): + #Call the given function in a daemonized thread and return the thread. + def new_func(*a, **k): + func(*a, **k) + thread = threading.Thread(target=new_func, args=args, kwargs=kwargs) + thread.start() + return thread + +class RepeatingTimer(threading.Thread): + """Call a function after a specified number of seconds, it will then repeat again after the specified number of seconds + Note: If the function provided takes time to execute, this time is NOT taken from the next wait period + + t = RepeatingTimer(30.0, f, args=[], kwargs={}) + t.start() + t.cancel() # stop the timer's actions + """ + + def __init__(self, interval, function, daemon=True, *args, **kwargs): + threading.Thread.__init__(self) + self.daemon = daemon + self.interval = float(interval) + self.function = function + self.args = args + self.kwargs = kwargs + self.finished = threading.Event() + + def cancel(self): + """Stop the timer if it hasn't finished yet""" + log.debug("Stopping repeater for %s" % (self.function,)) + self.finished.set() + stop = cancel + + def run(self): + while not self.finished.is_set(): + self.finished.wait(self.interval) + if not self.finished.is_set(): #In case someone has canceled while waiting + try: + self.function(*self.args, **self.kwargs) + except: + log.exception("Execution failed. Function: %r args: %r and kwargs: %r" % (self.function, self.args, self.kwargs)) diff --git a/src/widgetUtils/__init__.py b/src/widgetUtils/__init__.py new file mode 100644 index 0000000..87f95ff --- /dev/null +++ b/src/widgetUtils/__init__.py @@ -0,0 +1,5 @@ +import platform +#if platform.system() == "Windows": +from .wxUtils import * +#elif platform.system() == "Linux": +# from gtkUtils import * diff --git a/src/widgetUtils/__init__.pyc b/src/widgetUtils/__init__.pyc new file mode 100644 index 0000000..460139a Binary files /dev/null and b/src/widgetUtils/__init__.pyc differ diff --git a/src/widgetUtils/wxUtils.py b/src/widgetUtils/wxUtils.py new file mode 100644 index 0000000..fb7bcc1 --- /dev/null +++ b/src/widgetUtils/wxUtils.py @@ -0,0 +1,176 @@ +import wx + +toolkit = "wx" + +### Code responses for WX dialogs. + +# this is when an user presses OK on a dialogue. +OK = wx.ID_OK + +# This is when an user presses cancel on a dialogue. +CANCEL = wx.ID_CANCEL + +# This is when an user closes the dialogue or an id to create the close button. +CLOSE = wx.ID_CLOSE + +# The response for a "yes" Button pressed on a dialogue. +YES = wx.ID_YES + +# This is when the user presses No on a default dialogue. +NO = wx.ID_NO + +###events + +# This is raised when the application must be closed. +CLOSE_EVENT = wx.EVT_CLOSE + +# This is activated when a button is pressed. +BUTTON_PRESSED = wx.EVT_BUTTON + +# This is raised when a checkbox changes its status. +CHECKBOX = wx.EVT_CHECKBOX + +# This is activated when an user enter text on an edit box. +ENTERED_TEXT = wx.EVT_TEXT + +# This is raised when a user activates a menu. +MENU = wx.EVT_MENU + +# This is raised when a user presses any key in the control. +KEYPRESS = wx.EVT_CHAR_HOOK + +# This is raised when a user releases a key in the control. +KEYUP = wx.EVT_KEY_UP + +# This happens when a notebook tab is changed, It is used in Treebooks too. +NOTEBOOK_PAGE_CHANGED = wx.EVT_TREEBOOK_PAGE_CHANGED + +# This happens when a radiobutton group changes its status. +RADIOBUTTON = wx.EVT_RADIOBUTTON + +# Taskbar mouse clicks. +#TASKBAR_RIGHT_CLICK = wx.EVT_TASKBAR_RIGHT_DOWN +#TASKBAR_LEFT_CLICK = wx.EVT_TASKBAR_LEFT_DOWN +LISTBOX_CHANGED = wx.EVT_LISTBOX +LISTBOX_ITEM_ACTIVATED = wx.EVT_LIST_ITEM_ACTIVATED + +def exit_application(): + """ Closes the current window cleanly. """ + wx.GetApp().ExitMainLoop() + +def connect_event(parent, event, func, menuitem=None, *args, **kwargs): + """ Connects an event to a function. + parent wx.window: The widget that will listen for the event. + event widgetUtils.event: The event that will be listened for the parent. The event should be one of the widgetUtils events. + function func: The function that will be connected to the event.""" + if menuitem == None: + return getattr(parent, "Bind")(event, func, *args, **kwargs) + else: + return getattr(parent, "Bind")(event, func, menuitem, *args, **kwargs) + +def connectExitFunction(exitFunction): + """ This connect the events in WX when an user is turning off the machine.""" + wx.GetApp().Bind(wx.EVT_QUERY_END_SESSION, exitFunction) + wx.GetApp().Bind(wx.EVT_END_SESSION, exitFunction) + +class BaseDialog(wx.Dialog): + def __init__(self, *args, **kwargs): + super(BaseDialog, self).__init__(*args, **kwargs) + + def get_response(self): + return self.ShowModal() + + def get(self, control): + if hasattr(self, control): + control = getattr(self, control) + if hasattr(control, "GetValue"): return getattr(control, "GetValue")() + elif hasattr(control, "GetLabel"): return getattr(control, "GetLabel")() + else: return -1 + else: return 0 + + def set(self, control, text): + if hasattr(self, control): + control = getattr(self, control) + if hasattr(control, "SetValue"): return getattr(control, "SetValue")(text) + elif hasattr(control, "SetLabel"): return getattr(control, "SetLabel")(text) + elif hasattr(control, "ChangeValue"): return getattr(control, "ChangeValue")(text) + else: return -1 + else: return 0 + + def destroy(self): + self.Destroy() + + def set_title(self, title): + self.SetTitle(title) + + def get_title(self): + return self.GetTitle() + + def enable(self, control): + getattr(self, control).Enable(True) + + def disable(self, control): + getattr(self, control).Enable(False) + +class mainLoopObject(wx.App): + + def __init__(self): + self.app = wx.App() +# self.lc = wx.Locale() +# lang=languageHandler.getLanguage() +# wxLang=self.lc.FindLanguageInfo(lang) +# if not wxLang and '_' in lang: +# wxLang=self.lc.FindLanguageInfo(lang.split('_')[0]) +# if hasattr(sys,'frozen'): +# self.lc.AddCatalogLookupPathPrefix(paths.app_path("locales")) +# if wxLang: +# self.lc.Init(wxLang.Language) + + def run(self): + self.app.MainLoop() + +class list(object): + def __init__(self, parent, *columns, **listArguments): + self.columns = columns + self.listArguments = listArguments + self.create_list(parent) + + def set_windows_size(self, column, characters_max): + self.list.SetColumnWidth(column, characters_max*2) + + def set_size(self): + self.list.SetSize((self.list.GetBestSize()[0], 1000)) + + def create_list(self, parent): + self.list = wx.ListCtrl(parent, -1, **self.listArguments) + for i in range(0, len(self.columns)): + self.list.InsertColumn(i, u"%s" % (self.columns[i])) + + def insert_item(self, reversed, *item): + """ Inserts an item on the list.""" + if reversed == False: items = self.list.GetItemCount() + else: items = 0 + self.list.InsertItem(items, item[0]) + for i in range(1, len(self.columns)): + self.list.SetItem(items, i, item[i]) + + def remove_item(self, pos): + """ Deletes an item from the list.""" + if pos > 0: self.list.Focus(pos-1) + self.list.DeleteItem(pos) + + def clear(self): + self.list.DeleteAllItems() + + def get_selected(self): + return self.list.GetFocusedItem() + + def select_item(self, pos): + self.list.Focus(pos) + + def get_count(self): + selected = self.list.GetItemCount() + if selected == -1: + return 0 + else: + return selected diff --git a/src/widgetUtils/wxUtils.pyc b/src/widgetUtils/wxUtils.pyc new file mode 100644 index 0000000..80fdee1 Binary files /dev/null and b/src/widgetUtils/wxUtils.pyc differ diff --git a/src/wxUI/__init__.py b/src/wxUI/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/wxUI/mainWindow.py b/src/wxUI/mainWindow.py new file mode 100644 index 0000000..2ab41fc --- /dev/null +++ b/src/wxUI/mainWindow.py @@ -0,0 +1,73 @@ +# -*- coding: utf-8 -*- +import wx +import application +import widgetUtils + +class mainWindow(wx.Frame): + def makeMenu(self): + mb = wx.MenuBar() + app_ = wx.Menu() + mb.Append(app_, _(u"Application")) + player = wx.Menu() + self.player_play = player.Append(wx.NewId(), _(u"Play")) + self.player_play_all = player.Append(wx.NewId(), _(u"Play all")) + self.player_stop = player.Append(wx.NewId(), _(u"Stop")) + self.player_previous = player.Append(wx.NewId(), _(u"Previous")) + self.player_next = player.Append(wx.NewId(), _(u"Next")) + self.player_shuffle = player.AppendCheckItem(wx.NewId(), _(u"Shuffle")) + self.player_volume_down = player.Append(wx.NewId(), _(u"Volume down")) + self.player_volume_up = player.Append(wx.NewId(), _(u"Volume up")) + self.player_mute = player.Append(wx.NewId(), _(u"Mute")) + help_ = wx.Menu() + self.about = help_.Append(wx.NewId(), _(u"About {0}").format(application.name,)) + self.check_for_updates = help_.Append(wx.NewId(), _(u"Check for updates")) + mb.Append(player, _(u"Player")) + mb.Append(help_, _(u"Help")) + self.SetMenuBar(mb) + + def __init__(self): + super(mainWindow, self).__init__(parent=None, id=wx.NewId(), title=application.name) + self.Maximize(True) + self.makeMenu() + self.panel = wx.Panel(self) + self.sizer = wx.BoxSizer(wx.VERTICAL) + self.sb = self.CreateStatusBar() + lbl2 = wx.StaticText(self.panel, wx.NewId(), _(u"search")) + self.text = wx.TextCtrl(self.panel, wx.NewId()) + self.search = wx.Button(self.panel, wx.NewId(), _("Search")) + self.search.SetDefault() + box = wx.BoxSizer(wx.HORIZONTAL) + box.Add(lbl2, 0, wx.ALL, 20) + box.Add(self.text, 0, wx.ALL, 5) + box.Add(self.search, 0, wx.ALL, 5) + self.sizer.Add(box, 0, wx.ALL, 5) + lbl = wx.StaticText(self.panel, wx.NewId(), _("Results")) + self.list = wx.ListBox(self.panel, wx.NewId()) + self.sizer.Add(lbl, 0, wx.ALL, 5) + self.sizer.Add(self.list, 1, wx.EXPAND, 5) + self.panel.SetSizer(self.sizer) + self.SetClientSize(self.sizer.CalcMin()) + self.Layout() + self.SetSize(self.GetBestSize()) + + def change_status(self, status): + self.sb.SetStatusText(status) + + def about_dialog(self, *args, **kwargs): + info = wx.AboutDialogInfo() + info.SetName(application.name) + info.SetVersion(application.version) + info.SetDescription(application.description) + info.SetCopyright(application.copyright) + info.SetTranslators(application.translators) +# info.SetLicence(application.licence) + info.AddDeveloper(application.author) + wx.AboutBox(info) + + def get_text(self): + t = self.text.GetValue() + self.text.ChangeValue("") + return t + + def get_item(self): + return self.list.GetSelection() \ No newline at end of file