reward_handlers.py 13 KB

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