Beispiel #1
0
def album_detail_page(album_id=0, page=0):
    if page <= 0:
        abort(404)

    album = model_to_dict(Album.get(Album.id == album_id))
    if not album:
        abort(404)
    total_page = int(math.ceil(album["count"] * 1.0 / config.ITEMS_PER_PAGE))

    extra = entry_comments_api(entry_id=album_id)

    photos = list(
        Photo.select()
        .where(Photo.album_id == album_id)
        .order_by(Photo.pos)
        .paginate(page, config.ITEMS_PER_PAGE)
        .dicts()
    )
    return render_template(
        "album.html",
        album=album,
        page=page,
        total_page=total_page,
        photos=photos,
        **extra
    )
Beispiel #2
0
	def show_album(self, album_id=''):
		album=None
		try:
			album = Album.get(id=album_id)
		except DoesNotExist:
			print 'album does not exists'
		return self.render('admin/show_album.html', album=album)
Beispiel #3
0
	def add_photo(self, album_id=''):
		if request.method == 'POST':
			album = Album.get(id=album_id)
			photo = Photo()
			photo.album = album
			file = request.files['files']
			photo_title, size, photo_path, photo_url, thumb_url, thumb_path = self.gal_man.add_photo(album, file)
			result = []
			result.append({
				'name':photo_title,
				'size':size,
				'url':photo_url,
				'thumbnail_url':thumb_path,
				"delete_type":"POST",
			})
			photo.title = photo_title
			photo.photo_path = photo_path
			photo.thumb_path = thumb_path
			photo.photo_url = photo_url
			photo.thumb_url = thumb_url
			photo.size = size
			photo.save()
			return json.dumps(result)
		else:
			return 'response'
Beispiel #4
0
 def add_photo(self, album_id=''):
     if request.method == 'POST':
         album = Album.get(id=album_id)
         photo = Photo()
         photo.album = album
         file = request.files['files']
         photo_title, size, photo_path, photo_url, thumb_url, thumb_path = self.gal_man.add_photo(
             album, file)
         result = []
         result.append({
             'name': photo_title,
             'size': size,
             'url': photo_url,
             'thumbnail_url': thumb_path,
             "delete_type": "POST",
         })
         photo.title = photo_title
         photo.photo_path = photo_path
         photo.thumb_path = thumb_path
         photo.photo_url = photo_url
         photo.thumb_url = thumb_url
         photo.size = size
         photo.save()
         return json.dumps(result)
     else:
         return 'response'
Beispiel #5
0
 def show_album(self, album_id=''):
     album = None
     try:
         album = Album.get(id=album_id)
     except DoesNotExist:
         print 'album does not exists'
     return self.render('admin/show_album.html', album=album)
Beispiel #6
0
def album_detail_page(album_id=0, page=0):
    if page <= 0:
        abort(404)

    album = model_to_dict(Album.get(Album.id == album_id))
    if not album:
        abort(404)
    total_page = int(math.ceil(album['count'] * 1.0 / config.ITEMS_PER_PAGE))

    comments = list(Comment.select().where(
        Comment.entry_id == album_id).order_by(Comment.t).dicts())
    likes = list(Like.select().where(Like.entry_id == album_id).dicts())

    uids = list(
        set([c['authorId'] for c in comments] + [l['uid'] for l in likes]))
    users = dict([(u['uid'], {
        'name': u['name'],
        'headPic': u['headPic']
    }) for u in User.select().where(User.uid.in_(uids)).dicts()])

    photos = list(Photo.select().where(Photo.album_id == album_id).order_by(
        Photo.pos).paginate(page, config.ITEMS_PER_PAGE).dicts())
    return render_template("album.html",
                           album=album,
                           page=page,
                           total_page=total_page,
                           comments=comments,
                           likes=likes,
                           users=users,
                           photos=photos)
Beispiel #7
0
 def next(self, request, **kwargs):
   if request.GET['album'] and request.GET['track_num']:
     song = Song.get_song(int(request.GET['album']), int(request.GET['track_num']))
   if request.GET['album'] and not song:
     song = Album.get_similar_album(request.GET['album']).song_set[0]
   if not song:
     song = Album.get(0).song_set[0]
   bundle = self.build_bundle(obj=song, request=request)
   bundle = self.full_dehydrate(bundle)
   return self.create_response(request, { 'song': bundle })
