Example #1
0
    def songs():
        if request.method == "POST":
            title = str(request.data.get('title', ''))
            artist = str(request.data.get('artist', ''))
            if title and artist:
                song = Song(title=title, artist=artist)
                song.save()
                response = jsonify({
                    'id': song.id,
                    'title': song.title,
                    'date_created': song.date_created,
                    'date_modified': song.date_modified
                })
                response.status_code = 201
                return response
        else:
            # GET
            songs = Song.get_all()
            results = []

            for song in songs:
                obj = {
                    'id': song.id,
                    'title': song.title,
                    'artist': song.artist,
                    'date_created': song.date_created,
                    'date_modified': song.date_modified
                }
                results.append(obj)
            response = jsonify(results)
            response.status_code = 200
            return response
Example #2
0
def populate_db():
    a1 = Artist(name="Billy Joel", hometown="Long Island, NY")
    a2 = Artist(name="Tash Sultana", hometown="Melbourne, Australia")
    a3 = Artist(name="Mac Miller", hometown="Pittsburgh, PA")
    a4 = Artist(name="Red Hot Chili Peppers", hometown="Los Angeles, CA")

    db.session.add_all([a1, a2, a3, a4])
    db.session.commit()

    s1 = Song(name="Zanzibar", artist=a1)
    s2 = Song(name="Mystik", artist=a2)
    s3 = Song(name="Woods", artist=a3)
    s4 = Song(name="The Longest Wave", artist=a4)

    db.session.add_all([s1, s2, s3, s4])
    db.session.commit()

    print(s1)

    p1 = Playlist(name="Rock")
    p2 = Playlist(name="Slow Jams")

    stp1 = SongToPlaylist(song=s1, playlist=p1)
    stp2 = SongToPlaylist(song=s2, playlist=p1)
    stp3 = SongToPlaylist(song=s3, playlist=p2)
    stp4 = SongToPlaylist(song=s4, playlist=p2)

    db.session.add_all([p1, p2, stp1, stp2, stp3, stp4])
    db.session.commit()

    print("Artist - Woods", s3.artist.name)
    return "Database has been populated."
Example #3
0
    def add_song(self, **kwargs):
        artist_name = kwargs.get('title')[0]
        artist = Artist.objects(name=artist_name)

        song_name = kwargs.get('title')[-1]
        if not artist or Song.objects(name=song_name):
            self.add_artist(**kwargs)

        if self.is_song_exist(song_name):
            Log(type_added='song', name_added=song_name).save()
            return False

        self.download(kwargs.get('download_url'))
        size = kwargs.get('duration_size')
        size = ' '.join((size[2], size[3]))
        song = Song(artist=artist.get(),
                    name=song_name,
                    duration=kwargs.get('duration_size')[0],
                    download_url=kwargs.get('download_url'),
                    size=size)
        with open(TEMP_FILE, 'rb') as binary_file:
            song.audio_file.put(binary_file)
        shutil.rmtree(TEMP)
        if song:
            song.save()
            Log(type_added='song', name_added=song_name, added=True).save()
            return True

        Log(type_added='song', name_added=song_name).save()
        return False
Example #4
0
def add_song():
    url_image = None
    url_song = None
    if "image_url" in request.files:
        image = request.files["image_url"]
        image.filename = get_unique_filename(image.filename)
        upload = upload_file_to_s3(image)
        url_image = upload["url"]
    else:
        url_image = 'https://i.stack.imgur.com/l60Hf.png'
    if "song" in request.files:
        song_file = request.files["song"]
        song_file.filename = get_unique_filename(song_file.filename)
        upload = upload_file_to_s3(song_file)
        url_song = upload["url"]
        print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
        print(url_song)

    form = SongForm()
    form['csrf_token'].data = request.cookies['csrf_token']
    new_song = Song(
        artist_id=request.form['artist_id'],
        name=request.form['name'],
        description=request.form['description'],
        category=request.form['category'],
        album=request.form['album'],
        image_url=url_image,
        song=url_song,
        # public=request.form['public'],
    )

    db.session.add(new_song)
    db.session.commit()
    data = new_song.to_dict()
    return data
def new_song(request, id):
    if request.method == "GET":
        return render(request, "album_detail.html")
    elif request.method == "POST":
        album = Song(title=request.POST["title"],
                     seconds=int(request.POST["seconds"]),
                     album_id=id)
        album.save()
        return redirect(f"album/{id}", {"album": album})
Example #6
0
 def tearDownClass(self):
     # Delete Songs Data
     for each_record in range(self.records):
         record = each_record+1
         Song.objects(song_id=record).first().delete()
         Podcast.objects(podcast_id=record).first().delete()
         Audiobook.objects(audiobook_id=record).first().delete()
     # End-For
     self.app_context.pop()
