Beispiel #1
0
def mock_album():
    songs = [
        Song(title="You Ain't Goin' Nowhere", track=1, album_id=1, s3_name="Los Angeles 2012-10-26-00.ogg", duration="5:20"),
        Song(title="To Ramona", track=2, album_id=1, s3_name="Los Angeles 2012-10-26-02.ogg", duration="5:01"),
        Song(title="Things Have Changed", track=3, album_id=1, s3_name="Los Angeles 2012-10-26-02.ogg", duration="5:20"),
        Song(title="Tangled Up In Blue", track=4, album_id=1, s3_name="Los Angeles 2012-10-26-03.ogg", duration="6:26"),
        Song(title="The Levee's Gonna Break", track=5, album_id=1, s3_name="Los Angeles 2012-10-26-04.ogg", duration="7:14"),
        Song(title="Make You Feel My Love", track=6, album_id=1, s3_name="Los Angeles 2012-10-26-05.ogg", duration="5:00"),
        Song(title="Cry A While", track=7, album_id=1, s3_name="Los Angeles 2012-10-26-06.ogg", duration="5:42"),
        Song(title="Desolation Row", track=8, album_id=1, s3_name="Los Angeles 2012-10-26-07.ogg", duration="9:08"),
        Song(title="Highway 61 Revisitied", track=9, album_id=1, s3_name="Los Angeles 2012-10-26-08.ogg", duration="7:00"),
        Song(title="Love Sick", track=10, album_id=1, s3_name="Los Angeles 2012-10-26-09.ogg", duration="5:32"),
        Song(title="Thunder on the Mountain", track=11, album_id=1, s3_name="Los Angeles 2012-10-26-10.ogg", duration="7:51"),
        Song(title="Ballad of A Thin Man", track=12, album_id=1, s3_name="Los Angeles 2012-10-26-11.ogg", duration="6:17"),
        Song(title="Like A Rolling Stone", track=13, album_id=1, s3_name="Los Angeles 2012-10-26-12.ogg", duration="6:32"),
        Song(title="All Along the Watchtower", track=14, album_id=1, s3_name="Los Angeles 2012-10-26-13.ogg", duration="6:18"),
        Song(title="Blowin' In the Wind", track=15, album_id=1, s3_name="Los Angeles 2012-10-26-14.ogg", duration="9:02"),
    ]
    album = Album(
        title="Hollywood Bowl 2012",
        date=datetime.date(year=2012, day=26, month=10),
        venue="Hollywood Bowl",
        city="Los Angeles",
        bucket="priestc-dylan",
        folder="hollywood_bowl_2012",
        encoding="ogg q5",
        source="Core Sound micros DPA 4060 with Sony PCM - M10>Hard Drive>Flac"
    )
    album.songs = songs
    return album
Beispiel #2
0
    def setUp(self):
        Album.query.delete()
        Artist.query.delete()

        artist = Artist(name="Nick Danger", logo_url="nickdanger.jpg")

        db.session.add(artist)
        db.session.commit()

        db_artist = Artist.query.filter_by(name="Nick Danger").first()
        artist_id = db_artist.id

        album_1 = Album(title="bigh", year="2019", artist_id=artist_id)

        album_2 = Album(title="An Apple a Day Doesn't Fall Far From the Tree",
                        year="2019",
                        artist_id=artist_id)

        db.session.add(album_1)
        db.session.add(album_2)
        db.session.commit()

        self.album_1 = album_1
        self.album_2 = album_2

        self.client = app.test_client()
def upload():
    # upload one or more pictures to the filesystem and register it/them in the database
    if not 'MyWebsite_user_id' in session.keys():
        return redirect('/')
    if not User.is_logged_in(session['MyWebsite_user_id'],session['login_session']):
        return redirect('/danger')    
    user=User.get_one(session['MyWebsite_user_id'])
    album_id=request.form['active_album']
    # f=request.files['new_pic']
    files=request.files.getlist('new_pic')
    for eachfile in files:
        filename=secure_filename(eachfile.filename)
        ALLOWED_EXTENSIONS = ('bmp','png', 'jpg', 'jpeg', 'gif')
        if '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS:
            print(filename)
            if path.exists('UserFiles/'+user.email+'/'+filename):
                # Album.add_pic(user,pic,album_id)
                filename=filename.rsplit('.',1)
                filename[0]=filename[0]+str(round(datetime.timestamp(datetime.now())))
                filename='.'.join(filename)

            # Save pic to the filesystem
            eachfile.save('UserFiles/'+user.email+'/'+filename)
            # Add pic to the pictures db
            pic=Picture.new(user.id,user.email+'/'+filename,filename)
            # Add pic to the active album
            Album.add_pic(user,pic,album_id)
            # Create thumbnail image using PIL
            im=Image.open('UserFiles/'+user.email+'/'+filename)
            im.thumbnail((100,100),Image.ANTIALIAS)
            im.save('UserFiles/thumbnails/'+user.email+'/'+filename)
            user.set_active_album(album_id)
        else:
            print('invalid file extension.')
    return redirect('/dashboard')
    def get_collections(self):
        if not self.library_goosed:
            print("The library is not goosed. Call goose_up_library().")
            return False

        if not self.collections:
            collections_directory = "{0}/src/collections".format(
                self.base_location)
            collection_files = os.scandir(collections_directory)
            self.collections = []

            for collection_file in collection_files:
                with open(collection_file.path) as cfp:
                    collection_json = json.load(cfp)
                    collection = Collection(title=collection_json["title"])

                    for album_path in collection_json["albums"]:
                        album = Album()
                        album_files = os.scandir(album_path)

                        for album_file in album_files:
                            track = Track.init_from_file(album_file.path)

                            if track:
                                album.tracks.append(track)

                                album.title = track.album_title
                                album.artist_name = track.artist_name

                        collection.albums.append(album)
                    self.collections.append(collection)

        return self.collections