Beispiel #8
0
    def sync_to(self, sync_cls):
        objs = []
        # traverse the dir
        for dirpath, folders, files in os.walk(self.folder):
            for fname in files:
                fpath = os.path.join(dirpath, fname)
                # get album, if have
                rel = os.path.relpath(dirpath, self.folder)
                if rel != '.':  # has sub dir
                    try:
                        album = Album.get(name=rel)
                    except Album.DoesNotExist:
                        album = Album.create(name=rel, folder=rel)
                else:
                    album = None
                # TODO: should a file extension filter here?
                md5 = hashlib.md5(open(fpath).read()).hexdigest()
                try:  # if file has been exists before
                    local = Local.get(md5=md5)
                    opath = local.path.encode('utf8')
                    if opath != fpath:
                        logging.debug('%s path change: %s --> %s' % (local, local.path, fpath))
                        # file was moved, rename filename or folder
                        local.title, ext = os.path.splitext(fname)
                        local.album = album
                        #local.fpath = fpath
                        local.last_modified = datetime.datetime.now()
                        local.save()
                        objs.append(local)  # objs: path modified.
                except Local.DoesNotExist:  # new file
                    try:
                        # file content modified
                        local = Local.get(path=fpath)
                        logging.debug('%s modified, path: %s' % (local, fpath))
                    except Local.DoesNotExist:
                        # brand new file
                        logging.debug('new file %s' % fpath)
                        local = Local()
                        local.title, ext = os.path.splitext(fname)
                        local.album = album
                        local.path = fpath
                    local.md5 = md5
                    local.last_modified = datetime.datetime.now()
                    local.save()
                    objs.append(local)

        # for those have not been upload
        for l in Local.select():
            sets = getattr(l, sync_cls.model.local.related_name)
            if sets.count() == 0 and l not in objs:
                objs.append(l)

        # pass objs that needs update to sync class
        logging.info('local: sync to %s, count %d' % (sync_cls, len(objs)))
        sync_cls.sync_from_local(objs)
Beispiel #9
0
 def next(self, request, **kwargs):
     if request.GET['album'] and request.GET['track_num']:
         song = Song.get_song(int(request.GET['album']),
                              int(request.GET['track_num']))
     if request.GET['album'] and not song:
         song = Album.get_similar_album(request.GET['album']).song_set[0]
     if not song:
         song = Album.get(0).song_set[0]
     bundle = self.build_bundle(obj=song, request=request)
     bundle = self.full_dehydrate(bundle)
     return self.create_response(request, {'song': bundle})
Beispiel #10
0
 def remove_album(self, album_id=''):
     try:
         album = Album.get(id=album_id)
         album.delete_instance(recursive=True)
         shutil.rmtree(album.album_path)
         shutil.rmtree(album.thumb_path)
         flash(u"Альбом %s видалено успішно" % album.title)
         return redirect(url_for('.index'))
     except DoesNotExist:
         print "album does not exist"
     flash(u"Такого альбому не існує")
     return redirect(url_for('.index'))
Beispiel #11
0
	def remove_album(self, album_id=''):
		try:
			album = Album.get(id=album_id)
			album.delete_instance(recursive=True)
			shutil.rmtree(album.album_path)
			shutil.rmtree(album.thumb_path)
			flash(u"Альбом %s видалено успішно" % album.title)
			return redirect(url_for('.index'))
		except DoesNotExist:
			print "album does not exist"
		flash(u"Такого альбому не існує")
		return redirect(url_for('.index'))
Beispiel #12
0
def cover_view(album_id):
    """ Return a cacheable cover for an album """
    album = Album.get(album_id)
    if not album or not album.cover: abort(404)

    filename = album.cover_filepath
    mimetype = 'image/png' if filename.endswith('png') else 'image/jpg'
    cache = 60 * 60 * 24 * 365  # 1 Year

    return send_file(filename,
                     mimetype=mimetype,
                     cache_timeout=cache,
                     conditional=True)
def addReleases(artist_id, update_artist = True):
  artist_record = Artist.get(id=artist_id)
  musicbrainz_artist = musicbrainz.getBestArtistMatch(artist_record.name)
  release_ids = []

  for release in musicbrainz_artist.getReleases():
    release_ids.append(utils.extractUuid(release.id))

  # These release results do not contain all the information, we must re-query for that info...
  for rid in release_ids:
    release = musicbrainz.getRelease(rid)

    if not release: continue

    release_group_id = utils.extractUuid(release.getReleaseGroup().id)

    try:
      release_group_tracked = Album.get(release_group_id=release_group_id)
    except peewee.DoesNotExist:
      release_group_tracked = None

    if release_group_tracked: continue

    release_record = Album.create(
        musicbrainz_id = rid,
        asin = release.getAsin(),
        release_group_id = release_group_id,
        artist_id = artist_id,
        name = release.getTitle(),
        type = release.getType(),
        released_on = release.getEarliestReleaseDate(),
        state = 'wanted')

    track_number = 1

    for track in release.getTracks():
      Track.create(
          album_id = release_record.id,
          number = track_number,
          title = track.getTitle(),
          length = track.getDuration(),
          state = 'wanted')

      track_number += 1

  # Rescan the Music Library after adding new releases to see if the user has 
  # them or not. Will not run if explicitly told not to by the caller.
  if(update_artist): ThreadPool.put(updateArtist, {'artist_id': artist_id})
