Ejemplo n.º 1
0
Archivo: views.py Proyecto: ggreer/G2
def next(request, authid):
  """Go to the next song in the playlist, and return a string for ices to parse.
  If nothing is next in the playlist, play "bees.mp3" or something"""
  if authid != settings.NEXT_PASSWORD:
    return HttpResponse()

  try:
    old = PlaylistEntry.objects.nowPlaying()
  except PlaylistEntry.DoesNotExist:
    # Nothing currently playing
    pass
  else:
    # Retire this entry
    oldentry = OldPlaylistEntry(song=old.song, adder=old.adder, addtime=old.addtime, playtime=old.playtime)
    oldentry.save()
    old.delete()

  # Now find a new item to play
  try:
    new = PlaylistEntry.objects.all()[0]
  except IndexError:
    # No more playlist entires
    location = settings.DEAD_AIR_TRACK
    metadata = "bees"
    return HttpResponse(location +'\n'+ metadata)
  else:
    new.playing = True
    new.playtime = datetime.datetime.today()
    new.save()
    song = new.song
    blame = " [blame %s]" % new.adder.username

  location = getSong(song)
  metadata = u"%s%s" % (song.metadataString(request.user), blame)
  return HttpResponse(location +'\n'+ metadata)
Ejemplo n.º 2
0
Archivo: views.py Proyecto: ggreer/G2
def api(request, resource=""):
  
  #authentication
  if request.user.is_authenticated():
    user = request.user
  else: #non-persistent authentication for things like bots and clients
    try:
      username = request.REQUEST['username']
    except KeyError:
      try: #is there a userid arg?
        username = User.objects.get(id=request.REQUEST['userid']).username
      except (User.DoesNotExist, KeyError):
        return HttpResponseForbidden()
    try: #try using password
      password = request.REQUEST['password']
      user = authenticate(username=username, password=password)
      if user is None:
        return HttpResponseForbidden()
    except KeyError:
      try: #try api_key
        api_key = request.REQUEST['key']
        userprofile = UserProfile.objects.get(user__username=username, api_key=api_key)
        user = userprofile.user
        if not userprofile.api_key: #api key not yet set
          return HttpResponseForbidden()
      except (KeyError, User.DoesNotExist):
        return HttpResponseForbidden()
        
  if resource == "nop":
    return HttpResponse("1")
        
  if resource == "nowplaying":
    try:
      entryid = PlaylistEntry.objects.nowPlaying().id
      return HttpResponse(str(entryid))
    except PlaylistEntry.DoesNotExist:
      return HttpResponse()
    
  if resource == "merge":
    if not user.has_perm("playlist.merge_song"):
      return HttpResponseForbidden()
    try:
      old = Song.objects.get(id=request.REQUEST['old'])
      new = Song.objects.get(id=request.REQUEST['new'])
    except KeyError:
      return HttpResponseBadRequest #args insufficient
    except Song.DoesNotExist:
      raise Http404 #songs don't exist
  
    logging.info("Mod %s (uid %d) merged song with sha_hash %s into %d at %s" %
      (request.user.username, request.user.id, old.sha_hash, new.id, now()))
    
    new.merge(old)
    return HttpResponse()
      
      
  
  if resource == "deletions":
    try:
      lastid = request.REQUEST['lastid']
    except KeyError:
      lastid = 0
    if not lastid: lastid = 0 #in case of "&lastid="
    deletions = RemovedEntry.objects.filter(id__gt=lastid)
    data = serialize("json", deletions, fields=('oldid'))
    return HttpResponse(data)
    
  

  if resource == "adds":
    try:
      lastid = request.REQUEST['lastid']
    except KeyError:
      lastid = 0
    if not lastid: lastid = 0
    adds = PlaylistEntry.objects.extra(select={"user_vote": "SELECT ROUND(score, 0) FROM playlist_rating WHERE playlist_rating.user_id = \
    %s AND playlist_rating.song_id = playlist_playlistentry.song_id", "avg_score": "SELECT AVG(playlist_rating.score) FROM playlist_rating WHERE playlist_rating.song_id = playlist_playlistentry.song_id", "vote_count": "SELECT COUNT(*) FROM playlist_rating WHERE playlist_rating.song_id = playlist_playlistentry.song_id"},
    select_params=[request.user.id]).select_related("song__artist", "song__album", "song__uploader", "adder").order_by('addtime').filter(id__gt=lastid)
    data = serialize("json", adds, relations={'song':{'relations':('artist'), 'fields':('title', 'length', 'artist', 'avgscore')}, 'adder':{'fields':('username')}})
    return HttpResponse(data)
    
  #if resource == "history":
    #try:
      #lastid = request.REQUEST['lastid']
    #except KeyError:
      #raise Http404
    #if not lastid: raise Http404
    #if lastid[0] != 'h':
      #raise Http404 #avert disaster
    #lastid = lastid[1:] #get rid of leading 'h'
    #history = OldPlaylistEntry.objects.select_related().filter(id__gt=lastid)
    #data = serialize("json", history, relations={'song':{'relations':('artist'), 'fields':('title', 'length', 'artist')}, 'adder':{'fields':('username')}})
    #return HttpResponse(data)
  
  if resource == "pltitle":
    try:
      return HttpResponse(PlaylistEntry.objects.nowPlaying().song.metadataString() + " - GBS-FM")
    except PlaylistEntry.DoesNotExist:
      return HtttpResponse("GBS-FM")
    
  
  def getSong(request):
    """Returns a song object given a request object"""
    try:
      songid = request.REQUEST['songid']
      songid = int(songid)
      song = Song.objects.get(id=songid)
    except KeyError:
      song = PlaylistEntry.objects.nowPlaying().song
    except ValueError:
      if songid == "curr":
        song = PlaylistEntry.objects.nowPlaying().song
      elif songid == "prev":
        song = OldPlaylistEntry.objects.select_related("song").extra(where=['playlist_oldplaylistentry.id =\
        (select max(playlist_oldplaylistentry.id) from playlist_oldplaylistentry)'])[0].song
    return song
  
  if resource == "favourite":
    song = getSong(request)
    if song in user.get_profile().favourites.all():
      state = "old favourite"
    else:
      user.get_profile().favourites.add(song)
      state = "new favourite"
    return HttpResponse(song.metadataString() +'\n' + state)
    
  if resource == "unfavourite":
    song = getSong(request)
    user.get_profile().favourites.remove(song)
    return HttpResponse(song.metadataString())
    
  #if resource == "getuser":
    #try:
      #user = User.objects.get(username=request.REQUEST['username'])
    #except KeyError:
      #user = request.user
    #except User.DoesNotExist:
      #raise Http404
    
    #return HttpResponse(user.id)
    
  if resource == "getfavourite":
    """
    Get a song from favourites of the specified user (ID: userid).
    Trys to make it addable but will return best unaddable one otherwise.
    """
    try:
      lover = User.objects.get(id=int(request.REQUEST['loverid']))
    except KeyError:
      try:
        lover = User.objects.get(username=str(request.REQUEST['lovername']))
      except KeyError:
        lover = user
    songs = lover.get_profile().favourites.all().check_playable(user)
    unplayed = songs.filter(on_playlist=False, banned=False) #TODO: use recently_played too!
    if unplayed: #only use it if there are actually unplayed songs!
      songs = unplayed
    try:
      song = random.choice(songs)
    except:
      raise Http404
    
    return HttpResponse(str(song.id) + "\n" + song.metadataString())
  
  if resource == "vote":
    if not user.has_perm("playlist.can_rate"):
      return HttpResponseForbidden()
    try:
      vote = float(request.REQUEST['vote'])
    except KeyError:
      raise Http404
    song = getSong(request)
    prevscore = song.rate(vote, user)
    
    return HttpResponse(str(prevscore) + " " +song.metadataString())
  
  if resource == "comment":
    if not user.has_perm("playlist.can_comment"):
      return HttpResponseForbidden()
    try:
      comment = request.REQUEST['comment']
    except KeyError:
      raise Http404
    song = getSong(request)
    time = song.comment(user, comment)
    
    return HttpResponse(str(time))
    
  if resource == "pllength":
    length = PlaylistEntry.objects.length()
    try:
      comment = request.REQUEST['formatted']
      return render_to_response('pl_length.html', {'length':length})
    except KeyError:
      return HttpResponse(str(length['seconds']) + '\n' + str(length['song_count']))
  
  if resource == "add":
    if not user.has_perm("playlist.queue_song"):
      return HttpResponseForbidden()
    try:
      song = Song.objects.select_related().get(id=request.REQUEST['songid'])
    except (KeyError, Song.DoesNotExist):
      raise Http404
    
    try: 
      song.playlistAdd(user)
    except AddError, e:
      return HttpResponseBadRequest(e.args[0])
    
    return HttpResponse(song.metadataString())