Beispiel #5
0
class AlbumTest(TestCase):
    def setUp(self):
        self.user = User(username='******', email='*****@*****.**',
                         first_name='Sherlock', last_name="Holmes",
                         password='******')
        self.user.full_clean()
        self.user.save()
        self.photo = Photo(owner=self.user,
                           image='images/test.png',
                           name='test',
                           caption='testing')
        self.photo.clean()
        self.photo.save()
        self.tag = Tag(name='test tag', owner=self.user)
        self.tag.clean()
        self.tag.save()
        self.photo.tags.add(self.tag)
        self.album = Album(owner=self.user,
                           name='test album')
        self.album.clean()
        self.album.save()
        self.album.photos.add(self.photo)

    def test_id_creation(self):
        self.assertIsNotNone(self.album.id)

    def test_owner_entry(self):
        self.assertEqual(self.album.name, 'test album')

    def test_name_entry(self):
        self.assertEqual(self.photo.name, 'test')

    def test_album_to_photo_association(self):
        photos = Photo.objects.filter(album=self.album.id)
        self.assertEqual(photos[0].name, 'test')
Beispiel #6
0
    def stream(page) -> dict:
        pipeline = [{
            '$unwind': {
                'path': '$photos'
            }
        }, {
            '$sort': {
                'photos.created': -1
            }
        }, {
            '$skip': (page - 1) * Config.IMG_PER_PAGE
        }, {
            '$limit': Config.IMG_PER_PAGE
        }]
        photos = Album.objects(user=current_user.id).aggregate(*pipeline)

        # подсчет кол-ва страниц для пагинации
        pipeline = [{'$unwind': {'path': '$photos'}}, {'$count': 'total'}]
        photos_total = Album.objects(user=current_user.id).aggregate(*pipeline)
        pages_total = ceil(
            int(list(photos_total)[0].get('total', 1)) / Config.IMG_PER_PAGE)

        result = {
            'photos': list(photos),
            'pages_total': pages_total,
            'current_page': page,
        }
        return result
Beispiel #7
0
    def post(self):
        """POST handler for gallery albums.

        URL pattern: /albums
        POST data must contain album metadata: 'name'.

        Returns 201 CREATED with JSON data structure describing new album.
        Returns Content-type: application/json.
        Also returns Location header pointing to API URL for album details.
        
        Include 'wrapjson' parameter in POST to wrap returned JSON in
        a <textarea>. This also changes the returned Content-type to text/html.

        If request is poorly formatted returns 400 BAD REQUEST.

        Returns 401 UNAUTHORIZED to all calls if authorization fails.
        """
        try:
            data = dict(((str(k), v) for k, v in self.request.POST.items()))
            album = Album(album_id=config.ALBUM_ID_GENERATOR(),
                          **data)
        except:
            data = {}
            self.error(400)
        else:
            if not config.DEMO_MODE:
                album.put() 

            data = album.to_dict()
            self.response.headers['Location'] = data['url']
            self.response.set_status(201)
        
        write_json(self, data, wrapjson='wrapjson' in self.request.POST)
def reorder_album():
    if not 'MyWebsite_user_id' in session.keys():
        return redirect('/')
    if not User.is_logged_in(session['MyWebsite_user_id'],
                             session['login_session']):
        return redirect('/danger')
    # print("form:", request.form['json'])
    # print(request.form['album_id'])
    python_obj = json.loads(request.form['json'])
    # print("jSON:", json.loads(request.form['json']))
    # print(python_obj["album_id"])
    # print(python_obj["ordering"])
    # print("jSON:", request.get_json(force=True))
    album_order = Album_to_Pic()
    # This section to be replaced by album_order.set_order(python_obj)
    old_order = album_order.get_order(python_obj["album_id"])
    album = Album.query.get(python_obj["album_id"])
    for picture_id in old_order:
        if picture_id not in python_obj["ordering"]:
            picture = Picture.query.get(picture_id)
            album.pictures.remove(picture)
            album_order.commit()
    for rank, picture_id in enumerate(python_obj["ordering"], 1):
        # print(rank, picture_id)

        picture = Picture.query.get(picture_id)
        if picture not in album.pictures:
            Album.add_pic(user=None, picture=picture, album_id=album.id)

        record = album_order.get_one(python_obj["album_id"], picture_id)
        record.rank = rank
    album_order.commit()
    # print(album_order.get_order(python_obj["album_id"]))
    return redirect('/dashboard')
Beispiel #9
0
def add_to_db(audio_files):
    for audio_file in audio_files:
        audio_file_id3 = eyed3.load(audio_file)
        
        # If the artist, album or track doesn't exist in the database, create
        # table(s) for them.
        try:
            if not Artist.objects.filter(name=audio_file_id3.tag.artist).exists():
                artist = Artist(name=audio_file_id3.tag.artist)
                artist.save()
        
            if not Album.objects.filter(title=audio_file_id3.tag.album).exists():
                album = Album(title=audio_file_id3.tag.album, \
                              artist=artist)
                album.save()
            
            if not Track.objects.filter(title=audio_file_id3.tag.title).exists():
                track = Track(title=audio_file_id3.tag.title, \
                              album=album, \
                              artist=artist, \
                              fspath=audio_file, \
                              media_url=MEDIA_URL + audio_file.split(MEDIA_ROOT)[1])
                track.save()
                print 'Added to DB: ' + audio_file_id3.tag.title
        except Exception as e:
            print 'Error: ' + e