Example #7
0
def load_playlist(fname):
    try:
        with open(fname + ".playlist") as f:
            playlist = Playlist()
            data = json.load(f)
            playlist.name = data['name']
            playlist.thumbnail = data['thumbnail']
            db.session.add(playlist)
            db.session.commit()
            for s in data['songs']:
                song_obj = Song.query.filter_by(
                    itunes_resource_id=s['itunes_resource_id']).first()
                if song_obj is None:
                    song_obj = Song()
                    song_obj.name = s['name']
                    song_obj.artist = s['artist']
                    song_obj.album = s['album']
                    song_obj.thumbnail_url = s['thumbnail_url']
                    song_obj.preview_url = s['preview_url']
                    song_obj.external_url = s['external_url']
                    song_obj.itunes_resource_id = s['itunes_resource_id']
                    db.session.add(song_obj)
                    db.session.commit()
                playlist.songs.append(song_obj)
                db.session.commit()
            return True
    except IOError as e:
        return False

    return False
Example #8
0
def skip_song():
	gyros = data.getGyroData()
	keys = gyros.keys()
	for key in keys:
		pos_orientation = (gyros[keys[0]] > 0)
		for coord in gyros[key]:
			if coord<0 and pos_orientation:
				pos_orientation = False
				return Song.query().first()
			elif coord>0 and !pos_orientation:
				pos_orientation = True
				return Song.query().first()
Example #9
0
 def convert(self):
     tune_log.log('converting')
     try:
         converted = Song(title=self.song.title,
                          audio=self.song.audio,
                          text=self.song.text,
                          conductor=self.song.conductor)
         tune_log.log('converting {}'.format(self.song.format()))
         converted.insert()
     except Exception as e:
         raise Tune_error('Test => Database error while converting.') from e
     return json.dumps({'success': self.__str__()})
Example #10
0
    def test_get_songs(self):
        '''
        Test case to check if all songs are returned by the get_songs function
        '''

        self.new_song.save_song()

        test_song = Song(name="Wierd Song Awkward Song")

        test_song.save_song()

        gotten_songs = Song.get_songs(3456789098765431234567890098765432123456787654323456787654323456787654323456787654334)

        self.assertTrue( len(gotten_songs) != len(Song.query.all()) )
Example #11
0
    def test_search_songs(self):
        '''
        Test case to check if all songs matching the provided song name are returned by the search_songs function
        '''

        self.new_song.save_song()

        test_song = Song(name="Wierd Song Awkward Song")

        test_song.save_song()

        gotten_songs = Song.search_songs("Wierd")

        self.assertFalse(len(gotten_songs) == len(Song.query.all()))
Example #12
0
 def __init__(self, *args):
     helper = 'unknown error with arguments: ' + str(args)
     if len(args) > 1:
         [name, audio, lyrics] = args
         try:
             song = Song(title=name, audio=audio, text=lyrics)
             song.insert()
         except Exception as e:
             raise Tune_error(' Initializing Object') from e
     elif len(args) > 3:
         [name, audio, lyrics, conductor] = args
         try:
             song = Song(title=name,
                         audio=audio,
                         text=lyrics,
                         conductor=conductor)
             song.insert()
         except Exception as e:
             raise Tune_error(' Initializing Object') from e
     else:
         try:
             song = Song.query.filter_by(id=args[0]).first()
             helper = 'no such song were found on our database '
         except Exception as e:
             raise Tune_error(
                 'Database error while looking for song.') from e
     try:
         self.song = song
         # db.session.close()
     except Exception as e:
         raise Tune_error(helper) from e
Example #13
0
def scanDirectory():
    app.logger.info('Scanning {}'.format(app.config['MUSIC_FOLDER']))

    # find new files
    new_paths = []
    for curdir, subdirs, files in os.walk(app.config['MUSIC_FOLDER']):
        for file_name in files:
            file_path = os.path.abspath(os.path.join(curdir, file_name))
            # app.logger.debug(file_path)

            if not Song.query.filter_by(abs_path=file_path).first():
                new_paths.append(file_path)

    if new_paths:
        for file_path in new_paths:
            if any([file_path.lower().endswith(ext)
                    for ext in ['mp3', 'm4a']]):
                song = Song(file_path)
                db.session.add(song)
            else:
                app.logger.warn(
                    'Did not add this file based on extension: {}'.format(
                        file_path))
            # app.logger.debug('Adding {}'.format(file_path))
        app.logger.info('Committing {} new files...'.format(len(new_paths)))
        db.session.commit()

    app.logger.info('{} songs added...'.format(len(new_paths)))
    return len(new_paths)
