reward_handlers.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. import os
  2. from flask import current_app
  3. from sqlite3 import Error
  4. from ownchatbot.user_handlers import spend_points
  5. import subprocess
  6. import json
  7. def check_vote(db, vote_name, user_id): # Check if user has already voted on this vote
  8. try:
  9. cursor = db.execute(
  10. "SELECT voters FROM votes WHERE name = ?",
  11. (vote_name,)
  12. )
  13. row = cursor.fetchone()
  14. if row is None:
  15. current_app.logger.warning(f'\"{vote_name}\" not found in vote table.')
  16. return False
  17. if row[0] == user_id:
  18. return True
  19. except Error as cverror:
  20. current_app.logger.error(f'Couldn\'t check if {user_id} already voted on \"{vote_name}\": {cverror.args[0]}')
  21. return False
  22. def add_to_vote(db, vote_name, user_id): # Add a count to a vote
  23. try: # Check if vote exists in the database
  24. cursor = db.execute(
  25. "SELECT count FROM votes WHERE name = ?",
  26. (vote_name,)
  27. )
  28. vote = cursor.fetchone()
  29. if vote is None:
  30. current_app.logger.warning(f'{vote_name} not found in vote table.')
  31. return False
  32. else: # If vote exists, add a count
  33. db.execute(
  34. "UPDATE votes SET count = count + 1, voters = ? WHERE name = ?",
  35. (user_id, vote_name,)
  36. )
  37. db.commit()
  38. return True
  39. except Error as terror:
  40. current_app.logger.error(f'Couldn\'t add to \"{vote_name}\" vote: {terror.args[0]}')
  41. return False
  42. def add_to_queue(db, user_id, reward_name): # Add a reward to the queue
  43. try:
  44. db.execute(
  45. "INSERT INTO reward_queue(reward, user_id, fulfilled, refunded) VALUES(?, ?, ?, ?)",
  46. (reward_name, user_id, 0, 0)
  47. )
  48. db.commit()
  49. return True
  50. except Error as qerror:
  51. current_app.logger.error(f'Couldn\'t add to reward \"{reward_name}\" for {user_id} queue: {qerror.args[0]}')
  52. return False
  53. def run_script(reward_name, script_cmd): # Run a script form a special reward
  54. try:
  55. subprocess.check_call(script_cmd, shell=True)
  56. except Exception as scerror:
  57. current_app.logger.error(f'Couldn\'t run script \"{reward_name}\": {scerror.args[0]}')
  58. return False
  59. return True
  60. def add_to_goal(db, user_id, reward_name, points_contributed): # Add a contribution to a goal
  61. try:
  62. cursor = db.execute(
  63. "SELECT progress, target FROM goals WHERE name = ?",
  64. (reward_name,)
  65. )
  66. row = cursor.fetchone()
  67. if row is None:
  68. current_app.logger.warning(f'\"{reward_name}\" not found in goal table.')
  69. return False
  70. progress, target = row
  71. if progress + points_contributed > target:
  72. points_contributed = target - progress
  73. if points_contributed < 0:
  74. points_contributed = 0
  75. if spend_points(db, user_id, points_contributed):
  76. cursor = db.execute(
  77. "UPDATE goals SET progress = ? WHERE name = ?",
  78. (progress + points_contributed, reward_name)
  79. )
  80. db.commit()
  81. return True
  82. except Error as gerror:
  83. current_app.logger.error(f'Couldn\'t update goal: {gerror.args[0]}')
  84. return False
  85. def goal_left(db, reward_name):
  86. try:
  87. cursor = db.execute(
  88. "SELECT progress, target FROM goals WHERE name = ?",
  89. (reward_name,)
  90. )
  91. row = cursor.fetchone()
  92. if row is None:
  93. current_app.logger.warning(f'{reward_name} not found in Goal table.')
  94. else:
  95. progress, target = row
  96. left = target - progress
  97. return left
  98. except Error as glerror:
  99. current_app.logger.error(f'Couldn\'t check progress for \"{reward_name}\" goal: {glerror.args[0]}')
  100. def goal_reached(db, reward_name): # Set a goal as completed
  101. try:
  102. cursor = db.execute(
  103. "SELECT complete FROM goals WHERE name = ?",
  104. (reward_name,)
  105. )
  106. row = cursor.fetchone()
  107. if row is None:
  108. current_app.logger.warning(f'{reward_name} not found in goal table.')
  109. else:
  110. return row[0]
  111. except Error as grerror:
  112. current_app.logger.error(f'Couldn\'t check if goal was met: {grerror.args[0]}')
  113. def was_goal_reached(db, reward_name): # Check if a goal was reached
  114. try:
  115. cursor = db.execute(
  116. "SELECT progress, target FROM goals WHERE name = ?",
  117. (reward_name,)
  118. )
  119. row = cursor.fetchone()
  120. if row is None:
  121. current_app.logger.warning(f'{reward_name} not found in Goal table.')
  122. else:
  123. progress, target = row
  124. if progress == target:
  125. cursor = db.execute(
  126. "UPDATE goals SET complete = TRUE WHERE name = ?",
  127. (reward_name,)
  128. )
  129. db.commit()
  130. return True
  131. return False
  132. except Error as wgrerror:
  133. current_app.logger.error(f'Couldn\'t mark goal met: {wgrerror.args[0]}')
  134. return False
  135. def all_votes(db): # Get all the votes
  136. try:
  137. cursor = db.execute(
  138. "SELECT votes.name, votes.count, votes.info FROM votes"
  139. )
  140. return cursor.fetchall()
  141. except Error as aterror:
  142. current_app.logger.error(f'Couldn\'t select all votes: {aterror.args[0]}')
  143. def refund_reward(db, reward_id): # Refund a user for a particular reward
  144. reward_id = reward_id
  145. try:
  146. cursor = db.execute(
  147. "UPDATE reward_queue SET refunded = 1 WHERE id = ?",
  148. (reward_id,)
  149. )
  150. db.commit()
  151. except Error as rferror:
  152. current_app.logger.error(f'Couldn\'t refund reward id {reward_id}: {rferror.args[0]}')
  153. return False
  154. def fulfill_reward(db, reward_id): # Mark a reward as fulfilled in the database
  155. reward_id = reward_id
  156. try:
  157. cursor = db.execute(
  158. "UPDATE reward_queue SET fulfilled = 1 WHERE id = ?",
  159. (reward_id,)
  160. )
  161. db.commit()
  162. except Error as frerror:
  163. current_app.logger.error(f'Couldn\'t fulfill reward id {reward_id}: {frerror.args[0]}')
  164. return False
  165. def all_active_votes(db): # Get only active votes
  166. votes = all_votes(db)
  167. all_active_votes = []
  168. for name, count, info in votes:
  169. if is_reward_active(name):
  170. all_active_votes.append((name, count, info))
  171. return all_active_votes
  172. def all_goals(db): # Get all the goals
  173. try:
  174. cursor = db.execute(
  175. """SELECT name, progress, target, info FROM goals"""
  176. )
  177. return cursor.fetchall()
  178. except Error as agerror:
  179. current_app.logger.error(f'Couldn\'t select all goals: {agerror.args[0]}')
  180. def all_active_goals(db): # Get only active goals
  181. goals = all_goals(db)
  182. all_active_goals = []
  183. for name, progress, target, info in goals:
  184. if is_reward_active(name):
  185. all_active_goals.append((name, progress, target, info))
  186. return all_active_goals
  187. def all_active_rewards(): # Get only active rewards
  188. rewards = current_app.config['REWARDS']
  189. all_active_rewards = {}
  190. for reward_name, reward_dict in rewards.items():
  191. if reward_dict.get('categories'): # If reward has empty categories list
  192. for category in reward_dict['categories']: # Compare each category to ACTIVE_CAT list
  193. if category in current_app.config['ACTIVE_CAT']:
  194. all_active_rewards[reward_name] = reward_dict
  195. break
  196. return all_active_rewards
  197. def save_rewards(reward_info): # Write rewards to rewards.py
  198. new_rewards = json.dumps(reward_info, indent=4)
  199. rewards_file = os.path.join(current_app.instance_path, 'rewards.py')
  200. try:
  201. with open(rewards_file, 'w') as f:
  202. f.write(f'REWARDS = {new_rewards}')
  203. f.close
  204. except Exception as srerror:
  205. current_app.logger.error(f'Couldn\'t save rewards.py: {serror.args[0]}')
  206. return False
  207. return True
  208. def save_config(config_dict): # Write settings to config.py
  209. settings_file = os.path.join(current_app.instance_path, 'config.py')
  210. secret_key = current_app.config['SECRET_KEY']
  211. new_settings = f"# Owncast stuff. Needed to interact with your Owncast instance\n\
  212. ACCESS_TOKEN = '{config_dict['ACCESS_TOKEN']}'\n\
  213. OWNCAST_URL = '{config_dict['OWNCAST_URL']}'\n\
  214. \n\
  215. # OwnchatBot Configuration \n\
  216. SECRET_KEY = '{secret_key}' # Needed for internal Flask stuff. DO NOT DELETE.\n\
  217. POINTS_INTERVAL = {config_dict['POINTS_INTERVAL']} # How long, in seconds, between points awards\n\
  218. POINTS_AWARD = {config_dict['POINTS_AWARD']} # How many points awarded each interval?\n\
  219. GUNICORN = {config_dict['GUNICORN']} # Integrate OwnchatBot logging into Gunicorn\n\
  220. PREFIX = '{config_dict['PREFIX']}' # Preceeds commands, so OwnchatBot knows what is a command\n\
  221. MGMT_AUTH = '{config_dict['MGMT_AUTH']}' # Needed to access the OwnchatBot management panel. See README.md for more details.\n"
  222. with open(settings_file, 'w') as f:
  223. f.write(new_settings)
  224. f.close
  225. current_app.config.from_pyfile('config.py', silent=True) # Reread config.py into the app
  226. def reread_categories(): # Read _CAT varaibles and write to categories.py
  227. categories_file = os.path.join(current_app.instance_path, 'categories.py')
  228. active_categories = current_app.config['ACTIVE_CAT']
  229. inactive_categories = current_app.config['INACTIVE_CAT']
  230. try:
  231. with open(categories_file, 'r', encoding='utf-8') as f: # Read categories.py, and set up lines to change
  232. category_data = f.readlines()
  233. category_data[0] = f'ACTIVE_CAT = {active_categories}\n'
  234. category_data[1] = f'INACTIVE_CAT = {inactive_categories}\n'
  235. f.close
  236. with open(categories_file, 'w', encoding='utf-8') as f: # Write changes to categories.py
  237. f.writelines(category_data)
  238. f.close
  239. current_app.config.from_pyfile('categories.py', silent=True) # Reread categories into the app
  240. except Error as rcerror:
  241. current_app.logger.error(f'Couldn\'t reread categories: {rcerror.args[0]}')
  242. def activate_category(category): # Move an item from the ACTIVE_CAT list to the INACTIVE_CAT list
  243. try:
  244. categories_file = os.path.join(current_app.instance_path, 'categories.py')
  245. active_categories = current_app.config['ACTIVE_CAT']
  246. inactive_categories = current_app.config['INACTIVE_CAT']
  247. active_categories.append(category) # Add to ACTIVE_CAT
  248. inactive_categories.remove(category) # Remove from INACTIVE_CAT
  249. reread_categories()
  250. except Error as acerror:
  251. current_app.logger.error(f'Couldn\'t activate {category}: {acerror.args[0]}')
  252. def deactivate_category(category): # Move an item from the INACTIVE_CAT list to the ACTIVE_CAT list
  253. try:
  254. categories_file = os.path.join(current_app.instance_path, 'categories.py')
  255. active_categories = current_app.config['ACTIVE_CAT']
  256. inactive_categories = current_app.config['INACTIVE_CAT']
  257. active_categories.remove(category) # Remove from ACTIVE_CAT
  258. inactive_categories.append(category) # Add to INACTIVE_CAT
  259. reread_categories()
  260. except Error as dcerror:
  261. current_app.logger.error(f'Couldn\'t deactivate {category}: {dcerror.args[0]}')
  262. def get_queue(db): # Get the reward queue and the username
  263. try:
  264. cursor = db.execute(
  265. """SELECT reward_queue.id, reward_queue.created, reward_queue.reward, reward_queue.user_id, reward_queue.fulfilled, reward_queue.refunded, points.name
  266. FROM reward_queue
  267. INNER JOIN points
  268. on reward_queue.user_id = points.id"""
  269. )
  270. return cursor.fetchall()
  271. except Error as gqerror:
  272. current_app.logger.error(f'Couldn\'t get queue: {gqerror.args[0]}')
  273. def is_reward_active(reward_name): # Check if reward is active
  274. active_categories = current_app.config['ACTIVE_CAT']
  275. reward_dict = current_app.config['REWARDS'].get(reward_name, None)
  276. try:
  277. if reward_dict:
  278. if 'categories' in reward_dict: # Is there a categories key at all?
  279. for category in reward_dict['categories']: # Cycle through categories and compare to active_categories
  280. if category in active_categories:
  281. return True
  282. return False
  283. elif reward_dict['categories'] == []: # If categories key is there but empty, return False
  284. return False
  285. else:
  286. return True
  287. return None
  288. except Error as iraerror:
  289. current_app.logger.error(f'Couldn\'t check if {reward_name} is active: {iraerror.args[0]}')