Beispiel #10
0
def album(request, album_id = None):
    if album_id is not None:
        album = request.db_session.query(Album).get(album_id)
    else:
        album = Album()

    if request.method == 'POST':
        if 'cancel' in request.POST:
            return redirect('index')
        form = AlbumForm(request.POST)
        if form.is_valid():
            # hydrate album object
            album.title = form.cleaned_data['title']
            album.artist = form.cleaned_data['artist']
            # save it
            request.db_session.add(album)
            request.db_session.commit()
            # show flash message to confirm update is OK
            messages.success(request, "Album saved successfully")
            # redirect to list of albums
            return redirect('index')
    elif album_id is not None:
        form = AlbumForm(album.__dict__)
    else:
        form = AlbumForm()

    return render(request, "album.html", {'form': form, 'album_id': album_id})
Beispiel #11
0
def add_album(request):
    """
	Add a new album by POST-ing a hashtag.
	"""
    album_form = AlbumForm(request.POST or None)
    errors = []

    if request.method == "POST":
        if album_form.is_valid():
            # sanitize data
            value = album_form.cleaned_data
            hashtag = value["hashtag"]
            print hashtag
            # get existing database albums
            user = User.objects.get(username=request.user)
            user_albums = Album.objects.get_user_posted_albums(user=user)
            print user_albums

            for album in user_albums:
                if album.name == hashtag:
                    errors.append("Album already exists.")
                    break

                    # add album to user albums if it doesn't exist already.
            if len(errors) == 0:
                new_album = Album(name=hashtag, user=user)
                new_album.save()
                print hashtag
                return HttpResponseRedirect(reverse("add_confirm", kwargs={"hashtag": hashtag}))
            else:
                context_instance = RequestContext(request, {"errors": errors})
                return render_to_response("add_album.html", context_instance)

    context_instance = RequestContext(request, {"album_form": album_form, "errors": errors})
    return render_to_response("add_album.html", context_instance)
Beispiel #12
0
def album_create(request):
    if request.method == 'POST':
        form = AlbumForm(request.POST)
        print 'submit album'
        if form.is_valid():  # coming from save button click
            q = Album()
            for each in form:
                if type(
                        each.field
                ) is forms.ModelChoiceField:  # get the value from 'select' (artist)
                    # value_needed = form.cleaned_data[each.name].pk ---> this is the option number
                    value_needed = form.cleaned_data[each.name]
                    a = Artist.objects.get(
                        name=value_needed)  # a is Artist instance
                    setattr(q, each.name, a)
                else:  # get the value from title or date
                    value_needed = form.cleaned_data[each.name]
                    setattr(q, each.name, value_needed)
            q.save()
            return redirect('index')  # you won't see 'form' in url
    else:  # if a GET (or any other method, or when getting to this page at first - we'll create a blank form
        form = AlbumForm()
        print 'Initial album_create page '
    return render(
        request,
        'mymusic/album_create.html',
        {
            'form':
            form  # render create album with empty form or with the form we already started to fill
        })
def reorder_album():
    if not 'MyWebsite_user_id' in session.keys():
        return redirect('/')
    if not User.is_logged_in(session['MyWebsite_user_id'],session['login_session']):
        return redirect('/danger')    
    python_obj = json.loads(request.form['json'])
    album_order=Album_to_Pic()
    # This section to be replaced by album_order.set_order(python_obj)
    old_order=album_order.get_order(python_obj["album_id"])
    album=Album.query.get(python_obj["album_id"])
    # Remove pictures from album if they are no longer in the list
    for picture_id in old_order:
        if picture_id not in python_obj["ordering"]:
            picture=Picture.query.get(picture_id)
            album.pictures.remove(picture)
            album_order.commit()
    # Rewrite all the rank values in the db table using the index value of the list
    for rank,picture_id in enumerate(python_obj["ordering"],1):
        # print(rank, picture_id)
        if picture_id.isnumeric():
            # if the list contains a picture that is not in the album, then add it
            picture=Picture.query.get(picture_id)
            if picture not in album.pictures:
                Album.add_pic(user=None,picture=picture,album_id=album.id)
            record=album_order.get_one(python_obj["album_id"],picture_id)
            record.rank=rank
    album_order.commit()
    # print(album_order.get_order(python_obj["album_id"]))
    return redirect('/dashboard')
Beispiel #14
0
def seed():
    Artist(name='The Beatles').insert()
    Artist(name='Pink Floyd').insert()

    Album(title='Abbey Road', year='1969', artist='The Beatles').insert()
    Album(title='Dark Side of the Moon', year='1973',
          artist='Pink Floyd').insert()
