Beispiel #1
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,}))