class groove_controller:
    def __init__(self, manager):
        self.client = Client()
        self.client.init()
        self.manager = manager

    def checkSong(self, song):
        instance = vlc.libvlc_new(1, ["-q"])
        try:
            media = instance.media_new(song.stream.url)
            return True
        except TypeError:
            print("Error found adding: " + '\033[92m' + song.name + '\033[0m' + " searching for playable version")
            return False

    def getSong(self, songName):
        songs = self.client.search(songName, type='Songs')
        try:
            song = songs.next()
            while True:
                if self.checkSong(song):
                    print("Found: " + '\033[92m' + song.name + " - " + song.artist.name + '\033[0m')
                    return song
                else:
                    song = songs.next()
        except Exception as e:
            return "Error"
        def getAll(self, songName):
            art = self.client.search(songName, Client.ARTISTS)
            return art.next().songs

    def getManySongs(self, search ,n):
        foundSongs = self.client.search(search, type='Fast')
        returnData = []
        songCount = 0
        for song in foundSongs:
            returnData.append({'song': song['SongName'],
                               'artist': song['ArtistName'],
                               'album': song['AlbumName'],
                               'SongID': song['SongID'],
                               'ArtistID': song['ArtistID']})
            songCount += 1
            if songCount > 19:
                break
        return returnData
示例#2
0
def find(songname):
    client = Client()
    client.init()
    songs = []
    print "start search"
    for song in client.search(songname, Client.SONGS):
        songs.append(song)
    if songs:
        return songs[0]
示例#3
0
def search_for_musics(query, option):
    client = Client()
    client.init()
    musicas_list = []
    if option == '1':
        musicas = client.search(query, Client.SONGS)
        for musica in musicas:
            musicas_list.append(musica.export())
    elif option == '2':
        musicas = client.search(query, Client.ALBUMS)
        for musica in musicas:
            musicas_list.append(musica.export())
    elif option == '3':
        musicas = client.search(query, Client.ARTISTS)
        for musica in musicas:
            musicas_list.append(musica.export())
    elif option == '4':
        playlist = client.playlist(query)
        for musica in playlist:
            musicas_list.append(musica.export())
    else:
        musicas_list = []
    return musicas_list
示例#4
0
def search_grooveshark(query):
    """
    Makes a search on Grooveshark and return the songs.
    """
    logger.debug("Searching Grooveshark for: '%s'", query)

    client = Client()
    client.init()

    resolve_pool = ThreadPool(processes=16)
    track_list = resolve_pool.map(get_track, client.search(query))
    resolve_pool.close()

    return [song for song in track_list if song]
示例#5
0
def search_for_musics(query, option):
    client = Client()
    client.init()
    musicas_list = []
    if option == '1':
        musicas = client.search(query, Client.SONGS)
        for musica in musicas:
            musicas_list.append(musica.export())
    elif option == '2':
        musicas = client.search(query, Client.ALBUMS)
        for musica in musicas:
            musicas_list.append(musica.export())
    elif option == '3':
        musicas = client.search(query, Client.ARTISTS)
        for musica in musicas:
            musicas_list.append(musica.export())
    elif option == '4':
        playlist = client.playlist(query)
        for musica in playlist:
            musicas_list.append(musica.export())
    else:
        musicas_list = []
    return musicas_list
示例#6
0
def PlayMusic(self, userinput):
    client = Client()
    client.init()

    searchquery = userinput.split("song")[1]

    try:
        song = next(client.search(searchquery, type='Songs'))
        p = subprocess.Popen([
            "exec cvlc " + song.stream.url + " vlc://quit --quiet > /dev/null"
        ],
                             shell=True)

        return "Playing " + str(song)
    except StopIteration:
        return "It don't see that song."
def get_gsresults(searchterms):
	c = Client()
	c.init()
	d = c.search(searchterms)
	x = 0
	v = 0
	client = soundcloud.Client(client_id='dcc1e7da1893fe098685ba22946454eb')
	tracks = client.get('/tracks', q=searchterms, license='cc-by-sa')
	r = []
	for i in tracks.data:
		 if x < 10:
			 r.append({'artist':i.user['username'], 'title':i.title, 'url':i.id, 'arturl':i.artwork_url})
			 x += 1
			 continue
		 for i in d:
			 if v < 10:
				 r.append({'album':i._album_name, 'artist':i._artist_name, 'title':i.name, 'url':i.stream.url, 'arturl':i._cover_url})
				 v += 1
			
	return r