Beispiel #15
0
    def test_parse_album(self):

        response = '''{"response":[{"aid":"16178407","thumb_id":"96509883","owner_id":"6492","title":"qwerty",
            "description":"desc","created":"1298365200","updated":"1298365201","size":"3",
            "privacy":"3"},{"aid":"17071606","thumb_id":"98054577","owner_id":"-6492",
            "title":"","description":"","created":"1204576880","updated":"1229532461",
            "size":"3","privacy":"0"}]}
            '''
        instance = Album()
        owner = UserFactory.create(remote_id=6492)
        instance.parse(json.loads(response)['response'][0])
        instance.save()

        self.assertEqual(instance.remote_id, '6492_16178407')
        self.assertEqual(instance.thumb_id, 96509883)
        self.assertEqual(instance.owner, owner)
        self.assertEqual(instance.title, 'qwerty')
        self.assertEqual(instance.description, 'desc')
        self.assertEqual(instance.created, datetime(2011,2,22,9,0,0))
        self.assertEqual(instance.updated, datetime(2011,2,22,9,0,1))
        self.assertEqual(instance.size, 3)
        self.assertEqual(instance.privacy, 3)

        instance = Album()
        group = GroupFactory.create(remote_id=6492)
        instance.parse(json.loads(response)['response'][1])
        instance.save()

        self.assertEqual(instance.remote_id, '-6492_17071606')
        self.assertEqual(instance.group, group)
def create(request, albumTitle):
	is_auth = request.user.is_authenticated()
	if (is_auth):
		album = Album(title=request.albumTitle, description=none, userId=request.user)
		album.save()
		return render_to_response('create.html', {'is_auth':is_auth, 'user':request.user, 'title':albumTitle})
	else:
		return render_to_response('login.html',{'is_auth':is_auth})
def update_album_info():
    if not 'MyWebsite_user_id' in session.keys():
        return redirect('/')
    if not User.is_logged_in(session['MyWebsite_user_id'],session['login_session']):
        return redirect('/danger')    
    album_info=json.loads(request.form['json'])
    # print("Album Info",album_info)
    Album.update_info(album_info)
    return "Thank You"
Beispiel #18
0
def album(request, album_id, lang="en", name=""):
    if album_id == "0":
        query = request.GET.get("query", " ")
        album = Album(query=query)
        album.id = 0

    else:
        album = get_object_or_404(Album, id=album_id)
    try:
        page = int(request.GET.get("page", "1"))
    except ValueError:
        page = 1

    if request.GET.get("redirect", "") != "":
        if album_id == "0" and page == 1:
            goto = reverse("wilson:custom_album", kwargs={"lang": translation.get_language(), "query": query})
        elif album_id == "0" and page > 1:
            goto = reverse(
                "wilson:custom_album", kwargs={"lang": translation.get_language(), "page": page, "query": query}
            )
        elif page == 1:
            goto = reverse(
                "wilson:album",
                kwargs={"lang": translation.get_language(), "album_id": album_id, "name": slugify(album.title())},
            )
        else:
            goto = reverse(
                "wilson:album_page",
                kwargs={
                    "lang": translation.get_language(),
                    "album_id": album_id,
                    "name": slugify(album.title()),
                    "page": page,
                },
            )
        return HttpResponseRedirect(goto)

    paginator = Paginator(album.pictures_id_list(), 35, 7)

    # If page request (9999) is out of range, deliver last page of results.
    try:
        album_pics = paginator.page(page)
    except (EmptyPage, InvalidPage):
        album_pics = paginator.page(paginator.num_pages)
    album_pics.page_range = paginator.page_range
    return render_to_response(
        "wilson/album.html",
        {
            "album": album,
            "album_pics": album_pics,
            "menu": {
                "left": list(MenuPlaceholder.objects.filter(parent=None, position_h="l").order_by("position_v")),
                "right": list(MenuPlaceholder.objects.filter(parent=None, position_h="r").order_by("position_v")),
            },
        },
        context_instance=RequestContext(request),
    )
Beispiel #19
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 })
def delete_album():
    if not 'MyWebsite_user_id' in session.keys():
        return redirect('/')
    if not User.is_logged_in(session['MyWebsite_user_id'],session['login_session']):
        return redirect('/danger')
    print ("Delete Album: ",request.form['json'])
    deleting_album=json.loads(request.form['json'])
    album_id=deleting_album['album_id']
    Album.delete(album_id)
    return redirect ('/dashboard')
Beispiel #21
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 #22
0
def album_list_page(page=0):
    if page <= 0:
        abort(404)
    total = Album.select().count()
    total_page = int(math.ceil(total * 1.0 / config.ITEMS_PER_PAGE))
    album_list = Album.select().order_by(Album.id.desc()).paginate(
        page, config.ITEMS_PER_PAGE)
    return render_template("album_list.html",
                           page=page,
                           total_page=total_page,
                           album_list=album_list)
Beispiel #23
0
    def test_delete_album_success(self):
        new_album = Album(title=self.test_album['title'],
                          band_id=self.test_album['band_id'])
        new_album.insert()

        res = self.client().delete(
            '/albums/{}'.format(new_album.id),
            headers={"Authorization": "Bearer {}".format(self.manager)})
        data = json.loads(res.data)
        self.assertEqual(res.status_code, 200)
        self.assertTrue(data['success'])
def reorder_albums():
    if not 'MyWebsite_user_id' in session.keys():
        return redirect('/')
    if not User.is_logged_in(session['MyWebsite_user_id'],session['login_session']):
        return redirect('/danger')
    album_order=json.loads(request.form['json'])
    # print('Album order',album_order['ordering'])
    for rank,album_id in enumerate(album_order['ordering'],1):
        # print(album_id,rank)
        Album.set_rank(album_id,rank)
    return redirect('/dashboard')