Ejemplo n.º 3
0
def api(request, resource=""):

  #authentication
  if request.user.is_authenticated:
    user = request.user
  else: #non-persistent authentication for things like bots and clients
    try:
      username = request.GET['username']
    except KeyError:
      try: #is there a userid arg?
        username = User.objects.get(id=request.GET['userid']).username
      except (User.DoesNotExist, KeyError):
        return HttpResponseForbidden()
    try: #try using password
      password = request.GET['password']
      user = authenticate(username=username, password=password)
      if user is None:
        return HttpResponseForbidden()
    except KeyError:
      try: #try api_key
        api_key = request.GET['key']
        userprofile = UserProfile.objects.get(user__username=username, api_key=api_key)
        user = userprofile.user
        if not userprofile.api_key: #api key not yet set
          return HttpResponseForbidden()
      except (KeyError, User.DoesNotExist):
        return HttpResponseForbidden()

  if resource == "nop":
    return HttpResponse("1")

  if resource == "restartftp":
    Popen(["/srv/pydj/doc/killftp.sh"]).wait()
    olddir = os.curdir
    os.chdir('/srv/pydj/')
    Popen(["python", "manage.py", "ftp"])
    os.chdir(olddir)
    return HttpResponse("ftp_restarted")

  if resource == "nowplaying":
    try:
      entryid = PlaylistEntry.objects.nowPlaying().id
      return HttpResponse(str(entryid))
    except PlaylistEntry.DoesNotExist:
      return HttpResponse()

  if resource == "merge":
    if not user.has_perm("playlist.merge_song"):
      return HttpResponseForbidden()
    try:
      old = Song.objects.get(id=request.GET['old'])
      new = Song.objects.get(id=request.GET['new'])
    except KeyError:
      return HttpResponseBadRequest #args insufficient
    except Song.DoesNotExist:
      raise Http404 #songs don't exist

    logging.info("Mod %s (uid %d) merged song with sha_hash %s into %d at %s" %
      (request.user.username, request.user.id, old.sha_hash, new.id, now()))

    new.merge(old)
    return HttpResponse()



  if resource == "deletions":
    try:
      lastid = request.GET['lastid']
    except KeyError:
      lastid = 0
    if not lastid: lastid = 0 #in case of "&lastid="
    deletions = RemovedEntry.objects.filter(id__gt=lastid)
    data = serialize("json", deletions, fields=('oldid'))
    return HttpResponse(data)



  if resource == "adds":
    try:
      lastid = request.GET['lastid']
    except KeyError:
      lastid = 0
    if not lastid: lastid = 0
    adds = PlaylistEntry.objects.extra(select={"user_vote": "SELECT ROUND(score, 0) FROM playlist_rating WHERE playlist_rating.user_id = \
    %s AND playlist_rating.song_id = playlist_playlistentry.song_id", "avg_score": "SELECT AVG(playlist_rating.score) FROM playlist_rating WHERE playlist_rating.song_id = playlist_playlistentry.song_id", "vote_count": "SELECT COUNT(*) FROM playlist_rating WHERE playlist_rating.song_id = playlist_playlistentry.song_id"},
    select_params=[request.user.id]).select_related("song__artist", "song__album", "song__uploader", "adder").order_by('addtime').filter(id__gt=lastid)
    data = serialize("json", adds, relations={'song':{'relations':('artist'), 'fields':('title', 'length', 'artist', 'avgscore')}, 'adder':{'fields':('username')}})
    return HttpResponse(data)

  #if resource == "history":
    #try:
      #lastid = request.GET['lastid']
    #except KeyError:
      #raise Http404
    #if not lastid: raise Http404
    #if lastid[0] != 'h':
      #raise Http404 #avert disaster
    #lastid = lastid[1:] #get rid of leading 'h'
    #history = OldPlaylistEntry.objects.select_related().filter(id__gt=lastid)
    #data = serialize("json", history, relations={'song':{'relations':('artist'), 'fields':('title', 'length', 'artist')}, 'adder':{'fields':('username')}})
    #return HttpResponse(data)

  if resource == "pltitle":
    try:
      return HttpResponse(PlaylistEntry.objects.nowPlaying().song.metadataString() + " - GBS-FM")
    except PlaylistEntry.DoesNotExist:
      return HtttpResponse("GBS-FM")


  if resource == "pltitle2":
    try:
      return HttpResponse(PlaylistEntry.objects.nowPlaying().song.metadataString())
    except PlaylistEntry.DoesNotExist:
      return HtttpResponse("GBS-FM")


  def getSong(request):
    """Returns a song object given a request object"""
    try:
      songid = request.GET['songid']
      songid = int(songid)
      song = Song.objects.get(id=songid)
    except KeyError:
      song = PlaylistEntry.objects.nowPlaying().song
    except ValueError:
      if songid == "curr":
        song = PlaylistEntry.objects.nowPlaying().song
      elif songid == "prev":
        song = OldPlaylistEntry.objects.select_related("song").extra(where=['playlist_oldplaylistentry.id =\
        (select max(playlist_oldplaylistentry.id) from playlist_oldplaylistentry)'])[0].song
    return song

  if resource == "favourite":
    song = getSong(request)
    if song in user.userprofile.favourites.all():
      state = "old favourite"
    else:
      user.userprofile.favourites.add(song)
      state = "new favourite"
    return HttpResponse(song.metadataString() +'\n' + state)

  if resource == "unfavourite":
    song = getSong(request)
    user.userprofile.favourites.remove(song)
    return HttpResponse(song.metadataString())

  #if resource == "getuser":
    #try:
      #user = User.objects.get(username=request.GET['username'])
    #except KeyError:
      #user = request.user
    #except User.DoesNotExist:
      #raise Http404

    #return HttpResponse(user.id)

  if resource == "getfavourite":
    """
    Get a song from favourites of the specified user (ID: userid).
    Trys to make it addable but will return best unaddable one otherwise.
    """
    try:
      lover = User.objects.get(id=int(request.GET['loverid']))
    except KeyError:
      try:
        lover = User.objects.get(username=str(request.GET['lovername']))
      except KeyError:
        lover = user
    songs = lover.userprofile.favourites.all().check_playable(user)
    unplayed = songs.filter(on_playlist=False, banned=False) #TODO: use recently_played too!
    if unplayed: #only use it if there are actually unplayed songs!
      songs = unplayed
    try:
      song = random.SystemRandom().choice(songs)
    except:
      raise Http404

    return HttpResponse(str(song.id) + "\n" + song.metadataString())

  if resource == "vote":
    if not user.has_perm("playlist.can_rate"):
      return HttpResponseForbidden()
    try:
      vote = float(request.GET['vote'])
    except KeyError:
      raise Http404
    song = getSong(request)
    prevscore = song.rate(vote, user)

    return HttpResponse(str(prevscore) + " " +song.metadataString())

  if resource == "comment":
    if not user.has_perm("playlist.can_comment"):
      return HttpResponseForbidden()
    try:
      comment = request.GET['comment']
    except KeyError:
      raise Http404
    song = getSong(request)
    time = song.comment(user, comment)

    return HttpResponse(str(time))

  if resource == "pllength":
    length = PlaylistEntry.objects.length()
    try:
      comment = request.GET['formatted']
      return render(request, 'pl_length.html', {'length':length})
    except KeyError:
      return HttpResponse(str(length['seconds']) + '\n' + str(length['song_count']))

  if resource == "add":
    if not user.has_perm("playlist.queue_song"):
      return HttpResponseForbidden()
    try:
      song = Song.objects.select_related().get(id=request.GET['songid'])
    except (KeyError, Song.DoesNotExist):
      raise Http404

    try:
      song.playlistAdd(user)
    except AddError, e:
      return HttpResponseBadRequest(e.args[0])

    return HttpResponse(song.metadataString())