示例#8
0
class GroovesharkPlugin:
	__slots__ = ('client', 'songmap')

	def __init__(self):
		self.client = Client()
		self.client.init()
		self.songmap = {}

	def getSongRec(self, lst):
		lst = list(lst)
		if len(lst) == 0:
			print("Sorry Charlie.  No Results.")
			return None
		i, _ = inputChoice(list(res.name + " by " + res.artist.name if type(res) == grooveshark.classes.Song else res.name for res in lst))
		c = lst[i]
		if type(c) is grooveshark.classes.Song:
			return c
		return self.getSongRec(c.songs)

	def pickSong(self):
		responseTuple = inputChoice(["Song", "Artist", "Album"])
		if responseTuple == None:
			return None
		else:
			typ,_ = responseTuple
		typ = [Client.SONGS, Client.ARTISTS, Client.ALBUMS][typ]
		search = input('Grooveshark search: ')
		song = self.getSongRec(self.client.search(search, typ))
		if song == None:
			return None
		retval = Song(song.name, song.artist.name)
		self.songmap[retval] = song.safe_download()
		return retval
	
	def getSongData(self, song):
		return self.songmap[song]
示例#9
0
# -*- coding:utf-8 -*-
#
# Copyright (C) 2012, Maximilian Köhl <*****@*****.**>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

from __future__ import print_function
import subprocess
import sys
from grooveshark import Client

client = Client()
client.init()

for song in client.search(sys.argv[1]):
    print(sys.argv[1])
    print(song.__str__().encode("utf-8"))
    subprocess.call(['mplayer', song.stream.url])
示例#10
0
class Grooveshark(Application):
    __URLS__ = {
        '/desktop/.*|/icons/.*': 'www',
        '/request/popular': 'popular',
        '/request/search': 'search',
        '/request/stream': 'stream'
    }
    www = Directory(os.path.join(os.path.dirname(__file__), 'www'))

    def __init__(self):
        super().__init__()
        self.client = Client()
        self.client.init()
        self._cache = {}
        self._cache['streams'] = {}

    def _respond_json(self, data, response):
        response.headers['Content-Type'] = 'application/json; charset=UTF-8'
        response.body.append(json.dumps(data).encode('utf-8'))

    def _bad_request(self, message, response):
        response.status = 400
        response.message = 'ERROR'
        response.headers['Content-Type'] = 'application/json; charset=UTF-8'
        response.body.append(
            json.dumps({
                'status': 'error',
                'result': message
            }).encode('utf-8'))

    def popular(self, request, response):
        if 'popular' not in self._cache:
            self._cache['popular'] = (time.time(), [
                song.export() for song in self.client.popular()
            ])
        if time.time() - self._cache['popular'][0] > 7200:
            self._cache['popular'] = (time.time(), [
                song.export() for song in self.client.popular()
            ])
        self._respond_json(
            {
                'status': 'success',
                'result': self._cache['popular'][1]
            }, response)

    def search(self, request, response):
        if 'type' not in request.query:
            request.query['type'] = [SEARCH_TYPE_SONGS]
        if 'query' in request.query:
            if not request.query['type'][0] in (Client.SONGS, Client.ALBUMS,
                                                Client.ARTISTS):
                self._bad_request('unknown type', response)
            else:
                result = [
                    object.export() for object in self.client.search(
                        request.query['query'][0], request.query['type'][0])
                ]
                self._respond_json({
                    'status': 'success',
                    'result': result
                }, response)
        else:
            self._bad_request('missing query argument', response)

    def stream(self, request, response):
        song = Song.from_export(json.loads(request.query['song'][0]),
                                self.client.connection)
        if song.id in self._cache['streams']:
            stream, cache = self._cache['streams'][song.id]
        else:
            stream = song.stream
            cache = Cache(stream.data, stream.size)
            self._cache['streams'][song.id] = stream, cache
        if 'Range' in request.headers:
            response.status = 206
            start_byte, end_byte = request.headers['Range'].replace(
                'bytes=', '').split('-')
            if start_byte:
                start_byte = int(start_byte)
            else:
                start_byte = 0
            if end_byte:
                end_byte = int(end_byte)
            else:
                end_byte = stream.size
            cache.offset = start_byte
            if 'download' in request.query:
                response.headers[
                    'Content-Disposition'] = 'attachment; filename="{} - {} - {}.mp3"'.format(
                        song.name, song.album.name, song.artist.name)
            response.headers['Accept-Ranges'] = 'bytes'
            response.headers['Content-Type'] = stream.data.info(
            )['Content-Type']
            response.headers['Content-Length'] = str(stream.size)
            response.headers['Content-Range'] = 'bytes {}-{}/{}'.format(
                start_byte, end_byte, stream.size)
            response.body = FileWrapper(cache)
        else:
            cache.reset()
            if 'download' in request.query:
                response.headers[
                    'Content-Disposition'] = 'attachment; filename="{} - {} - {}.mp3"'.format(
                        song.name, song.album.name, song.artist.name)
            response.headers['Accept-Ranges'] = 'bytes'
            response.headers['Content-Type'] = stream.data.info(
            )['Content-Type']
            response.headers['Content-Length'] = str(stream.size)
            response.body = FileWrapper(cache)