Beispiel #25
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 #26
0
    def get(self):
    	user = users.get_current_user()
        if user is not None:
            nickname = users.get_current_user().nickname()
            logInOut = users.create_logout_url(self.request.uri)
            greeting = "Please Enter Your Picasa Album Address:"
            gd_client = gdata.photos.service.PhotosService()
            
            # try delete the user's album in the DB
            # pass if can't find.
            try:
                query = "Where owner = '%s'" % (nickname)
                allAlbum = Album.gql(query)
                db.delete(allAlbum)
            except:
                print "no album deleted for %s" % (nickname)
                pass

            # Grab user album list from Google Picasa and store in DB    
            try:
                albumList = gd_client.GetUserFeed(user=user)
                for album in albumList.entry:
                    newAlbum = Album()
                    newAlbum.owner = nickname
                    newAlbum.albumName = album.title.text
                    newAlbum.albumID = album.gphoto_id.text
                    newAlbum.albumPhoto = album.numphotos.text
                    newAlbum.put()
            except:
                print "%s album not added into DB" % (nickname)
                pass
                    # Grab all available albums for the user
            nickname = users.get_current_user().nickname()
            query = "Where owner = '%s'" % (nickname)
            time.sleep(1)
            allAlbum = Album.gql(query)
            print query
            print allAlbum.count()

            template_values = {
                    'user': user,
                    'logInOut': logInOut,
                    'greeting': greeting,
                    'albumInfo': allAlbum,
            }
            return render_template(self, 'index.html', template_values)
        
        else:
            logInOut = users.create_login_url(self.request.uri)
            greeting = "Please Login to continue."

            template_values = {
                'user': user,
                'logInOut': logInOut,
                'greeting': greeting,
            }
            return render_template(self, 'index.html', template_values)
        return render_template(self, 'index.html', template_values)
Beispiel #27
0
def create_album_view(request):
    owner = request.user
    if request.method == 'POST':
        form = CreateAlbumForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            album = Album(name=name, owner=owner)
            album.save()
            return HttpResponseRedirect('/main')
    else:
        form = CreateAlbumForm()
        return render(request, 'photorizer/create_album.html', {'form': form})
Beispiel #28
0
def createAlbum():
    form = CreateAlbumForm(prefix="createAlbum")
    if form.validate_on_submit():
        album = Album(name=form.name.data, 
                      description=form.description.data, 
                      creationDate=datetime.utcnow(), 
                      numImages=0, 
                      coverImageId=0)
        if form.passwordProtected.data and form.passwordHash.data:
            album.passwordHash = getAlbumPasswordHash(album.creationDate, form.passwordHash.data)
        db.session.add(album)
        db.session.commit()
    return admin(createAlbumForm=form)
Beispiel #29
0
    def post(self):
        if not self.has_permission:
            return
        user = self.current_user
        name = self.get_argument('name', None)
        name = strip_tags(name)
        if not name:
            return self.send_error_result(msg=u'没有填写专辑名')

        if len(name) >= 10:
            return self.send_error_result(msg=u'专辑名不能超过 10 个字符')

        album = Album(name=name, user_id=user.id).save()
        return self.send_success_result(data=album.to_dict())
Beispiel #30
0
def create_album(request):
    if not request.user.is_authenticated():
        return  redirect('/')
    if request.method=='GET':
        albums=Album.objects.all()
        print albums      
        maincat=MainCat.objects.all()
        nart,cart,rart,cm,tg=getthree()
        #日历
        today=today=datetime.datetime.now()
        s=calendar.HTMLCalendar(6)
        cals=list(s.itermonthdays2(today.year,today.month))
        tdarts=Article.objects.values('id','createtime').filter(createtime__year=today.year,createtime__month=today.month).order_by('createtime') #列表字典[{'createtime': datetime.datetime(2014, 4, 6, 4, 36, 32, 896000, tzinfo=<UTC>)},
        tdart=set([i['createtime'].day for i in tdarts])

        tmpq=Article.objects.exclude(createtime__year=today.year,createtime__month=today.month)
        premon=tmpq.filter(createtime__lt=today).order_by('-createtime')[:1]
        aftmon=tmpq.filter(createtime__gt=today).order_by('createtime')[:1]
           
        tt=[]
        for i in cals:
            tt.append(list(i))
        ttt=[]   
        for a in tt:
            for i in tdart:
                if a[0] == i:
                    a.append(1)
            if len(a)==2:
                a.append(0)    
            ttt.append(a)
        return render_to_response('create_album.html',locals(),context_instance=RequestContext(request))
    else:
        albumpath=request.POST['albumpath']
        albumname=request.POST['albumname']
        a=Album(album_name=albumname,album_path=albumpath)
        a.save()
        maincat=MainCat.objects.all()
        nart,cart,rart,cm,tg=getthree()
        #日历
        today=today=datetime.datetime.now()
        s=calendar.HTMLCalendar(6)
        cals=list(s.itermonthdays2(today.year,today.month))
        tdarts=Article.objects.values('id','createtime').filter(createtime__year=today.year,createtime__month=today.month).order_by('createtime') #列表字典[{'createtime': datetime.datetime(2014, 4, 6, 4, 36, 32, 896000, tzinfo=<UTC>)},
        tdart=set([i['createtime'].day for i in tdarts])

        tmpq=Article.objects.exclude(createtime__year=today.year,createtime__month=today.month)
        premon=tmpq.filter(createtime__lt=today).order_by('-createtime')[:1]
        aftmon=tmpq.filter(createtime__gt=today).order_by('createtime')[:1]
        tt=[]
        for i in cals:
            tt.append(list(i))
        ttt=[]   
        for a in tt:
            for i in tdart:
                if a[0] == i:
                    a.append(1)
            if len(a)==2:
                a.append(0)    
            ttt.append(a)
        return render_to_response('create_album.html',locals(),context_instance=RequestContext(request))
