This paste brought to you by Pastebin. View Raw

  1. #!/usr/bin/env python2
  2. import random, sqlite3, sys
  3.  
  4. # Just a wrapper function to print line to standard output
  5. def printline(data = "", end = "\n"):
  6.     sys.stdout.write(data + end)
  7.     sys.stdout.flush()
  8.  
  9. # Just a wrapper function to keep reading line input until there's valid input
  10. def readline():
  11.     while True:
  12.         line = sys.stdin.readline().strip()
  13.         if len(line) > 0:
  14.             return line
  15.  
  16. # Populate database with nice videos suitable to play during a reunion dinner
  17. def init_db():
  18.     try:
  19.         with open("flag.txt", "r") as f:
  20.             flag = f.read().strip()
  21.     except:
  22.         flag = "you_need_to_connect_to_the_remote_service_to_get_the_flag"
  23.         printline("Unable to open flag.txt. Using dummy flag value: {flag}".format(flag=flag))
  24.  
  25.     # Use non-persistent database, so changes are not saved across connections
  26.     connection = sqlite3.connect(":memory:")
  27.     connection.row_factory = sqlite3.Row
  28.     global sql
  29.     sql = connection.cursor()
  30.  
  31.     sample_videos = [
  32.         {"url": "https://www.youtube.com/watch?v=LcL_lsWqEfs", "rating": 5, "topic": "Akira"},
  33.         {"url": "https://www.youtube.com/watch?v=r-5KzHDPCTM", "rating": 5, "topic": "Cow"},
  34.         {"url": "https://www.youtube.com/watch?v=3DkqMjfqqPc", "rating": 5, "topic": "Salamander"},
  35.         {"url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ", "rating": 4, "topic": "Rick"},
  36.         {"url": "https://www.youtube.com/watch?v=wZZ7oFKsKzY", "rating": 2, "topic": "Cat"},
  37.         {"url": "https://www.youtube.com/watch?v=5w8QEWA8wGM", "rating": 1, "topic": "Shark"},
  38.         {"url": "https://www.youtube.com/watch?v=-50NdPawLVY", "rating": 0, "topic": "Crab"}
  39.     ]
  40.  
  41.     sql.execute("CREATE TABLE flags (flag text)")
  42.     sql.execute("CREATE TABLE videos (topic text, rating int, url text)")
  43.     sql.execute("INSERT INTO flags VALUES ('{flag}')".format(flag=flag))
  44.  
  45.     for video in sample_videos:
  46.         sql.execute("INSERT INTO videos VALUES ('{topic}', '{rating}', '{url}')".format(topic=video["topic"], rating=video["rating"], url=video["url"]))
  47.  
  48. # Pretty-print all the videos fetched from query
  49. def print_videos(videos):
  50.     for id, video in enumerate(videos):
  51.         printline("#{id}: Topic: {topic}, Rating: {rating}, URL: {url}".format(id=id+1, topic=video["topic"], rating=video["rating"], url=video["url"]))
  52.     printline()
  53.  
  54. # Timer restriction is imposed on remote service, but removed here for local testing purposes
  55. def loop_forever():
  56.     options_msg = "\n".join([
  57.         "What do you want to do next?",
  58.         "1) Save a video",
  59.         "2) List all videos",
  60.         "3) Search video by topic",
  61.         "4) Search video by rating",
  62.         "5) Play random videos",
  63.         "6) Stop watching now",
  64.         "Enter option: "
  65.     ])
  66.  
  67.     options = {
  68.         "1": option_one,
  69.         "2": option_two,
  70.         "3": option_three,
  71.         "4": option_four,
  72.         "5": option_five,
  73.         "6": option_six,
  74.     }
  75.  
  76.     while True:
  77.         printline(options_msg, end="")
  78.         option = readline();
  79.         if option not in options.keys():
  80.             printline("Invalid option selected!")
  81.             continue
  82.  
  83.         # execute function corresponding to option chosen
  84.         try:
  85.             options[option]()
  86.         except sqlite3.OperationalError:
  87.             printline("An unexpected error occured while querying the database")
  88.  
  89. # Save a video
  90. def option_one():
  91.     printline("Enter topic: ", end="")
  92.     topic = readline().replace('"', "")
  93.     while True:
  94.         try:
  95.             printline("Enter rating: ", end="")
  96.             rating = int(readline())
  97.             break
  98.         except ValueError:
  99.             printline("Invalid rating! Rating must be an integer value!")
  100.     printline("Enter URL: ", end="")
  101.     url = readline().replace('"', "")
  102.     sql.execute('INSERT INTO videos VALUES ("{topic}", "{rating}", "{url}")'.format(topic=topic, url=url, rating=rating))
  103.     printline("Adding video - Topic: {topic}, Rating: {rating}, URL: {url}".format(topic=topic, rating=rating, url=url))
  104.  
  105. # List all videos
  106. def option_two():
  107.     videos = sql.execute("SELECT topic, rating, url FROM videos").fetchall()
  108.     printline()
  109.     printline("Listing all videos:")
  110.     print_videos(videos)
  111.  
  112. # Search video by topic
  113. def option_three():
  114.     printline("Enter topic: ", end="")
  115.     topic = readline().replace("'", "")
  116.     videos = sql.execute("SELECT topic, rating, url FROM videos WHERE topic = '{topic}' COLLATE NOCASE".format(topic=topic)).fetchall()
  117.     print_videos(videos)
  118.  
  119. # Search video by rating
  120. def option_four():
  121.     while True:
  122.         try:
  123.             printline("Enter rating: ", end="")
  124.             rating = int(readline())
  125.             break
  126.         except ValueError:
  127.             printline("Invalid rating! Rating must be an integer value!")
  128.     videos = sql.execute("SELECT topic, rating, url FROM videos WHERE rating = '{rating}' COLLATE NOCASE".format(rating=rating)).fetchall()
  129.     print_videos(videos)
  130.  
  131. # Play random videos
  132. def option_five():
  133.     topic = random.choice(list(sql.execute("SELECT DISTINCT topic FROM videos")))["topic"]
  134.     printline("Chosen to play random topic: {topic}".format(topic=topic))
  135.     videos = sql.execute("SELECT topic, rating, url FROM videos WHERE topic = '{topic}' COLLATE NOCASE".format(topic=topic)).fetchall()
  136.     print_videos(videos)
  137.  
  138. # Stop playing now
  139. def option_six():
  140.     printline("Hope you liked the videos and enjoy your reunion dinner!")
  141.     sys.exit(0)
  142.  
  143. def main():
  144.     init_db()
  145.     printline("It's time for reunion dinner, but you are hooked onto YouTube videos...")
  146.     loop_forever()
  147.  
  148. if __name__ == "__main__":
  149.     main()
  150.