示例#11
0
class MusicClient(object):
    """ Music client which wraps grooveshark api, allowing music to be streamed
    """
    def __init__(self):
        self.client = Client()
        self.client.init()

    def stop(self):
        p = subprocess.Popen(["ps", "-A"], stdout=subprocess.PIPE)
        out, err = p.communicate()

        for line in out.splitlines():
            if "mplayer" in line:
                pid = int(line.split(None, 1)[0])
                os.kill(pid, signal.SIGKILL)

    def find(self, search, index=None, max_results=15, type="Songs"):
        """ Find a song via grooveshark api search.

        Args:
            search (string): song title to search for.
            index (None, int): index value of song selection.
            max_results (int, optional): number of results to return from the search.

        Returns:
            result (tuple, grooveshark.classes.Song, list): song result list
        """
        song_results = list(self.client.search(search,
                                               type=type))[:max_results]

        if isinstance(index, int):
            index = int(index)
            result_count = len(song_results)

            if -1 < index < result_count:
                result = song_results[index]
            else:
                result = []
        else:
            result = song_results

        return result

    def youtube(self, url):
        """ Build the pafy youtube object

        Args:
            url (string): the youtube url

        Returns:
            result Pafy youtube
        """
        youtube = pafy.new(url)

        return youtube

    def file(self, url):
        """ Build a loose song dict from a url

        Args:
            url (string): the file url

        Returns:
            result song (dict)
        """
        song = {
            "title": '',
            "artist": '',
            "album": '',
            "track": '',
            "url": url,
            "duration": '',
            "queued_by": ''
        }

        return song

    def search(self, search):
        """ Returns formatted string list of song results from the search term provided

        Args:
            (string): Formatted list of song search results
        """

        search_results = "\n".join([
            repr(index) + "." + song.name + " by " + song.artist.name +
            " from " + song.album.name
            for index, song in enumerate(self.find(search), start=1)
        ])
        search_results = search_results if search_results else "No results found for {0}".format(
            search)

        return search_results

    def radio(self, genre):
        return self.client.radio(genre)

    def play(self, song):
        """ Play song subprocess callback, via mplayer

        Args:
            queued (int): flag for tracking whether a queued song is playing
            song (dict): song dictionary retrieved from queue list
        """
        popen_object = None

        print("Playing " + song["title"] + " by " + song["artist"])
        FNULL = open(os.devnull, "w")
        popen_object = subprocess.Popen(["mplayer", song["url"]],
                                        shell=False,
                                        stdout=FNULL,
                                        stderr=subprocess.STDOUT,
                                        bufsize=1)

        while popen_object.poll() is None:
            time.sleep(1.0)