Beispiel #31
0
def create_new_album(request):
    """Create new album."""
    user = User.objects.get(pk=request.user.id)
    if request.method == 'POST':
        form = NewAlbumForm(request.POST)
        album = Album(title=form.data['title'],
                      description=form.data['description'])
        album.save()
        user.albums.add(album)
        return redirect('/images/library/')
    elif request.method == 'GET':
        new_album_form = NewAlbumForm()
        return render(request,
                      'newalbum.html',
                      context={'new_album_form': new_album_form})
 def test_create_album(self):
     """Create an album and verify that it appears as expected."""
     album = Album(
         title='An Album',
         description='A Description',
         author=self.u
     )
     album.full_clean()
     album.save()
     self.assertIsInstance(album, Album)
     self.assertIsInstance(album.date_created, datetime)
     self.assertIsInstance(album.date_modified, datetime)
     self.assertEqual(album.title, 'An Album')
     self.assertEqual(album.description, 'A Description')
     self.assertEqual(album.author, self.u)
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 #34
0
    def add_album(self, album_id=None, album_data=None):
        if album_id is None and album_data is None:
            raise Exception

        if album_data is None:
            album_data = self.sp.album(album_id)

        if album_id is None:
            album_id = album_data['id']

        try:
            cover_url = album_data['images'][0]['url']
        except IndexError:
            cover_url = None

        album = Album(spotify_id=album_id,
                      name=album_data['name'],
                      lead_artist_id=album_data['artists'][0]['id'],
                      cover_url=cover_url,
                      label=album_data.get('label'),
                      popularity=album_data.get('popularity'),
                      release_date=album_data.get('release_date'),
                      type=album_data.get('type'))

        self.db.add(album)

        return
Beispiel #35
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 #36
0
	def get(self):
		album = Album.objects(id=self.album_id, user=current_user.id).first()
		
		case = {
			'min': Config.MIN_PHOTOS_DIR,
			'max': Config.UPLOADS_DEFAULT_DEST,
			'full': Config.UPLOADS_DEFAULT_DEST
		}

		if album:
			file = os.path.join(case.get(self.filetype), str(current_user.id), album.slug, self.filename)
			
			# ресайз картинки
			if self.filetype == 'max':
				img = PilImage.open(file, mode='r')
				ratio = (Config.MAX_WIDTH / float(img.size[0]))
				height = int((float(img.size[1]) * float(ratio)))
				img = img.resize((Config.MAX_WIDTH, height), PIL.Image.ANTIALIAS)
				rgb_im = img.convert('RGB')
				
				img_response = io.BytesIO()
				rgb_im.save(img_response, 'JPEG')
				img_response.seek(0)
			else:
				img_response = file
		else:
			img_response = os.path.join(Config.BASE_DIR, 'static/images/forbidden.jpg')
		
		if self.filetype != 'full':
			as_attachment = False
		else:
			as_attachment = True
			
		return send_file(img_response, mimetype='image/jpeg', as_attachment=as_attachment)
Beispiel #37
0
    def delete(self, album_id, image_id, extension=None):
        """DELETE handler for gallery images.

        URL pattern: /albums/${album_id}/images/${image_id}
        
        If image exists, returns 200 OK. 
        If image doesn't exist, returns 404 NOT FOUND.

        Returns 401 UNAUTHORIZED to all calls if authorization fails.
        """
        q = Album.all().filter('album_id =', album_id)
        album = q.get()
        if not album:
            return self.error(404)

        q = Image.all().filter('album =', album).filter('image_id =', image_id)
        image = q.get()
        if not image:
            return self.error(404)
        
        if extension and extension != image.extension:
            return self.error(404)

        if not config.DEMO_MODE:
            image.delete()
Beispiel #38
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 #39
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
    )
    def setUp(self):
        Song.query.delete()
        Album.query.delete()
        Artist.query.delete()

        artist = Artist(name="Nick Danger", logo_url="nickdanger.jpg")

        db.session.add(artist)
        db.session.commit()

        db_artist = Artist.query.filter_by(name="Nick Danger").first()
        artist_id = db_artist.id

        album = Album(title="bigh", year=2019, artist_id=artist_id)

        db.session.add(album)
        db.session.commit()

        db_album = Album.query.filter_by(title="bigh").first()
        album_id = db_album.id

        song_1 = Song(title="Eessennet",
                      artist_id=artist_id,
                      album_id=album_id)

        song_2 = Song(title="bigh", artist_id=artist_id, album_id=album_id)

        db.session.add(song_1)
        db.session.add(song_2)
        db.session.commit()

        self.song_1 = song_1
        self.song_2 = song_2

        self.client = app.test_client()
Beispiel #41
0
    def get(self, album_id):
        user = get_user()
        album = Album.get_by_id(
            int(album_id),
            DEFAULT_DOMAIN_KEY
        )

        if album:
            upload_url = blobstore.create_upload_url('/album/%s/upload-photo' % album_id)

            photo_query = Photo.query(
                ancestor=album.key
            )

            comments_query = Comment.query(
                Comment.parent == album.key
            ).order(-Comment.date_created)

            template_values = {
                'user': user,
                'album': album,
                'photos': photo_query.fetch(None),
                'comments': comments_query.fetch(None),
                'upload_url': upload_url,
            }

            self.render_template('view_album.html', template_values)
        else:
            self.raise_error(404)
