Source

gSharkDown / lib / tfuncs.py

import os
import sys
import gtk
import gobject
import dbus
import dbus.service
import dbus.mainloop.glib
import time
from urllib import urlretrieve
import threading
import groove
try:
    import pygst
    pygst.require('0.10')
    import gst
except:
    print "You don't have python-gstreamer installed!"
    sys.exit(0)

basepath = os.path.abspath(os.path.dirname(sys.argv[0]).strip("/lib"))


class t_init(threading.Thread):
    def __init__(self, _frame):
        threading.Thread.__init__(self)
        self.frame = _frame

    def run(self):
        p = 1
        while p:
            try:
                groove.init()
                groove.getToken()
                self.frame.progress_bar.set_text(_("Ready"))
                p = 0
            except Exception, e:
                if e.args[0] == 11004:
                                        time.sleep(1)
                else:
                    print e.args


class t_download(threading.Thread):

    def __init__(self, _window, _song, _filename, _path):
        threading.Thread.__init__(self)
        self.win = _window
        self.filename = _filename
        self.songid = _song["SongID"]
        self.path = _path
        self.duration = float(_song["EstimateDuration"])

    def run(self):
        try:
            key = groove.getStreamKeyFromSongIDEx(self.songid)
        except Exception, e:
            print e
        try:
            self.t = time.time()
            self.beg = self.t
            self.lastCount = 0
            urlretrieve("http://" + key["result"]["%s" % self.songid]["ip"] + "/stream.php",
                       os.path.join(self.path, self.filename),
                       self.hook,
                        "streamKey=" + key["result"]["%s" % self.songid]["streamKey"])
        except Exception, e:
            print e.args

    def hook(self, countBlocks, Block, TotalSize):
        progress = float(countBlocks * Block) * 1.00 / float(TotalSize)
        gobject.timeout_add(10, self.update_progress,
                            progress, countBlocks, TotalSize, Block)

    def update_progress(self, progress, countBlocks, TotalSize, Block):
        if progress < 0.99:
            mb = 1024 ** 2
            self.win.progress_bar.pulse()
            sizestr = "%.02f/%.02f MB" % (float(countBlocks * Block) / mb,
                                          float(TotalSize) / mb)
            self.win.progress_bar.set_text("Downloading: %s" % (sizestr))
        else:
            self.win.progress_bar.set_fraction(1.00)
            self.win.progress_bar.set_text("Downloaded!")


class t_play(threading.Thread):

    def __init__(self, _window, _song, _conf, _lastfm):
        threading.Thread.__init__(self)
        self.win = _window
        self.songid = _song["SongID"]
        self.song = _song
        self.repeat = _conf
        self.lastfm = _lastfm

    def run(self):
        try:
            key = groove.getStreamKeyFromSongIDEx(self.songid)
        except Exception, e:
            print e
        playurls = "http://%s/stream.php?streamKey=%s"
        play_url = playurls % (key["result"]["%s" % self.songid]["ip"],
                               key["result"]["%s" % self.songid]["streamKey"])
        self.win.player.set_property('uri', play_url)
        self.win.player.set_state(gst.STATE_PLAYING)
        if self.lastfm != "":
            self.lastfm.scrobble(self.song['ArtistName'],
                                    self.song['SongName'],
                                    int(time.time()))
            self.lastfm.update_now_playing(self.song['ArtistName'],
                                              self.song['SongName'])
        bus = self.win.player.get_bus()
        bus.enable_sync_message_emission()
        bus.add_signal_watch()
        bus.connect("message", self.on_message_cb)
        bus.connect('message::eos', self.on_stopped)

    def on_message_cb(self, bus, message):
        if message.type == gst.MESSAGE_STATE_CHANGED:
            old, new, pending = message.parse_state_changed()
            self.update_buttons(new)
        return gst.BUS_PASS

    def on_stopped(self, config, widget=None, data=None):
        if self.repeat == 1:
            self.win.play_next(self.win.ff_button)
        else:
            self.win.play_button.set_stock_id(gtk.STOCK_MEDIA_PLAY)
            self.win.staticon.set_from_file("%s/data/gsharkdown_16.png" % basepath)
            self.win.staticon.set_tooltip(_("gSharkDown : Grooveshark Downloader"))

    def update_buttons(self, state):
        if state == gst.STATE_NULL:
            self.win.play_button.set_stock_id(gtk.STOCK_MEDIA_PLAY)
        else:
            self.win.play_button.set_stock_id(gtk.STOCK_MEDIA_STOP)

class t_key_listener(threading.Thread):

    def __init__(self, _window):
        threading.Thread.__init__(self)
        self.win = _window

    def run(self):
        try:
            dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
            bus = dbus.Bus(dbus.Bus.TYPE_SESSION)
            bus_object = bus.get_object('org.gnome.SettingsDaemon',
                                '/org/gnome/SettingsDaemon/MediaKeys')
    
            dbus_interface = 'org.gnome.SettingsDaemon.MediaKeys'
            bus_object.GrabMediaPlayerKeys("MyMultimediaThingy", 0,
                                  dbus_interface=dbus_interface)

            bus_object.connect_to_signal('MediaPlayerKeyPressed',
                                self.on_media_key)
        except:
            pass
    
    def on_media_key(self, comes_from, what):
        if what in ['Stop', 'Play', 'Next', 'Previous']:
            if what == 'Stop':
                self.win.play_selected(self.win.play_button)
            elif what == 'Play':
                self.win.play_selected(self.win.play_button)
            elif what == 'Next':
                self.win.play_next(self.win.ff_button)
            elif what == 'Previous':
                self.win.play_previous(self.win.prev_button)

class t_search(threading.Thread):

    def __init__(self, _window, _term, _type):

        threading.Thread.__init__(self)
        self.win = _window
        self.term = _term
        self.type = _type

    def run(self):
        self.win.result.clear()
        try:
            self.win.results = groove.getSearchResultsEx(self.term, self.type)
        except Exception, e:
            print e.args
        for item in self.win.results:
            self.win.result.append([item['SongName'],
                                    item['ArtistName'],
                                    item['AlbumName'],
                                    item['SongID']])