Example #14
0
def manageSongAdd():
    """
    新增歌曲
    """
    res = {}
    if request.method == "POST":
        songName = request.form.get("songName")
        singer = request.form.get("singer")
        style = request.form.get("style")
        fileURL = request.form.get("fileURL")

        song = Song.query.filter_by(songName=songName).first()
        if song:
            res["status"] = -2
            res["message"] = "歌曲已存在"
            return jsonify(res)
        # 写入到song表
        try:
            song = Song(
                songName = songName,    # 歌曲名称
                singer = singer,        # 歌手
                style = int(style),     # 歌曲类型
                fileURL = fileURL,      # 文件路径
            )
            db.session.add(song)
            db.session.commit()
            res["status"] = 1
            res["message"] = "歌曲新增成功"
        except Exception as e:
            res["status"] = -1
            res["message"] = "歌曲新增失败"
        return jsonify(res)
    return render_template("home/manageSongAdd.html")
Example #15
0
def add_song():
    content = request.json

    songUrl = content['url']
    songType = content['type']
    eMin = content['min']
    eMax = content['max']
    #songUrl = request.form['songUrl']
    #songType = request.form['songType']
    #eMin = request.form['min']
    #eMax = request.form['max']

    song = Song(url=songUrl)
    db.session.add(song)
    db.session.commit()

    if songType.lower() == 'temperature':
        envSong = SongTemperature(song_id=song.id,
                                  temp_min=eMin,
                                  temp_max=eMax)
    else:
        envSong = SongLight(song_id=song.id, light_min=eMin, light_max=eMax)

    db.session.add(envSong)
    db.session.commit()

    return make_response(redirect('/'))
Example #16
0
def getlist():
    if not acces_permission(current_user.role, 1):
        return redirect(url_for('index'))

    print("sono qui")

    if request.method == "POST":
        print("sono nel submit")
        #print(request.form["songs"])
        #print(request.files["songs"].read().decode("UTF-8"))
        v = request.files["songs"].read().decode("UTF-8").split("\n")
        print(v)
        for i in v:
            print(i[9].encode())
            j = i.split("|")
            print(j[0])
            song = Song(Name=j[0], Artist=j[1], Year=int(j[2]))
            db.session.add(song)
        db.session.commit()
    form = uploadFile()
    global LAST_SONG
    if (len(LIST_SELECTED_SONG) > 0):
        LAST_SONG = LIST_SELECTED_SONG[len(LIST_SELECTED_SONG) - 1]
    return render_template("dj.html",
                           songs=LIST_SELECTED_SONG,
                           length=len(LIST_SELECTED_SONG),
                           form=form)
Example #17
0
 def setUpClass(self):
     self.app = create_app('testing')
     self.app_context = self.app.app_context()
     self.app_context.push()
     self.client = self.app.test_client()
     # Create Songs Data
     for each_record in range(self.records):
         record = each_record+1
         uploaded = datetime.now()+timedelta(days=record)
         _song = {
             "song_id": record,
             "name": "Name-{}".format(record),
             "duration" : record,
             "uploaded": uploaded
         }
         _podcast = {
             "podcast_id": record,
             "name": "Name-{}".format(record),
             "duration": record,
             "uploaded": uploaded,
             "host":"Host-{}".format(record),
             "participants": ["Participant-{}".format(i) for i in range(record)]
         }                
         _audiobook = {
             "audiobook_id": record,
             "title": "Title-{}".format(record),
             "author": "Author-{}".format(record),
             "narrator": "Narrator-{}".format(record),
             "duration" : record,
             "uploaded": uploaded                
         }
         Song(**_song).save()
         Podcast(**_podcast).save()
         Audiobook(**_audiobook).save()
Example #18
0
def song():
    try:
        data = request.get_json()
        result = Song.query.filter_by(
            name_of_song=data["name_of_song"]).first()
        if result:
            if result.name_of_song:
                return jsonify({"message": "Song already exist"}), 409

        new_song = Song(name_of_song=data['name_of_song'],
                        duration_of_song=data['duration_of_song'],
                        uploaded_time=datetime.utcnow())
        db.session.add(new_song)
        db.session.commit()
        data = song_schema.dump(new_song)
        return jsonify({
            "Data": data,
            "message": "Song created successfully"
        }), 201

    except Exception as e:

        return jsonify({'error_msg': str(e)}), 400
    except InternalServerError as e:
        return jsonify({'error_msg': str(e)}), 500