Beispiel #42
0
    def get(self, album_id, photo_id):
        album = Album.get_by_id(
            int(album_id),
            parent=DEFAULT_DOMAIN_KEY
        )
        photo = Photo.get_by_id(
            int(photo_id),
            parent=album.key
        )

        image_url = '%s/album/%s/photo/%s' % (
            self.request.host_url,
            album.key.integer_id(),
            photo.key.integer_id()
        )

        comments_query = Comment.query(
            Comment.parent == photo.key
        ).order(-Comment.date_created)

        comments = comments_query.fetch(None)

        template_values = {
            'image_url': image_url,
            'photo': photo,
            'album': album,
            'comments': comments,
        }

        self.render_template('view_photo.html', template_values)
Beispiel #43
0
    def get(self, hash, extension=None):
        q = Album.all().filter('hash =', hash)
        album = q.get()
        if album:
            if extension:
                return self.error(404)
            
            q = Image.all().filter('album =', album)
            return self.response.out.write(render_template('album.html', {
                'name': album.name,
                'images': q,
            }))

        q = Image.all().filter('hash =', hash)
        image = q.get()
        if image:
            if not extension:
                return self.response.out.write(render_template('image.html',
                    { 'image': image }))
            elif image.extension == extension:
                return write_image(self, image.image_data, extension)
            else:
                return self.error(404)
        
        return self.error(404)
Beispiel #44
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 #45
0
    def _tidal_album_to_album(self, tidal_album: dict) -> Album:
        year: Optional[str]
        if tidal_album.get("releaseDate"):
            year = tidal_album["releaseDate"].split("-")[0]
        else:
            year = None

        cover_url: Optional[str]
        if tidal_album.get("cover"):
            cover_url = TidalClient._get_cover_url(tidal_album["cover"])
        else:
            cover_url = None

        artists = [
            self._tidal_artist_to_artist(tidal_artist)
            for tidal_artist in tidal_album["artists"]
        ]

        _, best_available_quality = self._get_quality(tidal_album)

        return Album(
            id=tidal_album["id"],
            name=tidal_album["title"],
            artists=artists,
            year=year,
            cover_url=cover_url,
            best_available_quality=best_available_quality,
            explicit=tidal_album.get("explicit", False),
        )
Beispiel #46
0
    def delete(self) -> str:
        album = Album.objects(id=self.album_id, user=current_user.id)

        if album.first():
            album.update_one(
                __raw__={'$pull': {
                    'photos': {
                        'file': self.file
                    }
                }})
            album = album.first()

            path_max = os.path.join(Config.UPLOADS_DEFAULT_DEST,
                                    str(current_user.id), album.slug,
                                    self.file)
            path_min = os.path.join(Config.DEFAULT_MIN_DIR,
                                    str(current_user.id), album.slug,
                                    self.file)

            try:
                os.remove(path_max)
                os.remove(path_min)
            except FileNotFoundError:
                pass

            return album.slug
        else:
            return ''
Beispiel #47
0
def add_song():
    if not request.json:
        abort(Response('Request not in JSON format', 400))

    artist_name = request.json.get('artist_name', 'Unknown Artist')
    artist = Artist.query.filter_by(name=artist_name).first()
    if not artist:
        artist = Artist(name=artist_name)
        db.session.add(artist)
        g.redis.incr('artists')

    album_name = request.json.get('album_name', 'Unknown Album')
    album = Album.query.filter_by(name=album_name, artist_id=artist.id).first()
    if not album:
        album = Album(name=album_name,
                      year=request.json.get('year'),
                      artist=artist)
        db.session.add(album)
        g.redis.incr('albums')

    song = Song(track=request.json.get('track'),
                name=request.json.get('name'),
                album=album)

    db.session.add(song)
    db.session.commit()
    g.redis.incr('songs')
    return song.to_dict(), 200
Beispiel #48
0
def addAlbum():
    if 'username' not in login_session:
        return redirect(url_for('showLogin'))

    bands = session.query(Music_Band).all()
    if request.method == 'POST':
        if not request.form['album_name']:
            return "mising name"
        if not request.form['description']:
            return "missing description"
        if not request.form['band']:
            return "missing band"
        if not request.form['user_id']:
            return "Missing user_id"

        try:
            band = session.query(Music_Band).filter_by(
                name=request.form['band']).one()
            session.add(
                Album(name=request.form['album_name'],
                      description=request.form['description'],
                      music_band_id=band.id,
                      user_id=request.form['user_id']))
            session.commit()
            newAlbum = session.query(Album).filter_by(
                name=request.form['album_name']).one()
            flash("New Album was created")
            return redirect(url_for('homePage'))
        except:
            return "some error while adding the album"

    else:
        return render_template('addAlbum.html', bands=bands)
Beispiel #49
0
def create_album_submission():

    form = AlbumForm(request.form, meta={'csrf': False})
    if form.validate():  #validate that the form exist
        try:  #create a object type Album
            album = Album(artist_id=form.artist_id.data,
                          name=form.name.data,
                          year=form.year.data)
            db.session.add(album)
            db.session.commit()

            flash('Album ' + form.name.data + ' was successfully created!')
        except ValueError as e:
            print(e)
            error = True
            db.session.rollback()
            flash('An error occurred. Album ' + form.name.data +
                  ' could not be listed.')
            not_found_error(400)

        finally:
            print('final')
            db.session.close()

    else:
        message = []
        for field, err in form.errors.items():
            message.append(field + ' ' + '|'.join(err))
        flash('Errors ' + str(message))

    return render_template('pages/home.html')
