Exemple #1
0
  def get(self):
    ## Album list disabled until it is further optimized.
    #album_list = []
    album_list = Album.get_new(num=36)
    start = datetime.date.today() - datetime.timedelta(days=6)
    end = datetime.date.today() + datetime.timedelta(days=1)
    song_num = 10
    album_num = 10
    logging.debug("Calling get top")
    top_songs, top_albums = Play.get_top(start, end, song_num, album_num)
    posts = BlogPost.get_last(num=3)
    events = Event.get_upcoming(num=3)

    template_values = {
      'news_selected': True,
      'flash': self.flashes,
      'session': self.session,
      'album_list': album_list,
      'top_songs': top_songs,
      'top_albums': top_albums,
      'posts': posts,
      'events': events,
      }
    self.response.out.write(template.render(get_path("index.html"),
                                            template_values))
Exemple #2
0
 def get(self):
   self.response.headers["Content-Type"] = "text/json"
   album_key = ndb.Key(urlsafe=self.request.get("album_key"))
   songlist_html = memcache.get("songlist_html_%s" % album_key.urlsafe())
   if songlist_html:
     self.response.out.write(json.dumps({
           'songListHtml': songlist_html,
           'generated': 'memcache',
           }))
     return
   album = Album.get(album_key, one_key=True)
   self.response.headers["Content-Type"] = "text/json"
   if not album:
     self.response.out.write(json.dumps({
           'err': ("An error occurred and the specified album could "
                   "not be found.  Please try again.")
           }))
     return
   songlist_html = template.render(get_path("ajax_songlist.html"), {
       'songList': Song.get(album.tracklist),
       })
   memcache.set("songlist_html_%s"%album_key.urlsafe(), songlist_html)
   self.response.out.write(json.dumps({
         'songListHtml': template.render(get_path("ajax_songlist.html"), {
             'songList': Song.get(album.tracklist),
             }),
         'generated': 'generated',
         }))
Exemple #3
0
  def get(self):
    if not self.session_has_program():
      self.session.add_flash(
        "You can't chart songs until you have an associated program in the "
        "system.  Please contact a member of management immediately.")
      self.redirect("/dj/")
      return

    memcache_key = "playlist_html_%s"%self.session.get('program').get('key')
    playlist_html = memcache.get(memcache_key)
    if not playlist_html:
      playlist_html = template.render("dj_chartsong_playlist_div.html",
        {'playlist': Play.get_last(num=50,
                                   program=Program.get(self.program_key),
                                   after=(datetime.date.today())),
         }
      )
      memcache.set(memcache_key, playlist_html, 60 * 60 * 24)

    last_psa = None #Psa.get_last() # cache.getLastPsa()
    new_albums = None
    #new_song_div_html = memcache.get("new_song_div_html")
    album_songs = []
    new_song_div_html = None
    if not new_song_div_html:
      new_albums = Album.get_new() #by_artist=True)
      if new_albums:
        logging.debug(new_albums)
        album_songs = Song.get(new_albums[0].tracklist)
      new_song_div_html = template.render(
        get_path("dj_chartsong_newsongdiv.html"),
        {'new_albums': new_albums,
         'album_songs': album_songs,})
      memcache.set("new_song_div_html", new_song_div_html)

    template_values = {
      'last_psa': last_psa,
      'playlist_html': playlist_html,
      'session': self.session,
      'flash': self.flashes,
      'new_albums': new_albums,
      'album_songs': album_songs,
      'new_song_div_html': new_song_div_html,
    }
    self.response.out.write(
      template.render(get_path("dj_chartsong.html"), template_values))
Exemple #4
0
  def get(self):
    new_album_list = None
 #   new_album_html = memcache.get("manage_new_albums_html")
 #   if not new_album_html:
    new_album_list = Album.get_new()
    new_album_html = template.render(
        get_path("dj_manage_new_albums_list.html"),
        {'new_album_list': new_album_list})
    memcache.set("manage_new_albums_html", new_album_html)
    template_values = {
      'new_album_list': new_album_list,
      'new_album_html': new_album_html,
      'session': self.session,
      'flash': self.flashes,
    }
    self.response.out.write(
        template.render(get_path("dj_manage_albums.html"), template_values))