示例#12
0
class Grooveshark(Application):
    __URLS__ = {'/desktop/.*|/icons/.*' : 'www',
                '/request/popular' : 'popular',
                '/request/search' : 'search',
                '/request/stream' :  'stream'}
    www = Directory(os.path.join(os.path.dirname(__file__), 'www'))
    def __init__(self):
        super().__init__()
        self.client = Client()
        self.client.init()
        self._cache = {}
        self._cache['streams'] = {}     
    
    def _respond_json(self, data, response):
        response.headers['Content-Type'] = 'application/json; charset=UTF-8'
        response.body.append(json.dumps(data).encode('utf-8'))
    
    def _bad_request(self, message, response):
        response.status = 400
        response.message = 'ERROR'
        response.headers['Content-Type'] = 'application/json; charset=UTF-8'
        response.body.append(json.dumps({'status' : 'error', 'result' : message}).encode('utf-8'))
    
    def popular(self, request, response):
        if not 'popular' in self._cache:
            self._cache['popular'] =  (time.time(), [song.export() for song in self.client.popular()])
        if time.time() - self._cache['popular'][0] > 7200:
            self._cache['popular'] =  (time.time(), [song.export() for song in self.client.popular()])
        self._respond_json({'status' : 'success', 'result' : self._cache['popular'][1]}, response)
    
    def search(self, request, response):
        if not 'type' in request.query:
            request.qery['type'] = [SEARCH_TYPE_SONGS]
        if 'query' in request.query:
            if not request.query['type'][0] in (Client.SONGS,
                                                Client.ALBUMS,
                                                Client.ARTISTS):
                self._bad_request('unknown type', response)
            else:
                result = [object.export() for object in self.client.search(request.query['query'][0], request.query['type'][0])]
                self._respond_json({'status' : 'success', 'result' : result}, response)
        else:
            self._bad_request('missing query argument', response)
    
    def stream(self, request, response):
        song = Song.from_export(json.loads(request.query['song'][0]), self.client.connection)
        if song.id in self._cache['streams']:
            stream, cache = self._cache['streams'][song.id]
        else:
            stream = song.stream
            cache = Cache(stream.data, stream.size)
            self._cache['streams'][song.id] = stream, cache
        if 'Range' in request.headers:
            response.status = 206
            start_byte, end_byte = request.headers['Range'].replace('bytes=', '').split('-')
            if start_byte:
                start_byte = int(start_byte)
            else:
                start_byte = 0
            if end_byte:
                end_byte = int(end_byte)
            else:
                end_byte = stream.size
            cache.offset = start_byte
            if 'download' in request.query:
                response.headers['Content-Disposition'] = 'attachment; filename="{} - {} - {}.mp3"'.format(song.name, song.album.name, song.artist.name)
            response.headers['Accept-Ranges'] = 'bytes'
            response.headers['Content-Type'] = stream.data.info()['Content-Type']
            response.headers['Content-Length'] = str(stream.size)
            response.headers['Content-Range'] = 'bytes {}-{}/{}'.format(start_byte, end_byte, stream.size)
            response.body = FileWrapper(cache)
        else:
            cache.reset()
            if 'download' in request.query:
                response.headers['Content-Disposition'] = 'attachment; filename="{} - {} - {}.mp3"'.format(song.name, song.album.name, song.artist.name)
            response.headers['Accept-Ranges'] = 'bytes'
            response.headers['Content-Type'] = stream.data.info()['Content-Type']
            response.headers['Content-Length'] = str(stream.size)
            response.body = FileWrapper(cache)
示例#13
0
class Grooveshark(Application):
    __URLS__ = {
        "/desktop/.*|/icons/.*": "www",
        "/request/popular": "popular",
        "/request/search": "search",
        "/request/stream": "stream",
    }
    www = Directory(os.path.join(os.path.dirname(__file__), "www"))

    def __init__(self):
        super().__init__()
        self.client = Client()
        self.client.init()
        self._cache = {}
        self._cache["streams"] = {}

    def _respond_json(self, data, response):
        response.headers["Content-Type"] = "application/json; charset=UTF-8"
        response.body.append(json.dumps(data).encode("utf-8"))

    def _bad_request(self, message, response):
        response.status = 400
        response.message = "ERROR"
        response.headers["Content-Type"] = "application/json; charset=UTF-8"
        response.body.append(json.dumps({"status": "error", "result": message}).encode("utf-8"))

    def popular(self, request, response):
        if "popular" not in self._cache:
            self._cache["popular"] = (time.time(), [song.export() for song in self.client.popular()])
        if time.time() - self._cache["popular"][0] > 7200:
            self._cache["popular"] = (time.time(), [song.export() for song in self.client.popular()])
        self._respond_json({"status": "success", "result": self._cache["popular"][1]}, response)

    def search(self, request, response):
        if "type" not in request.query:
            request.query["type"] = [SEARCH_TYPE_SONGS]
        if "query" in request.query:
            if not request.query["type"][0] in (Client.SONGS, Client.ALBUMS, Client.ARTISTS):
                self._bad_request("unknown type", response)
            else:
                result = [
                    object.export()
                    for object in self.client.search(request.query["query"][0], request.query["type"][0])
                ]
                self._respond_json({"status": "success", "result": result}, response)
        else:
            self._bad_request("missing query argument", response)

    def stream(self, request, response):
        song = Song.from_export(json.loads(request.query["song"][0]), self.client.connection)
        if song.id in self._cache["streams"]:
            stream, cache = self._cache["streams"][song.id]
        else:
            stream = song.stream
            cache = Cache(stream.data, stream.size)
            self._cache["streams"][song.id] = stream, cache
        if "Range" in request.headers:
            response.status = 206
            start_byte, end_byte = request.headers["Range"].replace("bytes=", "").split("-")
            if start_byte:
                start_byte = int(start_byte)
            else:
                start_byte = 0
            if end_byte:
                end_byte = int(end_byte)
            else:
                end_byte = stream.size
            cache.offset = start_byte
            if "download" in request.query:
                response.headers["Content-Disposition"] = 'attachment; filename="{} - {} - {}.mp3"'.format(
                    song.name, song.album.name, song.artist.name
                )
            response.headers["Accept-Ranges"] = "bytes"
            response.headers["Content-Type"] = stream.data.info()["Content-Type"]
            response.headers["Content-Length"] = str(stream.size)
            response.headers["Content-Range"] = "bytes {}-{}/{}".format(start_byte, end_byte, stream.size)
            response.body = FileWrapper(cache)
        else:
            cache.reset()
            if "download" in request.query:
                response.headers["Content-Disposition"] = 'attachment; filename="{} - {} - {}.mp3"'.format(
                    song.name, song.album.name, song.artist.name
                )
            response.headers["Accept-Ranges"] = "bytes"
            response.headers["Content-Type"] = stream.data.info()["Content-Type"]
            response.headers["Content-Length"] = str(stream.size)
            response.body = FileWrapper(cache)
