Vladimir Kolev avatar Vladimir Kolev committed d1f4846

Added console interface, still experimental. Please do not package it!

Comments (0)

Files changed (2)

+#!/usr/bin/env python2.7
+
+__title__ = "gsd-cli"
+__version__ = "0.1"
+__author__ = "Vladimir Kolev"
+__license__ = "MIT"
+__copyright__ = "Copyright 2013 Vladimir Kolev"
+
+from docopt import docopt
+
+from lib.Cli import Cli
+
+doc = """gsd-cli is a terminal frontend for gSharkDown
+
+Usage:
+    gsd-cli (search|play|download)
+    gsd-cli search <term> [--no-color]
+    gsd-cli play <songid> [--player <executable>]
+    gsd-cli download <songid> [-o <file>]
+    gsd-cli dall <term> [--folder <foldername>]
+    gsd-cli -h | --help
+    gsd-cli -v | --version
+
+Options:
+    --no-color      Don't use colors
+    --player        Player to use
+    --file          Save the mp3 in a specified filepath
+    --folder        Create new folder at current position to download list
+    -h --help       Show help
+    -v --version    Show version
+
+Please be awere that using gsd-cli is not legal in some countries
+"""
+
+if __name__ == "__main__":
+    args = docopt(doc, version=__version__)
+    cli = Cli(**args)
+    cli.start()
+import os
+import sys
+import urllib
+from progressbar import Bar, ETA, Percentage, FileTransferSpeed, RotatingMarker, ProgressBar
+from termcolor import colored
+import groove
+import termios
+import fcntl
+
+class Cli(object):
+
+
+    def __init__(self, *args, **kwargs):
+        self.args = kwargs
+        self.pbar = None
+
+    def start(self):
+        if self.args.get('search'):
+            search = ""
+            if self.args.get('<term>'):
+                search = self.args.get('<term>', False)
+                print "Searching for %s" % (search)
+                try:
+                    groove.init()
+                    results = groove.getSearchResultsEx(search.encode('utf-8'))
+                    count = 0
+                    for song in results:
+                        print colored("[%d]" % count, 'white', attrs=['underline']), \
+                                colored("::", 'blue'), \
+                                colored(song['SongID'], 'blue', attrs=['bold']), \
+                            "\t:", colored(song['ArtistName'], 'white', attrs=['bold']), \
+                            "-", colored(song['SongName'])
+                        count += 1
+                        if count % 20 == 0:
+                            print colored('More results = c | Stop results = q | Download = d', 'green')
+                            key = self.getch()
+                            # Continue printing results
+                            if key in ['c', 'C']:
+                                continue
+                            else:
+                                break
+                    print colored("\t\tThis are all %d results" % (count), 'green', attrs=['bold'])
+                except:
+                    self.return_error("Grooveshark couldn't be initalized")
+
+            else:
+                self.return_warning("Nothing to search for")
+
+
+        elif self.args.get('play', False):
+            songid = ""
+            player = ""
+            if self.args.get("<song:id>"):
+                songid = self.args.get("<song:id>", False)
+            else:
+                self.return_error('No song:id specified.')
+            if self.args.get("--player"):
+                player = self.args.get('<executable>')
+            else:
+                self.return_error("No player specified.")
+            print "Playing %s in %s ..." % (songid, player)
+
+        elif self.args.get('download', False):
+            songid = ""
+            songurl = None
+            outfile = ""
+            if self.args.get("<songid>"):
+                songid = self.args.get("<songid>", False)
+                outfile = "%s.mp3" % (str(songid))
+                try:
+                    groove.init()
+                    response = groove.getStreamKeyFromSongIDEx(songid)
+                    playurls = "http://%s/stream.php?streamKey=%s"
+                    songurl = playurls % (response["result"]["%s" % songid]["ip"],
+                               response["result"]["%s" % songid]["streamKey"])
+                except Exception:
+                    self.return_error("Song with this ID was not found")
+                    sys.exit()
+            else:
+                self.return_warning("You must specify a SongID of the song")
+                sys.exit()
+
+            if self.args.get('-o'):
+                if self.args.get('<file>'):
+                    outfile = self.args.get('<file>', False)
+
+            if songurl is not None:
+                widgets = [colored('Downloading: ', 'blue', attrs=['bold']),
+                        Percentage(), ' ', Bar(marker=RotatingMarker()), ' ',
+                        ETA(), ' ', FileTransferSpeed()]
+                self.pbar = ProgressBar(widgets=widgets)
+                urllib.urlretrieve(songurl, outfile, reporthook=self._dlProgress)
+                self.pbar.finish()
+
+        elif self.args.get('dall', False):
+            print self.args
+            search = ""
+            outdir = ""
+            if self.args.get('<term>'):
+                search = self.args.get('<term>', False)
+
+            if self.args.get('--folder', False):
+                outdir = self.args.get('<foldername>', False)
+
+            print "Downloading all from %s in %s ..." % (search, outdir)
+
+    def _dlProgress(self, count, blockSize, totalSize):
+        if self.pbar.maxval is None:
+            self.pbar.maxval = totalSize
+            self.pbar.start()
+        self.pbar.update(min(count*blockSize, totalSize))
+
+    def return_error(self, message):
+        print colored("[ERROR] ", 'red', attrs=['bold']) + message + "\n"
+
+    def return_warning(self, message):
+        print colored("[WARNING] ", 'yellow', attrs=['bold']) + message + "\n"
+
+    def getch(self):
+        fd = sys.stdin.fileno()
+
+        oldterm = termios.tcgetattr(fd)
+        newattr = termios.tcgetattr(fd)
+        newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
+        termios.tcsetattr(fd, termios.TCSANOW, newattr)
+
+        oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
+        fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
+
+        try:
+            while 1:
+                try:
+                    c = sys.stdin.read(1)
+                    break
+                except IOError: pass
+        finally:
+            termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
+            fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
+        return c
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.