Esempio n. 1
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(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.size, 3)
        self.assertEqual(instance.privacy, 3)
        self.assertIsNotNone(instance.created)
        self.assertIsNotNone(instance.updated)

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

        self.assertEqual(instance.remote_id, '-6492_17071606')
        self.assertEqual(instance.group, group)
Esempio n. 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()
Esempio n. 3
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()
Esempio n. 4
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)
Esempio n. 5
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')
Esempio n. 6
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
        })
Esempio n. 7
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
Esempio n. 8
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))
Esempio n. 9
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
Esempio n. 10
0
    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
    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()
Esempio n. 12
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
Esempio n. 13
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),
        )
Esempio n. 14
0
	def add(self) -> Album:
		album = Album()
		album.user = current_user.id
		album.name = self.name
		album.description = self.description
		album.save()
		
		return album
Esempio n. 15
0
 def test_get_albums_success(self):
     test_album = Album(title=self.test_album['title'],
                        band_id=self.test_album['band_id'])
     test_album.insert()
     res = self.client().get(
         '/albums',
         headers={"Authorization": "Bearer {}".format(self.manager)})
     self.assertEqual(res.status_code, 200)
     test_album.delete()
Esempio n. 16
0
def main():
    new_artist = Artist.create(name="Newsboys")
    new_album = Album(
        artist=new_artist,
        title="Album title",
        publisher="Sparrow",
        release_date=datetime.date(1988, 12, 1),
        media_type="CD",
    )
    new_album.save()

    # batch save

    albums = [{
        "artist": new_artist,
        "title": "Hell is for Wimps",
        "release_date": datetime.date(1990, 7, 31),
        "publisher": "Sparrow",
        "media_type": "CD"
    }, {
        "artist": new_artist,
        "title": "Love Liberty Disco",
        "release_date": datetime.date(1999, 11, 16),
        "publisher": "Sparrow",
        "media_type": "CD"
    }, {
        "artist": new_artist,
        "title": "Thrive",
        "release_date": datetime.date(2002, 3, 26),
        "publisher": "Sparrow",
        "media_type": "CD"
    }]

    for album in albums:
        a = Album(**album)
        a.save()

    bands = ["MXPX", "Kutless", "Thousand Foot Krutch"]
    for band in bands:
        artist = Artist(name=band)
        artist.save()

    print("[+] done")
Esempio n. 17
0
    def process_item(self, item, spider):
        if item.get('song_name') is None:
            # 分页完
            raise DropItem('ajax page over.')
        singer = db.query(
            Singer.pk).filter_by(face=item['singer_face']).first()
        if singer is None:
            singer = Singer(name=item['singer'], face=item['singer_face'])
            db.add(singer)

        album_name = item.get('album_name')
        if album_name is not None:
            cover = item.get('album_cover')
            album = db.query(Album.pk).filter_by(cover=cover).first()
            if album is None:
                album = Album(
                    name=album_name,
                    intro=item.get('album_intro'),
                    rdt=item['release_date'],
                    cover=cover)
                db.add(album)
        else:
            album = Empty()

        db.commit()

        lrc = item.get('lrc')
        song = db.query(Song).filter_by(
            name=item['song_name'], singer=singer.pk).first()
        if song is None:
            song = Song(
                name=item['song_name'],
                singer=singer.pk,
                album=album.pk,
                lrc=lrc)
            db.add(song)
            db.commit()
        elif None not in (lrc, song.lrc):
            song.lrc = lrc

        tag_objs = []
        for tag in item['tags']:
            t = db.query(Tag.pk).filter_by(name=tag).first()
            if t is None:
                t = Tag(name=tag)
                db.add(t)
            tag_objs.append(t)
        db.commit()

        for tag in tag_objs:
            db.merge(SongTag(sid=song.pk, tid=tag.pk))
        db.commit()

        return item
Esempio n. 18
0
File: tests.py Progetto: emzatos/idb
    def test_db_album(self):
        album = Album('album_name', 'genre', 'release', 'url', 'label', 1,
                      'uri')
        db.session.add(album)
        db.session.commit()
        album_result = Album.query.filter_by(name='album_name').first()
        assert (album_result is album)

        db.session.delete(album)
        db.session.commit()
        assert Album.query.filter_by(name='album_name').first() is None
Esempio n. 19
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'])
Esempio n. 20
0
def new_album():
    """
    Add a new album
    """
    form = AlbumForm(request.form)
    if request.method == 'POST' and form.validate():
        # save the album
        album = Album()
        save_changes(album, form, new=True)
        flash('Data inserted successfully!')
        return redirect('/')
    return render_template('new_album.html', form=form)