Ejemplo n.º 4
0
Archivo: views.py Proyecto: ggreer/G2
    except AddError, e:
      return HttpResponseBadRequest(e.args[0])
    
    return HttpResponse(song.metadataString())
    
  if resource == "uncomment":
    try:
      comment = Comment.objects.select_related().filter(user=user)[0]
      comment.delete()
    except IndexError:
      raise Http404
    
    return HttpResponse(comment.song.metadataString())
  
  if resource == "metadata":
    song = getSong(request)
    return HttpResponse(song.artist.name + "\n" + song.album.name + "\n" + song.title)

  if resource == "metadata2":
    song = getSong(request)
    return HttpResponse(song.artist.name + "\n" + song.album.name + "\n" + song.title + "\n" + str(song.length)) 

  if resource == "randid":
    randomid = randomdongid()
    return HttpResponse(int(randomid[0]))

  if resource == "listeners":
    return HttpResponse(ListenerCount())
    
  if resource == "users":
    return HttpResponse(Users.objects.all().count())
Ejemplo n.º 5
0
    except AddError, e:
      return HttpResponseBadRequest(e.args[0])

    return HttpResponse(song.metadataString())

  if resource == "uncomment":
    try:
      comment = Comment.objects.select_related().filter(user=user)[0]
      comment.delete()
    except IndexError:
      raise Http404

    return HttpResponse(comment.song.metadataString())

  if resource == "metadata":
    song = getSong(request)
    return HttpResponse(song.artist.name + "\n" + song.album.name + "\n" + song.title)

  if resource == "metadata2":
    song = getSong(request)
    return HttpResponse(song.artist.name + "\n" + song.album.name + "\n" + song.title + "\n" + str(song.length))

  if resource == "randid":
    randomid = randomdongid()
    return HttpResponse(int(randomid[0]))

  if resource == "plinfo":
    pldongid = request.GET.get('plid', 0)
    playlistinfo = plinfoq(pldongid)
    return HttpResponse(str(playlistinfo[0]) + "\n" + playlistinfo[2] + "\n" + playlistinfo[3] + "\n" + playlistinfo[1])
    #return HttpResponse(playlistinfo)