示例#14
0
from __future__ import print_function
from grooveshark import Client
import sys

userIn = sys.argv[1]

client = Client()
client.init()

for song in client.search(userIn, type='Songs'):
	print(song.name, song.artist, sep=';')
	break
示例#15
0
from __future__ import print_function
from grooveshark import Client
import sys

client = Client()
client.init()

for song in client.search("dark horse katy perry", type='Songs'):
	print(song.name, song.artist, song.album, sep='-',file=sys.stdout)
	break
示例#16
0
class MusicClient(object):
    """ Music client which wraps grooveshark api, allowing music to be streamed
    """
    def __init__(self):
        self.client = Client()
        self.client.init()

    def stop(self):
        p = subprocess.Popen(["ps", "-A"], stdout=subprocess.PIPE)
        out, err = p.communicate()

        for line in out.splitlines():
            if "mplayer" in line:
                pid = int(line.split(None, 1)[0])
                os.kill(pid, signal.SIGKILL)

    def find(self, search, index=None, max_results=15, type="Songs"):
        """ Find a song via grooveshark api search.

        Args:
            search (string): song title to search for.
            index (None, int): index value of song selection.
            max_results (int, optional): number of results to return from the search.

        Returns:
            result (tuple, grooveshark.classes.Song, list): song result list
        """
        song_results = list(self.client.search(search, type=type))[:max_results]

        if isinstance(index, int):
            index = int(index)
            result_count = len(song_results)

            if -1 < index < result_count:
                result = song_results[index]
            else:
                result = []
        else:
            result = song_results

        return result

    def youtube(self, url):
        """ Build the pafy youtube object

        Args:
            url (string): the youtube url

        Returns:
            result Pafy youtube
        """
        youtube = pafy.new(url)
        
        return youtube

    def file(self, url):
        """ Build a loose song dict from a url

        Args:
            url (string): the file url

        Returns:
            result song (dict)
        """
        song = {
            "title": '',
            "artist": '',
            "album": '',
            "track": '',
            "url": url,
            "duration": '',
            "queued_by": ''
        }

        return song

    def search(self, search):
        """ Returns formatted string list of song results from the search term provided

        Args:
            (string): Formatted list of song search results
        """

        search_results = "\n".join([repr(index) + "." + song.name + " by " + song.artist.name + " from " + song.album.name for index, song in enumerate(self.find(search), start=1)])
        search_results = search_results if search_results else "No results found for {0}".format(search)
        
        return search_results

    def radio(self, genre):
        return self.client.radio(genre)

    def play(self, song):
        """ Play song subprocess callback, via mplayer

        Args:
            queued (int): flag for tracking whether a queued song is playing
            song (dict): song dictionary retrieved from queue list
        """
        popen_object = None

        print("Playing " + song["title"] + " by " + song["artist"])
        FNULL = open(os.devnull, "w")
        popen_object = subprocess.Popen(["mplayer", song["url"]], shell=False, stdout=FNULL, stderr=subprocess.STDOUT, bufsize=1)

        while popen_object.poll() is None:
            time.sleep(1.0)