di-p - sweb - Some web helper scripts.
git clone git://r-36.net/sweb
Log
Files
Refs
LICENSE
---
di-p (4712B)
---
     1 #!/usr/bin/python
     2 # coding=utf-8
     3 #
     4 # Copy me if you can.
     5 # by 20h
     6 #
     7 
     8 import sys
     9 import json
    10 import os
    11 import time
    12 import datetime
    13 import random
    14 import signal
    15 from subprocess import Popen
    16 import requests
    17 from getopt import getopt, GetoptError
    18 
    19 def runstream(player, stream):
    20         return Popen("%s \"%s\"" % (player, stream["playlist"]),
    21                         shell=True)
    22 
    23 def loadplaylistall():
    24         pluri = "http://api.audioaddict.com/v1/di/track_history.jsonp?"\
    25                         "callback=_API_TrackHistory_getAll&_=%s"
    26 
    27         utim = time.mktime(datetime.datetime.now().timetuple())
    28         fd = requests.get(pluri % (utim))
    29         playlists = str(fd.read(), "iso-8859-1")
    30         fd.close()
    31         playlists = playlists[playlists.index("(")+1:\
    32                         playlists.rindex(");")]
    33         playlist = json.loads(playlists)
    34 
    35 def loadplaylist(ids):
    36         pluri = "http://api.v2.audioaddict.com/v1/di/track_history/"\
    37                         "channel/%s.jsonp?callback=_API_Track"\
    38                         "History_getChannel&_=%s"
    39 
    40         utim = time.mktime(datetime.datetime.now().timetuple())
    41         fd = requests.get(pluri % (ids, utim))
    42         playlists = fd.text
    43         playlists = playlists[playlists.index("[{"):\
    44                         playlists.rindex(");")]
    45         playlist = json.loads(playlists)
    46 
    47         return playlist
    48 
    49 def usage(app):
    50         app = os.path.basename(app)
    51         sys.stderr.write("usage: %s [-dnluwy] [-i channel URI] [-p player]"\
    52                         " [-s shuffletime]"\
    53                         " key\n" % (app))
    54         sys.exit(1)
    55 
    56 def main(args):
    57         try:
    58                 opts, largs = getopt(args[1:], "hai:p:dlnrs:uwy")
    59         except GetoptError as err:
    60                 print(str(err))
    61                 usage(args[0])
    62                 sys.exit(1)
    63         
    64         uri = "http://listen.di.fm/public3"
    65 
    66         player = "mpv -quiet -cache 512 -playlist"
    67         debug = False
    68         listen = False
    69         plainlist = False
    70         playlist = False
    71         # 10 minutes
    72         shuffletime = 600
    73         doshuffle = False
    74         dorandom = False
    75         showuri = False
    76         doplaylist = False
    77         whatson = False
    78         for o, a in opts:
    79                 if o == "-d":
    80                         debug = True
    81                 elif o == "-a":
    82                         doplaylist = True
    83                 elif o == "-h":
    84                         usage(args[0])
    85                 elif o == "-i":
    86                         uri = a
    87                 elif o == "-l":
    88                         listen = True
    89                 elif o == "-p":
    90                         player = a
    91                 elif o == "-n":
    92                         plainlist = True
    93                 elif o == "-r":
    94                         dorandom = True
    95                 elif o == "-s":
    96                         doshuffle = True
    97                         shuffletime = int(a)
    98                 elif o == "-u":
    99                         showuri = True
   100                 elif o == "-y":
   101                         playlist = True
   102                 elif o == "-w":
   103                         whatson = True 
   104                 else:
   105                         assert False, "unhandled option"
   106         
   107         if len(largs) < 1 and listen != True and dorandom != True and \
   108                         doplaylist != True and whatson != True and \
   109                         playlist != True:
   110                 sys.stderr.write("You need to specify the to be played "
   111                                 "stream. Please see -l for all available "
   112                                 "streams.\n")
   113                 usage(args[0])
   114 
   115         fd = requests.get(uri)
   116         streams = fd.json()
   117 
   118         streams = sorted(streams, key = lambda k: k["key"])
   119 
   120         if doplaylist == True:
   121                 sys.stdout.write("[Playlist]\n")
   122                 sys.stdout.write("Version=2\n")
   123                 sys.stdout.write("NumOfEntries=%d\n" % (len(streams)))
   124 
   125                 i = 1
   126                 for stream in streams:
   127                         sys.stdout.write("Title%d=%s\n" % (i,
   128                                 stream["key"]))
   129                         sys.stdout.write("File%d=%s\n" % (i,
   130                                 stream["playlist"]))
   131                         i = i + 1
   132                 sys.stdout.write("\n")
   133 
   134                 return 0
   135 
   136         if whatson == True:
   137                 recentdata = loadplaylistall()
   138                 for i in streams:
   139                         cplay = recentdata[str(i["id"])]
   140                         sys.stdout.write("%s\t%s\n" % (i["key"],\
   141                                 cplay["track"]))
   142 
   143                 return 0
   144 
   145         if playlist == True:
   146                 def displayplaylist(playlist):
   147                         for song in playlist[::-1]:
   148                                 dates = datetime.datetime.fromtimestamp(
   149                                                 int(song["started"])).\
   150                                         strftime("%H:%M:%S")
   151                                 sys.stdout.write("[%s] %s\n" % (dates,\
   152                                         song["track"]))
   153 
   154                 for i in streams:
   155                         if i["key"] != largs[0]:
   156                                 continue
   157 
   158                         cplaylist = loadplaylist(i["id"])
   159                         displayplaylist(cplaylist)
   160                 return 0
   161 
   162         if listen == True:
   163                 if plainlist == True:
   164                         for i in streams:
   165                                 print(i["key"]) 
   166                         return 0
   167 
   168                 if showuri == True:
   169                         for i in streams:
   170                                 print(i["playlist"])
   171                         return 0
   172 
   173                 for i in streams:
   174                         print("%30s %s" % (i["key"], 
   175                                         i["name"]))
   176                 return 0
   177 
   178         stream = None
   179         if dorandom == True:
   180                 stream = random.choice(streams);
   181         else:
   182                 for i in streams:
   183                         if i["key"] == largs[0]:
   184                                 stream = i
   185                                 break
   186 
   187         if stream == None:
   188                 sys.stderr.write("Could not find the given stream." \
   189                         " Please use -l for all available streams.\n")
   190                 return 1
   191 
   192         if showuri == True:
   193                 print(("%s" % (stream["playlist"])))
   194                 return 0
   195 
   196         while 1:
   197                 p = runstream(player, stream)
   198                 sts = os.waitpid(p.pid, os.P_NOWAIT)[1]
   199                 if sts < 0:
   200                         return 1
   201 
   202                 if doshuffle == False:
   203                         break
   204 
   205                 i = 0
   206                 while 1:
   207                         time.sleep(1);
   208                         i += 1
   209 
   210                         sts = os.waitpid(p.pid, os.P_NOWAIT)[1]
   211                         if sts < 0 or i > shuffletime:
   212                                 if i > shuffletime:
   213                                         os.kill(p.pid, signal.SIGTERM)
   214                                         os.waitpid(p.pid, os.P_WAIT)
   215 
   216                                 stream = random.choice(streams)
   217                                 break
   218 
   219         os.waitpid(p.pid, os.P_WAIT)
   220 
   221         return 0
   222 
   223 if __name__ == "__main__":
   224         sys.exit(main(sys.argv))
   225