Example #19
0
 def setUpClass(self):
     self.app = create_app('testing')
     self.app_context = self.app.app_context()
     self.app_context.push()
     self.client = self.app.test_client()
     from random import randint
     self.fmt = "%Y-%m-%d %H:%M:%S"
     self.record = randint(10,100)
     self.uploaded = (datetime.now()+timedelta(days=self.record)).strftime(self.fmt)
     self._song = {
         "song_id": self.record,
         "name": "Name-{}".format(self.record),
         "duration" : self.record,
         "uploaded": self.uploaded
     }
     self._podcast = {
         "podcast_id": self.record,
         "name": "Name-{}".format(self.record),
         "duration": self.record,
         "uploaded": self.uploaded,
         "host":"Host-{}".format(self.record),
         "participants": ["Participant-{}".format(i) for i in range(self.record%10)]
     }                
     self._audiobook = {
         "audiobook_id": self.record,
         "title": "Title-{}".format(self.record),
         "author": "Author-{}".format(self.record),
         "narrator": "Narrator-{}".format(self.record),
         "duration" : self.record,
         "uploaded": self.uploaded                
     }
     Song(**self._song).save()
     Podcast(**self._podcast).save()
     Audiobook(**self._audiobook).save()
Example #20
0
def upload():
    form = UploadForm()
    if form.validate_on_submit():
        f = form.upload.data
        filename = secure_filename(f.filename)
        f.save(os.path.join(app.instance_path, filename))
        if filename.endswith(".mp3"):
            sound = AudioSegment.from_mp3(
                os.path.join(app.instance_path, filename))
            filenamemp3 = filename.split('.')[0] + '.wav'
            sound.export(os.path.join(app.instance_path, filenamemp3),
                         format='wav')
            os.remove(os.path.join(app.instance_path, filename))
            filename = filenamemp3
        s = Song(filename=filename, user_id=int(current_user.id))
        db.session.add(s)

        df = getbeats(os.path.join(app.instance_path, filename))
        for row in df.itertuples():
            b = Beat(start=row[6],
                     end=row[7],
                     flatness=row[1],
                     rms=row[2],
                     specbw=row[3],
                     mfcc=row[4],
                     note=row[5],
                     n_group=row[9],
                     idx=row[8],
                     song_id=Song.query.filter_by(
                         user_id=int(current_user.id)).all()[-1].id)
            db.session.add(b)

        db.session.commit()
        return redirect(url_for('profile'))
    return render_template('upload.html', title='Upload New Track', form=form)
Example #21
0
def get_slides(song_list):
    all_songs = []
    for song_id in song_list:
        song = Song.query.filter_by(id=song_id).one()
        for verse in song.lyrics.split("\n\n"):
            slide = Song(title=song.title, lyrics=verse)
            all_songs.append(slide)
    return all_songs
Example #22
0
 def get_artist_by_song(song_name):
     song = Song.objects(name=song_name)
     if not song:
         return False
     artist = Artist.objects(_id=song.get().artist)
     if not artist:
         return False
     return artist
 def __createSongModel(self, url, metadata):
     song = Song()
     song.url = url
     id = metadata.get('id')
     song.media_id = f'{id}.mp3'
     song.title = metadata.get('title')
     song.alt_title = metadata.get('alt_title')
     song.artist = metadata.get('artist')
     song.album = metadata.get('album')
     return song
Example #24
0
 def get_artist_tracklist(artist_name):
     artist = Artist.objects(name=artist_name)
     if not artist:
         return False
     artist_id = artist.get().id
     tracklist = Song.objects(artist=artist_id)
     if not tracklist:
         raise False
     return tracklist
Example #25
0
def add_song():
    url_image = None
    url_song = None
    if "image" in request.files:
        image = request.files["image"]
        image.filename = get_unique_filename(image.filename)
        upload = upload_file_to_s3(image)
        url_image = upload["url"]
    if "audio" in request.files:
        song_file = request.files["audio"]
        # content = request.files["audio"].read()
        song_file.filename = get_unique_filename(song_file.filename)
        upload = upload_file_to_s3(song_file)
        url_song = upload["url"]
        print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
        print(url_song)
        # Convert song file to binary
        # audio_binary = convertToBinaryData(content)
        # print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
        # print(audio_binary)
        # Convert audio file into Numpy array
        # AudioNumpyArray = read(song_file, normalized=False)
        # numpyData = {"array": AudioNumpyArray}

        # # Serialization
        # numpyData = {"array": AudioNumpyArray}
        # # use dump() to write array into file
        # encodedNumpyData = json.dumps(numpyData, cls=NumpyArrayEncoder)
    form = UploadForm()
    form['csrf_token'].data = request.cookies['csrf_token']
    new_song = Song(
        user_id=request.form['id'],
        title=request.form['title'],
        description=request.form['description'],
        image_url=url_image,
        audio_file=url_song,
        artist=request.form['artist'],
        genre_id=1,
    )

    db.session.add(new_song)
    db.session.commit()
    data = new_song.to_dict()
    return data