Esempio n. 21
0
def album_decoder(a):
    # assert (a['album_type'] == "album")
    # Should we do array of genres or just 1 genre...?
    try:
        genre = a['genres'][0]
    except:
        genre = "Unavailable"
    # genre = full['genres'] # IF WE DO A LIST OF GENRES

    # need to get image url from array of image objects
    album = Album(a['name'], genre, a['release_date'], a['images'][0]['url'],
                  a['label'], a['tracks']['total'], a['uri'])
    return album
Esempio n. 22
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)
Esempio n. 23
0
def get_or_create_album(artist, title, **kwargs):
    """ Return the object or make it if the artist/title pair doesn't exist.
    """
    instance = Album.query.filter_by(artist=artist, title=title).first()
    if instance:
        # FIXME: This should update album characteristics. Since it doesn't, cannot fix
        # a misspelled album title etc. without blowing away DB
        return instance
    else:
        instance = Album(artist, title, **kwargs)
        db.session.add(instance)
        db.session.flush()
        return instance
Esempio n. 24
0
def create():
    if not session.get('user'):
        return redirect(url_for('home'))
    form = CreateAlbumForm()
    if form.validate_on_submit():
        title = request.form.get('title')
        description = request.form.get('description')
        date = datetime.datetime.strptime(request.form.get('date'), '%Y-%m-%d')
        new_album = Album(title=title, description=description, date=date)
        db.session.add(new_album)
        db.session.commit()
        return redirect(url_for('home'))
    return render_template('create.html', form=form)
Esempio n. 25
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())
Esempio n. 26
0
File: main.py Progetto: vi-v/Lyre
def put_song_in_album(song):
    if song.album_hash() not in album_map:
        album = Album(song.album, song.artist)
        album.add(song)
        try:
            album.add(getattr(song, 'APIC:'))
        except AttributeError:
            pass
        album_map[song.album_hash()] = album
    else:
        album = album_map[song.album_hash()]
        album.add(song)

    put_album_in_artist(album)
Esempio n. 27
0
def createAlbum(name, url, band_name, art_url):
    with db.read_transaction:
        album = Album.nodes.get_or_none(name=name,
                                        url=url,
                                        band_name=band_name)
        album2 = Album.nodes.get_or_none(name=name, url=url)
        album3 = Album.nodes.get_or_none(url=url)
    if album == None and album3 == None and album2 == None:
        with db.write_transaction:
            album = Album(name=name,
                          url=url,
                          band_name=band_name,
                          art_url=art_url).save()
    return album if album != None else (album2 if album2 != None else album3)
Esempio n. 28
0
def new_gift():
    """
        Add a new product/gift
        """
    form = ProdForm(request.form)

    if request.method == 'POST' and form.validate():
        # save the album
        album = Album()
        save_changes(album, form, new=True)
        flash('Album created successfully!')
        return redirect('/')

    return render_template('new_gift.html', the_title='New Gift', form=form)
Esempio n. 29
0
def leftSideBar(request):
    sessObj = request.session['sessObj']
    sess = sessObj.sess
    cli = sessObj.cli
    #cli=request.session['client']
    sess.current_path = '/Photos'
    albums = [Album(count=getCount(sess, cli))]
    album_dict = {'Unorganized': Album(count=getCount(sess, cli))}
    if 'contents' in cli.metadata(sess.current_path):
        for f in cli.metadata(sess.current_path)['contents']:
            if f['is_dir']:
                albums.append(
                    Album(name=os.path.basename(f['path']),
                          path=f['path'],
                          count=getCount(sess, cli, f['path'])))
                album_dict[os.path.basename(f['path'])] = Album(
                    name=os.path.basename(f['path']),
                    path=f['path'],
                    count=getCount(sess, cli, f['path']))
    request.session['albums'] = album_dict
    out = render_to_string('leftSideBar.html', {'items': albums})
    respond = {'innerHTML': out}
    return HttpResponse(json.dumps(respond), content_type="application/json")
Esempio n. 30
0
def new_album():
    """
    Add a new album
    """
    form = AlbumForm(request.form)

    if request.method == 'POST':
        # save the album
        album = Album()
        save_changes(album, form, new=True)
        flash('Invoice created successfully!')
        return redirect('/invoice/invoice') 

    return render_template('new_album.html', form=form)