def generate_most_popular_song_question(): nickname = Common.common.get_value_from_cookie(request, 'nickname') # Make sure user is logged in, otherwise redirect to log in page. if nickname is None: return redirect('/log_in') connector = DbConnector() country_index = game_manager.answer_num % len(COUNTRIES) result = connector.get_all_results_for_query( QueryGenerator.get_four_ranked_songs_in_country(), (COUNTRIES[country_index], COUNTRIES[country_index], COUNTRIES[country_index], COUNTRIES[country_index])) while len( result ) == 0: # Just for safety, shouldn't happen unless DB is corrupted. country_index = (country_index + 1) % len(COUNTRIES) result = connector.get_all_results_for_query( QueryGenerator.get_four_ranked_songs_in_country(), (COUNTRIES[country_index], COUNTRIES[country_index], COUNTRIES[country_index], COUNTRIES[country_index])) connector.close() options = result[0] right_answer = options[0] answers = list(options) random.shuffle(answers) try: user_score = Common.common.get_value_from_cookie(request, 'score') if float(user_score) > 500 and nickname is not None: get_bonus = 'true' else: get_bonus = '' response = make_response( render_template( 'RankByCountryGame.html', question= "Which of the following songs is ranked the highest in " + COUNTRIES[country_index] + "?", option_1=answers[0], option_2=answers[1], option_3=answers[2], option_4=answers[3], game=game_manager.answer_num + 1, score=user_score, nickname=nickname, game_score=game_manager.score, bonus=get_bonus)) response.set_cookie('correctAnswerNum', str(answers.index(right_answer) + 1)) return game_manager.update_cookies_for_new_question(response) # In case there was a problem rendering the template, we will try replacing the question. # This is just for safety, and should not happen. except Exception as e: print "Error occurred with response - rank by country game - most popular song." print e.message generate_most_popular_song_question()
def get_relevant_user_scores(connector, num, nickname): if num == 1: users_scores = connector.get_all_results_for_query(QueryGenerator.get_score_and_total_points(), (nickname, nickname)) else: users_scores = connector.get_all_results_for_query(QueryGenerator.get_user_scores_for_game(), (num - 1, nickname, num - 1, nickname)) if len(users_scores) == 0 or users_scores[0][0] is None: users_scores = [(0, 0)] return users_scores
def generate_in_which_country_is_least_popular_question(): nickname = Common.common.get_value_from_cookie(request, 'nickname') # Make sure user is logged in, otherwise redirect to log in page. if nickname is None: return redirect('/log_in') random_countries = random.sample(COUNTRIES, 4) connector = DbConnector() result = connector.get_all_results_for_query( QueryGenerator.get_song_ranking_in_four_countries(), (random_countries[0], random_countries[1], random_countries[2], random_countries[3])) while len(result) == 0: random_countries = random.sample(COUNTRIES, 4) result = connector.get_all_results_for_query( QueryGenerator.get_song_ranking_in_four_countries(), (random_countries[0], random_countries[1], random_countries[2], random_countries[3])) connector.close() song_name = result[0][0] ranking = result[0][1:] right_answer = random_countries[ranking.index( max(ranking))] # The country with highest ranking. try: user_score = Common.common.get_value_from_cookie(request, 'score') if float(user_score) > 500 and nickname is not None: get_bonus = 'true' else: get_bonus = '' response = make_response( render_template('RankByCountryGame.html', question="In which country the song '" + song_name + "' is ranked the lowest?", option_1=random_countries[0], option_2=random_countries[1], option_3=random_countries[2], option_4=random_countries[3], game=game_manager.answer_num + 1, score=user_score, nickname=nickname, game_score=game_manager.score, bonus=get_bonus)) response.set_cookie('correctAnswerNum', str(random_countries.index(right_answer) + 1)) return game_manager.update_cookies_for_new_question(response) # In case there was a problem rendering the template, we will try replacing the question. # This is just for safety, and should not happen. except Exception as e: print "Error occurred with response - rank by country game - least popular." print e.message generate_in_which_country_is_least_popular_question()
def get_winning_artists_from_countries(connector): lst_of_artists = list() country = connector.get_all_results_for_query( QueryGenerator.get_n_random_countries(), (1, ))[0][0] # get 1 random country rows = connector.get_all_results_for_query( QueryGenerator.get_n_artists_from_country(), (country, 2)) # get 2 random artists from that country for row in rows: lst_of_artists.append((row[0])) return lst_of_artists
def get_bad_artists_from_countries(connector): lst_of_artists = list() for i in range(3): countries = connector.get_all_results_for_query( QueryGenerator.get_n_random_countries(), (2, )) # get 2 random countries for country in countries: country = country[0] lst_of_artists.append( connector.get_all_results_for_query( QueryGenerator.get_n_artists_from_country(), (country, 1))[0]) # get 1 random artist from country return lst_of_artists
def translate_artist_id_list_to_artist_name_list(connector, ids): lst_of_names = list() for artist_id in ids: lst_of_names.append( connector.get_one_result_for_query( QueryGenerator.get_artist_name_by_id(), (artist_id, ))[0]) return lst_of_names
def get_n_random_songs_from_artist(connector, n, artist_id): lst_of_songs = list() rows = connector.get_all_results_for_query( QueryGenerator.get_n_random_songs_by_artist(), (artist_id, n)) for row in rows: lst_of_songs.append((row[0], row[1])) return lst_of_songs
def get_n_random_covers_from_artist(connector, n, artist_id): lst_of_covers = list() rows = connector.get_all_results_for_query( QueryGenerator.get_n_album_covers_from_artist(), (artist_id, n)) for row in rows: lst_of_covers.append(row[0]) return lst_of_covers
def login(): global err err = '' if request.method == 'GET': return render_template('login.html') elif request.method == 'POST': # Get user input: nick = mdb.escape_string(request.form['nickname']) password = request.form['pwd'] if authenticate(nick, password): # Verify the address for nickname. query = QueryGenerator.get_score() connector = DbConnector() data = connector.get_one_result_for_query( query, (nick, nick)) # Get user's score. connector.close() if data[0] is None: # User has not played any game yet. score = 0 else: score = data[0] err = None response = make_response(redirect('/')) return update_cookies_logged_in(nick, score, response) else: err = 'Invalid nickname or password. Please try again!\n If you are new to Mr. Music, please sign up' return render_template('login.html', error=err)
def create_3_songs_game_page(): # validate user logged in. if not- send to login page nickname = Common.common.get_value_from_cookie(request, 'nickname') if nickname is None: return redirect('/log_in') connector = DbConnector() query = "SELECT word FROM frequent_words ORDER BY RAND() LIMIT 1" correct_answer = connector.get_one_result_for_query(query)[0] # get a frequent word randomly # get 3 song(titles) containging the word data = connector.get_all_results_for_query(QueryGenerator.get_songs_lyrics_contain(), (correct_answer, correct_answer)) while len(data) < 3: # if returned less than 3 titles correct_answer = connector.get_one_result_for_query(query)[0] # change word data = connector.get_all_results_for_query(QueryGenerator.get_songs_lyrics_contain(), (correct_answer, correct_answer)) # get 3 songs for new word songs = [tup[0] for tup in data] wrong_answers = get_wrong_answers(connector, correct_answer, songs, query) # get 3 words that do not appear in all 3 songs connector.close() answers = random.sample(wrong_answers + [correct_answer], 4) # randomize the order of the 4 options question_kind = "Which one of the words appear in all the following songs:" question = ", ".join(songs[0:3]) try: user_score = Common.common.get_value_from_cookie(request, 'score') if float(user_score) > 500 and nickname is not None: get_bonus = 'true' else: get_bonus = '' response = make_response(render_template('WordInSongGame.html', question=question, question_kind=question_kind, option_1=answers[0], option_2=answers[1], option_3=answers[2], option_4=answers[3], game=game_manager.answer_num + 1, score=user_score, nickname=nickname, game_score=game_manager.score, bonus=get_bonus)) # store correct answer in cookie for further use response.set_cookie('correctAnswerNum', str(answers.index(correct_answer) + 1)) return game_manager.update_cookies_for_new_question(response) except Exception as e: print "Error occurred with response" print e.message create_game_page()
def new_password(): # Validation - user is logged in. nickname = Common.common.get_value_from_cookie(request, 'nickname') if nickname is None: # if not logged in - send to home page. return redirect('/log_in') user_score = Common.common.get_value_from_cookie( request, 'score') # To show the user's score. global err err = '' nick_cookie = Common.common.get_value_from_cookie(request, 'nickname') user_score = Common.common.get_value_from_cookie(request, 'score') if float(user_score) > 500 and nickname is not None: get_bonus = 'true' else: get_bonus = '' if request.method == 'GET': return render_template('new_pass.html', score=user_score, nickname=nickname, bonus=get_bonus) elif request.method == 'POST': nick = mdb.escape_string(request.form['nickname']) if nick_cookie != nick: # Avoid user from changing another user's password. err = "You can only change your own password" return render_template('new_pass.html', error=err, score=user_score, nickname=nickname, bonus=get_bonus) # Display error. oldPwd = mdb.escape_string(request.form['oldPwd']) newPwd = mdb.escape_string(request.form['newPwd']) if oldPwd == newPwd: # Check that user is actually changing password. err = "Your new password is identical to your old one." return render_template('new_pass.html', error=err, score=user_score, nickname=nickname, bonus=get_bonus) # Display error. con = DbConnector() if authenticate(nick, oldPwd): # Check user gave his current password. hased_new = pbkdf2_sha256.hash(newPwd) # Hash new password. con.execute_query(QueryGenerator.update_password(), (hased_new, nick)) # Update password. con.close() err = "Congrats! You have a new password!" return render_template('new_pass.html', error=err, score=user_score, nickname=nickname, bonus=get_bonus) else: con.close() err = "Nickname or password are invalid. Please try again" return render_template('new_pass.html', error=err, score=user_score, nickname=nickname, bonus=get_bonus)
def update_cookie_with_new_score(nickname, response): connector = DbConnector() new_score_row = connector.get_one_result_for_query( QueryGenerator.get_score(), (nickname, nickname)) new_score = str(new_score_row[0]) connector.close() response.set_cookie('score', new_score) return response
def calc_answers(connector, answer_artist_id): # find 3 artist that didn't sing with answer_artist_id rows = connector.get_all_results_for_query(QueryGenerator.get_duets_answers_query(), ('% & %', '% feat%', '% and %', answer_artist_id, answer_artist_id)) res = [] for row in rows: res.append(row[0]) return res
def is_valid_sign_up_input(nick, email, password): global err if not nick.isalnum(): err = "Nickname can contain only numbers and letters" return False if not password.isalnum(): err = "Password can contain only numbers and letters" return False connector = DbConnector() data = connector.get_one_result_for_query(QueryGenerator.get_user_data(), (nick, )) if data is not None: err = "This nickname is already taken. Please choose a different one" return False data = connector.get_one_result_for_query(QueryGenerator.get_email(), (email, )) if data is not None: err = "This email is already in use" return False connector.close() return True
def authenticate(nick, password): if not (is_valid_login_input(nick, password)): return False connector = DbConnector() data = connector.get_one_result_for_query(QueryGenerator.get_user_data(), (nick, )) connector.close() if data is None: return False else: if pbkdf2_sha256.verify( password, data[2]): # Compares to the hash stored in the users table. return True return False
def get_wrong_answers(connector, correct_answer, songs, query): res = [] # keep the words here while len(res) < 3: answer = connector.get_one_result_for_query(query)[0] # pick a word randomly from frequent_words table while answer == correct_answer or answer in res: # in case we've randomly picked the word in all songs we've found before answer = connector.get_one_result_for_query(query)[0] for song in songs: # every answer should have at least one song it does not appear in data = connector.get_all_results_for_query(QueryGenerator.get_songs_lyrics_not_contain(), (answer, answer, song)) if len(data) > 0: # if we get back the name of the song, answer is not in it res.append(answer) break else: continue return res
def get_all_songs(connector): lst_of_artists = get_list_of_results(connector, QueryGenerator.get_n_random_artists(), 7) # get a list of 7 random artists winner_artist = random.randint(0, 6) lst_of_bad_songs = list() winner_songs = list() for i in range(7): if i == winner_artist: winner_songs = get_n_random_songs_from_artist( connector, 2, lst_of_artists[i]) # get 2 random songs from one artist else: lst_of_bad_songs.append( get_n_random_songs_from_artist( connector, 1, lst_of_artists[i])) # get 1 random song from artist return winner_songs, lst_of_bad_songs
def get_all_covers(connector): lst_of_artists = get_list_of_results( connector, QueryGenerator.get_n_random_artists_from_possible_artists(), 7) # get 7 random artists that have more than one real album cover winner_artist = random.randint(0, 6) bad_covers = list() winner_covers = list() for i in range(7): if i == winner_artist: winner_covers = get_n_random_covers_from_artist( connector, 2, lst_of_artists[i]) # get 2 random album covers from artist else: bad_covers.append( get_n_random_covers_from_artist( connector, 1, lst_of_artists[i])) # get 1 random album cover from artist return winner_covers, bad_covers
def create_words_in_song_game_page(): nickname = Common.common.get_value_from_cookie(request, 'nickname') if nickname is None: return redirect('/log_in') connector = DbConnector() song_row = connector.get_one_result_for_query(QueryGenerator.get_word_in_song_question_query()) lyrics = song_row[2] popular_words = get_5_popular_words(lyrics) right_answer = popular_words[0] wrong_answers = popular_words[1:4] connector.close() answers = random.sample(wrong_answers + [right_answer], 4) question_kind = "Which of the following words appears the most in the song? " try: user_score = Common.common.get_value_from_cookie(request, 'score') if float(user_score) > 500 and nickname is not None: get_bonus = 'true' else: get_bonus = '' response = make_response(render_template('WordInSongGame.html', question=song_row[1], question_kind=question_kind, option_1=answers[0], option_2=answers[1], option_3=answers[2], option_4=answers[3], game=game_manager.answer_num + 1, score=user_score, nickname=nickname, game_score=game_manager.score, bonus=get_bonus)) response.set_cookie('correctAnswerNum', str(answers.index(right_answer) + 1)) return game_manager.update_cookies_for_new_question(response) except Exception as e: print "Error occurred with response" print e.message create_words_in_song_game_page()
def create_game_page(): nickname = Common.common.get_value_from_cookie(request, 'nickname') if nickname is None: return redirect('/log_in') connector = DbConnector() # find two artist that sang together answer_row = connector.get_one_result_for_query(QueryGenerator.get_duets_question_query()) right_answer = answer_row[2] # seconed artist name wrong_answers = calc_answers(connector, answer_row[0]) # first artist id connector.close() answers = random.sample(wrong_answers + [right_answer], 4) try: user_score = Common.common.get_value_from_cookie(request, 'score') if float(user_score) > 500 and nickname is not None: get_bonus = 'true' else: get_bonus = '' response = make_response(render_template('DuetsGame.html', question=answer_row[1], # first artist name option_1=answers[0], option_2=answers[1], option_3=answers[2], option_4=answers[3], game=game_manager.answer_num + 1, score=user_score, nickname=nickname, game_score=game_manager.score, bonus=get_bonus)) response.set_cookie('correctAnswerNum', str(answers.index(right_answer) + 1)) return game_manager.update_cookies_for_new_question(response) except Exception as e: print "Error occurred with response" print e.message create_game_page()
def signup(): global err err = '' if request.method == 'GET': return render_template('signup.html', error=err) elif request.method == 'POST': # Get user input: nick = mdb.escape_string(request.form['nickname']) password = request.form[ 'pwd'] # No need to sanitize - going through hash. email = mdb.escape_string(str(request.form['email'])) if is_valid_sign_up_input(nick, email, password): # Validate input, hash_password = pbkdf2_sha256.hash(password) # Hash the password, connector = DbConnector() connector.execute_query( QueryGenerator.sign_in_user(), (nick, email, hash_password)) # Insert new user to users table. connector.close() err = "You have signed up successfully! Let's Play!" response = make_response(redirect('/')) return update_cookies_logged_in(nick, 0, response) return render_template('signup.html', error=err)
def update_game_result(self, nickname): connector = DbConnector() connector.execute_query(QueryGenerator.create_score_update_query(), (nickname, time.strftime('%Y-%m-%d %H:%M:%S'), self.game_id, self.score)) connector.close()
def create_game_page(): # Avoiding UnicodeDecodeError reload(sys) sys.setdefaultencoding('UTF8') nickname = Common.common.get_value_from_cookie(request, 'nickname') # Make sure the user is logon before accessing this page if nickname is None: return redirect('/log_in') connector = DbConnector() rand_song_row = connector.get_one_result_for_query(QueryGenerator.get_release_order_question_query()) rand_song_name = rand_song_row[3] album_id = rand_song_row[0] release_month = rand_song_row[1] release_year = rand_song_row[2] answers_rows = connector.get_all_results_for_query( QueryGenerator.get_release_order_answers_query(), (release_year, release_month, release_year, release_month, release_year, release_month, release_year, rand_song_name, album_id)) connector.close() # order the 4 songs by the release date (merge rand_song_name with answers_rows) global ordered_answers ordered_answers = [] inserted_rand_song_row = False for i in range(3): if int(answers_rows[i][0]) > 0 and not inserted_rand_song_row: ordered_answers.append(rand_song_name) inserted_rand_song_row = True ordered_answers.append(answers_rows[i][1]) if not inserted_rand_song_row: ordered_answers.append(rand_song_name) rand_order_answers = random.sample(ordered_answers, 4) try: user_score = Common.common.get_value_from_cookie(request, 'score') if float(user_score) > 500 and nickname is not None: get_bonus = 'true' else: get_bonus = '' response = make_response(render_template('ReleaseOrderGame.html', game=game_manager.answer_num + 1, score=user_score, nickname=nickname, game_score=game_manager.score, question='"' + '", "'.join(rand_order_answers) + '"', option_1=rand_order_answers[0], option_2=rand_order_answers[1], option_3=rand_order_answers[2], option_4=rand_order_answers[3], bonus=get_bonus)) return game_manager.update_cookies_for_new_question(response) except Exception as e: # in case there was a problem with rendering question page, we will try again print "Error occurred with response - release order game" print e.message create_game_page()
def get_relevant_result(connector, num): if num == 1: return connector.get_all_results_for_query(QueryGenerator.get_top_ten_query()) else: return connector.get_all_results_for_query(QueryGenerator.get_top_ten_query_for_game(), (num - 1, num - 1))