Beispiel #14
0
 def put(self, image_id):
     image_id = int(image_id)
     image = Image.get(id=image_id)
     if not image:
         raise tornado.web.HTTPError(404)
     album_id = self.get_int('album_id', None)
     if not album_id:
         return self.send_error_result(msg=u'没有指定专辑哦')
     album = Album.get(id=album_id)
     if not album:
         return self.send_error_result(msg=u'专辑不存在')
     if album.user_id != self.current_user.id:
         return self.send_error_result(msg=u'此专辑不是您的专辑')
     if image.album_id != album_id:
         image.album_id = album_id
     return self.send_success_result()
Beispiel #15
0
 def put(self, image_id):
     image_id = int(image_id)
     image = Image.get(id=image_id)
     if not image:
         raise tornado.web.HTTPError(404)
     album_id = self.get_int('album_id', None)
     if not album_id:
         return self.send_error_result(msg=u'没有指定专辑哦')
     album = Album.get(id=album_id)
     if not album:
         return self.send_error_result(msg=u'专辑不存在')
     if album.user_id != self.current_user.id:
         return self.send_error_result(msg=u'此专辑不是您的专辑')
     if image.album_id != album_id:
         image.album_id = album_id
     return self.send_success_result()
    def album(self, id):
        album = Album.get(id=id)
        title = album.artist.name + " &emdash; " + album.name

        return self.serve_template("album.html", album=album, title=title)
Beispiel #17
0
 def get(self, album_id):
     album_id = int(album_id)
     album = Album.get(id=album_id)
     if not album:
         raise tornado.web.HTTPError(404)
     return self.render("album/index.html", album=album, page=self.page)
Beispiel #18
0
 def get(self, album_id):
     album_id = int(album_id)
     album = Album.get(id=album_id)
     if not album:
         raise tornado.web.HTTPError(404)
     return self.render("album/index.html", album=album, page=self.page)
Beispiel #19
0
class UploadHandler(BaseHandler):
    @orm.db_session
    @tornado.web.authenticated
    @require_permission
    def post(self):
        if not self.request.files or 'myimage' not in self.request.files:
            self.write({"status": "error", "message": "对不起,请选择图片"})
            return
        image_type_list = [
            'image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/bmp',
            'image/x-png'
        ]
        send_file = self.request.files['myimage'][0]
        if send_file['content_type'] not in image_type_list:
            self.write({
                "status":
                "error",
                "message":
                "对不起,仅支持 jpg, jpeg, bmp, gif, png\
                        格式的图片"
            })
            return
        if len(send_file['body']) > 100 * 1024 * 1024:
            self.write({"status": "error", "message": "对不起,请上传100M以下的图片"})
            return

        tmp_file = tempfile.NamedTemporaryFile(delete=True)
        tmp_file.write(send_file['body'])
        tmp_file.seek(0)
        try:
            img = Img.open(tmp_file.name)
        except IOError, error:
            logging.info(error)
            logging.info('+' * 30 + '\n')
            logging.info(self.request.headers)
            tmp_file.close()
            self.write({"status": "error", "message": "对不起,此文件不是图片"})
            return

        width = img.size[0]
        height = img.size[1]
        if width < 80 or height < 80 or width > 30000 or height > 30000:
            tmp_file.close()
            self.write({
                "status": "error",
                "message": "对不起,请上传长宽在80px~30000px之间的图片!"
            })
            return

        user = self.current_user
        suffix = img.format.lower()
        upload_path = generate_upload_path(suffix=suffix)

        img.save(upload_path, img.format or 'JPEG')
        tmp_file.close()

        path = '/%s' % get_relative_path(upload_path).lstrip('/')
        album_id = self.get_argument('album_id', '')
        if not album_id:
            album = user.default_album
        else:
            album = Album.get(id=album_id)
            if not (album and album.user_id != user.id):
                album = user.default_album
        image = Image(user_id=user.id,
                      album_id=album.id,
                      path=path,
                      width=width,
                      height=height).save()
        image.crop()
        return self.send_success_result(msg=u'上传成功', data=image.to_dict())
Beispiel #20
0
def album_view(album_id):
    """ Return information on a single album """
    album = Album.get(album_id)
    if not album: abort(404)
    return jsonify(album.serialize())