Exemple #5
0
  def post(self):
    if self.request.get("submit") == "Chart Song":
      # Charting a song, not a PSA or ID
      track_artist = self.request.get("artist").encode("latin1", 'replace')
      trackname = self.request.get("trackname").encode("latin1", 'replace')
      isNew = int(self.request.get("isNew"))
      if isNew > 0:
        # if it's "new", the album should be in the datastore already with
        # a valid key.
        album = Album.get(self.request.get("album_key"))
        if not album:
          self.session.add_flash(
            "Missing album information for new song, please try again.")
          self.redirect("/dj/chartsong/")
          return
        # likewise, the song should be in the datastore already with a
        # valid key.
        song = Song.get(self.request.get("song_key"))
        if not song:
          self.session.add_flash(
            "An error occurred trying to fetch the song, please try again.")
          self.redirect("/dj/chartsong/")
          return
        logging.debug(song)
        trackname = song.title
        track_artist = song.artist
        Play.new(song=song, program=self.program_key,
                 play_date=datetime.datetime.now(), is_new=True,
                 artist=album.artist).put()
      else:
        # a song needs to have an artist and a track name
        if not track_artist or not trackname:
          self.session.add_flash(
            "Missing track information, please fill out both fields.")
          self.redirect("/dj/chartsong/")
          return
        song = Song.new(title=trackname, artist=track_artist)
        song.put()

        Play.new(song=song, program=self.program_key,
                 play_date=datetime.datetime.now(), isNew=False,
                 artist=track_artist).put()
      memcache_key = "playlist_html_%s"%self.session.get('program').get('key')
      playlist_html = template.render(
        "dj_chartsong_playlist_div.html",
        {'playlist': Play.get_last(
          program=self.program_key,
          after=(datetime.datetime.now() - datetime.timedelta(days=1)))})
      memcache.set(memcache_key, playlist_html, 60 * 60 * 24)
      ArtistName.try_put(track_artist)

      try:
        # last.fm integration
        lastfm_username = "******"
        lastfm_password = "******"
        lastfm_api_key = "59925bd7155e59bd39f14adcb70b7b77"
        lastfm_secret_key = "6acf5cc79a41da5a16f36d5baac2a484"
        network = pylast.get_lastfm_network(api_key=lastfm_api_key,
          api_secret=lastfm_secret_key,
          username=lastfm_username,
          password_hash=pylast.md5(lastfm_password))
        scrobbler = network.get_scrobbler("tst", "1.0")
        scrobbler.scrobble(track_artist, trackname, int(time.time()),
          pylast.SCROBBLE_SOURCE_USER, pylast.SCROBBLE_MODE_PLAYED, 60)
        self.session.add_flash(
          "%s has been charted and scrobbled to Last.FM,"
          " and should show up below."%trackname)
      except:
        # just catch all errors with the last.fm; it's not that important that
        # everything get scrobbled exactly; plus this is like the #1 source
        # of errors in charting songs.
        self.session.add_flash(
          "%s has been charted, but was not scrobbled to Last.FM"%
          trackname)
      self.redirect("/dj/chartsong/")
      return
      # End of song charting.
    elif self.request.get("submit") == "Station ID":
      # If the DJ has recorded a station ID
      station_id = models._raw_models.StationID(program=self.program_key,
                                    play_date=datetime.datetime.now())
      station_id.put()
      self.session.add_flash("Station ID recorded.")
      self.redirect("/dj/chartsong/")
      return
    elif self.request.get("submit") == "PSA":
      # If the DJ has recorded a PSA play
      psa_desc = self.request.get("psa_desc")
      Psa.new(desc=psa_desc, program=self.program_key).put()
      self.session.add_flash("PSA recorded.")
      self.redirect("/dj/chartsong/")
      return