Example #26
0
def search():
    songs, total = Song.search(g.search_form.q.data, 1,
                               100)  # page 1, 100 records per page
    if g.search_form.q.data == "":
        songs = Song.query.all()
        return render_template('song_table.html', songs=songs)
    if total > 0:
        return render_template('song_table.html', songs=songs)
    else:
        return render_template('song_table.html', songs=False)
Example #27
0
 def post(self):
     """
     Create the room
     """
     data = room_parser.parse_args()
     if 'song' not in request.files:
         return {
             "status": "error",
             'message': 'You have to upload at least one song'
         }, 400
     if Room.find_by_name(data['name']):
         return {
             "status": "error",
             'message': 'Room {} already exists'.format(data['name'])
         }, 400
     current_user = User.find_by_username(get_jwt_identity())
     song = request.files["song"]
     if song.filename == "":
         return {"status": "error", 'message': "Please select a file"}, 400
     elif not (song and allowed_file(song.filename)):
         return {
             "status": "error",
             'message': "Files must be in mp3 format."
         }, 400
     else:
         link = None
         try:
             room = Room(name=data['name'])
             db.session.add(room)
             song_name = secure_filename(song.filename)
             link = upload_file_to_s3(song, config.S3_BUCKET)
             db.session.flush()
             db.session.execute(joins.insert().values(
                 user_id=current_user.id, room_id=room.id))
             new_song = Song(name=song_name, link=link, room_id=room.id)
             room.current_song_id = new_song.id
             room.current_song = new_song
             room.owner_id = current_user.id
             db.session.add(new_song)
         except Exception as e:
             if link is not None:
                 s3.delete_object(Bucket=config.S3_BUCKET,
                                  Key=link[len(config.S3_LOCATION):])
             db.session.rollback()
             print(repr(e))
             return {
                 "status":
                 "error",
                 'message':
                 "Something wrong happen while creating room. Please try again."
             }, 400
         db.session.commit()
         result = room_schema.dump(room)
         return {"status": "success", "data": result}, 201
Example #28
0
 def tearDownClass(self):
     _song = Song.objects(song_id=self.record).first()
     _podcast = Podcast.objects(podcast_id=self.record).first()
     _audiobook = Audiobook.objects(audiobook_id=self.record).first()
     if _song:
         _song.delete()
     if _podcast:
         _podcast.delete()
     if _audiobook:
         _audiobook.delete()
     self.app_context.pop()
Example #29
0
def add_song():
    form = SongAddForm()
    if form.validate_on_submit():
        lyrics = form.lyrics.data
        lyrics = lyrics.replace("\r\n", "\n")
        song = Song(title=form.title.data, lyrics=lyrics)
        db.session.add(song)
        db.session.commit()
        flash('Congratulations, you have added a new song!',
              category='success')
        return redirect(url_for('add_song'))
    return render_template('add_song.html', title='Add a Song', form=form)
Example #30
0
def addtoList():
    s = request.args.get('s', 0)
    nomeSong, artista, anno = s.split(",")
    print(nomeSong)
    print(artista)
    print(anno)
    S = Song.query.filter_by(Name=nomeSong.replace(" ", ""),
                             Artist=artista,
                             Year=anno).first()
    LIST_SELECTED_SONG.append(
        Song(Name=nomeSong.strip(), Artist=artista.strip(), Year=anno))

    return jsonify(result=True)
Example #31
0
 def test_cifraclub(self):
     html = Song.get_lyrics_or_chords('https://www.cifraclub.com.br/jethro-tull/locomotive-breath/')
     self.assertIsNot(html, '')
Example #32
0
 def test_letras(self):
     html = Song.get_lyrics_or_chords('https://m.letras.mus.br/jethro-tull/19894/')
     self.assertIsNot(html, '')
Example #33
0
 def test_echords(self):
     html = Song.get_lyrics_or_chords('http://www.e-chords.com/chords/the-beatles/day-tripper')
     self.assertIsNot(html, '')
Example #34
0
 def test_lyricsfreak(self):
     html = Song.get_lyrics_or_chords('http://www.lyricsfreak.com/j/jethro+tull/locomotive+breath_20070951.html')
     self.assertIsNot(html, '')