Beispiel #50
0
def show_albums():
    if request.method == "GET":
        albums = Album.query.order_by(Album.title).all()
        serialized = [a.serialize() for a in albums]
        return jsonify(albums=serialized)
    else:
        data = request.get_json()

        if not data['title']:
            return jsonify({"msg": "Missing title parameter"}), 400
        if not data['year']:
            return jsonify({"msg": "Missing year parameter"}), 400
        if not data['artist']:
            return jsonify({"msg": "Missing artist parameter"}), 400

        title = data['title']
        year = data['year']
        artist = Artist.get_by_name(data['artist'])

        try:
            if not artist.id > 0:
                return jsonify({"msg": "Artist not found."}), 400

            artist_id = artist.id
            new_album = Album(title=title, year=year, artist_id=artist_id)

            db.session.add(new_album)
            db.session.commit()

            return redirect('/albums')
        except Exception as e:
            print(e)
            return jsonify(msg="Could not add album to database."), 400
Beispiel #51
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 #52
0
    def get(self, album_id, image_id, extension=None):
        """GET handler for GGB image metadata and files.

        URL pattern: /albums/${album_id}/images/${image_id}(${extension})

        If called without a file extension:
            If image exists, returns 200 OK with JSON image data structure.
            Returns Content-type: application/json.
            If image doesn't exist, returns 404 NOT FOUND.
        
        If called with a file extension:
            If image exists and has the matching extension, returns the image.
            Returned Content-type matches the image format.
            Otherwise returns 404 NOT FOUND.
       
        Returns 401 UNAUTHORIZED to all calls if authorization fails.
        """
        q = Album.all().filter('album_id =', album_id)
        album = q.get()
        if not album:
            return self.error(404)

        q = Image.all().filter('album =', album).filter('image_id =', image_id)
        image = q.get()
        if not image:
            return self.error(404)

        if not extension:
            data = image.to_dict()
            return write_json(self, image.to_dict())
        
        if extension != image.extension:
            return self.error(404)
   
        write_image(self, image.image_data, image.extension)
    def test_parse_album(self):

        owner = GroupFactory(remote_id=GROUP_ID)

        d = {u'count': 16, u'photo_320': u'http://cs619722.vk.me/u8704019/video/l_6369beb6.jpg', u'title': u'Coca-Cola Football',
             u'photo_160': u'http://cs619722.vk.me/u8704019/video/m_ef3493e1.jpg', u'id': 54387280, u'owner_id': -16297716}

        instance = Album()
        instance.parse(d)
        instance.save()

        self.assertEqual(instance.owner, owner)

        self.assertEqual(instance.pk, d['id'])
        self.assertEqual(instance.title, d['title'])
        self.assertEqual(instance.videos_count, 16)
        self.assertEqual(instance.photo_160, d['photo_160'])
Beispiel #54
0
    def get(self):
        user = users.get_current_user()
        albumName = self.request.get('name')
        nickname = users.get_current_user().nickname()
        
        # Clear all photo data stored in the db
        query = "Where owner = '%s'" % (user)
        allPhoto = Photo.gql(query)
        db.delete(allPhoto)
        # Get selected album with owner
        query = "Where albumName = '%s' AND owner ='%s'" % (albumName, nickname)
        selectedAlbum = Album.gql(query)
        # Pre-select if album is empty
        if selectedAlbum[0].albumPhoto == '0':
            template_values = {
                'user': user,
                'albumName': albumName,
            }
            render_template(self, 'photo.html', template_values)

        gd_client = gdata.photos.service.PhotosService()
        photoList = gd_client.GetFeed('/data/feed/api/user/%s/albumid/%s?kind=photo' % (user, selectedAlbum[0].albumID))

        # initialize Lock and Queue objects
        lock = Lock()
        photoQueue = Queue()

        for photo in photoList.entry:
            photoQueue.put(photo)

        # start consumer
        for i in range(numConsumer):
            worker = Thread(target=consumer, args=(photoQueue, selectedAlbum[0].albumPhoto, nickname, lock))
            worker.start()

#        for thread in joinable:
#            thread.join()
        photoQueue.join()

        # All consumer thread are finished, empty photoQueue
#        with stdout_mutex:
        print "All done"

        lock.acquire()
        time.sleep(1)
        query = "Where owner = '%s'" % (nickname)
        allPhoto = Photo.gql(query)
        print allPhoto.count()

        template_values = {
                'user': user,
                'allPhoto': allPhoto,
                'albumName': albumName,
        }
        lock.release()

        render_template(self, 'photo.html', template_values)
Beispiel #55
0
    def get(self):
        query = Album.query().order(-Album.date_created)

        albums = get_covered_albums(query, 3)

        template_values = {
            'albums': albums,
        }

        self.render_template('index.html', template_values)
Beispiel #56
0
    def get(self, album_id):
        album = Album.get_by_id(
            int(album_id),
            parent=DEFAULT_DOMAIN_KEY
        )

        if get_user().key == album.author:
            self.render_template('edit_album.html', {'album': album})
        else:
            self.raise_error(500)
Beispiel #57
0
 def createAlbums(self, albumMappings, remoteAlbums):
   """ Creates Albums from the data in albumMappings
     and finds the remote ids from a list of remoteAlbums
     based on the remote album name. """
   self.logger.info("Remote albums: " )
   remoteAlbumNames = [a["name"] for a in remoteAlbums]
   self.logger.info(remoteAlbumNames)
   albums = []
   for m in albumMappings:
     remoteName = m["remoteName"]
     localPath = path.join(self.albumsPath, m["localName"])
     album = Album(localPath, remoteName, 
         self.settings.backupDirName)
     for a in remoteAlbums:
       if remoteName == a["name"]:
         album.remoteId = a["id"]
         break
     albums.append(album)
   return albums