Exemple #6
0
  def post(self):
    self.response.headers['Content-Type'] = 'text/json'
    action = self.request.get("action")

    if action == "add":
      self.response.headers['Content-Type'] = 'text/json'
      # asin is Amazon's special ID number.
      # unique to the product (but different versions of the same
      # thing will have different ASIN's, like a vinyl vs. a cd vs. a
      # special edition etc.)
      asin = self.request.get("asin")
      album = Album.get(asin=asin)
      if album:
        album.set_new()
        album.put()
        self.response.out.write(json.dumps({
          'msg': "Success, already existed. The album was re-set to new."
        }))
        return

      # Grab the product details from Amazon to save to our datastore.
      i = amazon.productSearch(asin)
      try:
        i = i[0]
      except IndexError:
        self.response.out.write(json.dumps({
          'err': ("An error occurred.  Please try again, or if this keeps "
                  "happening, select a different album.")
        }))
        return
      # this overly complicated code sets up the json data associated with
      # the album we're adding.  It pulls the appropriate values from the
      # XML received.
      json_data = {
        'small_pic': i.getElementsByTagName(
          "SmallImage")[0].getElementsByTagName("URL")[0].firstChild.nodeValue,
        'large_pic': i.getElementsByTagName(
          "LargeImage")[0].getElementsByTagName("URL")[0].firstChild.nodeValue,
        'artist': i.getElementsByTagName("Artist")[0].firstChild.nodeValue,
        'title': i.getElementsByTagName("Title")[0].firstChild.nodeValue,
        'asin': i.getElementsByTagName("ASIN")[0].firstChild.nodeValue,
        'tracks': [t.firstChild.nodeValue
                   for t in i.getElementsByTagName("Track")],
      }
      largeCover = urlfetch.fetch(json_data['large_pic']).content
      large_filetype = json_data['large_pic'][-4:].strip('.')
      smallCover = urlfetch.fetch(json_data['small_pic']).content
      small_filetype = json_data['small_pic'][-4:].strip('.')

      title = json_data['title']
      artist = json_data['artist']
      tracks = json_data['tracks']

    elif action == "makeNew":
      # We're marking an existing album as "new" again
      self.response.headers['Content-Type'] = 'text/json'
      key = self.request.get("key")
      try:
        album = Album.get(key)
        album.set_new()
        album.put()
      except:
        self.response.out.write(
            json.dumps({'err': "Album not found. Please try again."}))
        return

      self.response.out.write(json.dumps({'msg': "Made new."}))
      return

    elif action == "makeOld":
      # We're removing the "new" marking from an album
      self.response.headers['Content-Type'] = 'text/json'
      key = self.request.get("key")
      try:
        album = Album.get(key)
        album.unset_new()
        album.put()
      except NoSuchEntry:
        pass
      self.response.out.write(json.dumps({'msg': "Made old."}))
      return

    elif action == "manual":
      # The user has typed in the title, the artist, all track names,
      # and provided a cover image URL.
      tracks = self.request.get("track-list")
      tracks = [line.strip() for line in tracks.splitlines() if
                len(line.strip()) > 0]
      cover_url = self.request.get("cover_url")
      if not cover_url:
        cover_url = "/static/images/noalbumart.png"

      # Try to fetch the cover art, if possible
      try:
        largeCover = urlfetch.fetch(cover_url).content
      except urlfetch.ResponseTooLargeError:
        if self.request.get("ajax"):
          self.response.out.write(
            json.dumps({
                'msg': ("The image you provided was too large. "
                        "There is a 1MB limit on cover artwork. "
                        "Try a different version with a reasonable size."),
                'result': 1,}))
        else:
          self.session.add_flash(
              "The image you provided was too large. "
              "There is a 1MB limit on cover artwork. "
              "Try a different version with a reasonable size.")
          self.redirect("/dj/albums/")
        return
      except urlfetch.InvalidURLError:
        if self.request.get("ajax"):
          self.response.out.write(
            json.dumps({
                'msg': ("The URL you provided could not be downloaded. "
                        "Hit back and try again."),
                'result': 1,}))
        else:
          self.session.add_flash("The URL you provided could "
                                 "not be downloaded. "
                                 "Try again.")
          self.redirect("/dj/albums/")
        return
      except urlfetch.DownloadError:
        if self.request.get("ajax"):
          self.response.out.write(
            json.dumps({
              'msg': ("The URL you provided could not be downloaded. "
                      "Hit back and try again."),
              'result': 1,}))
        else:
          self.session.add_flash("The URL you provided could "
                                 "not be downloaded. Try again.")
          self.redirect("/dj/albums")
        return

      large_filetype = cover_url[-4:].strip('.')
      smallCover = images.resize(largeCover, 100, 100)
      small_filetype = large_filetype

      title = self.request.get('title')
      artist = self.request.get('artist')
      asin = None


    ## Create the actual objects and store them
    fn = "%s_%s"%(slughifi(artist), slughifi(title))
    # Create the file nodes in the blobstore
    # _blobinfo_uploaed_filename WILL change in the future.
    small_file = files.blobstore.create(
      mime_type=small_filetype,
      _blobinfo_uploaded_filename="%s_small.png"%fn)
    large_file = files.blobstore.create(
      mime_type=large_filetype,
      _blobinfo_uploaded_filename="%s_big.png"%fn)

    # Write the images
    with files.open(small_file, 'a') as small:
      small.write(smallCover)
    with files.open(large_file, 'a') as large:
      large.write(largeCover)

    files.finalize(small_file)
    files.finalize(large_file)

    cover_small=files.blobstore.get_blob_key(small_file)
    cover_large=files.blobstore.get_blob_key(large_file)

    # Finally, create the album
    album = Album.new(title=title,
                      artist=artist,
                      tracks=tracks,
                      asin=asin,
                      cover_small=cover_small,
                      cover_large=cover_large)
    album.put()

    if self.request.get("ajax"):
      self.response.out.write(
        json.dumps({
            'msg': ("The album \"%s\" by %s was successfully added."%
                    (title, artist)),
            'result': 0,}))