reward_handlers.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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.error(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.error(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.error(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.error(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.error(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_milestone_reached(db, reward_name): # Check if a milestone was reached
  118. try:
  119. all_rewards = current_app.config['REWARDS'] # Get milestone numbers from REWARDS
  120. milestones_info = all_rewards[reward_name]['milestones']
  121. if milestones_info['milestone1'][1]:
  122. ms1_goal = milestones_info['milestone1'][1]
  123. ms1_reward = f'🚩 \"{milestones_info["milestone1"][0]}\"'
  124. if milestones_info['milestone2'][1]:
  125. ms2_goal = milestones_info['milestone2'][1]
  126. ms2_reward = f'🚩🚩 \"{milestones_info["milestone2"][0]}\"'
  127. if milestones_info['milestone3'][1]:
  128. ms3_goal = milestones_info['milestone3'][1]
  129. ms3_reward = f'🚩🚩🚩 \"{milestones_info["milestone3"][0]}\"'
  130. cursor = db.execute(
  131. "SELECT progress, milestones FROM goals WHERE name = ?",
  132. (reward_name,)
  133. ) # Get progress and milestones info from database
  134. row = cursor.fetchone()
  135. if row is None:
  136. current_app.logger.error(f'{reward_name} not found in Goal table.')
  137. else:
  138. progress = int(row['progress'])
  139. milestones = int(row['milestones'])
  140. if progress >= ms1_goal and progress < ms2_goal:
  141. new_milestones = 1
  142. ms_reward = ms1_reward
  143. elif progress >= ms2_goal and progress < ms3_goal:
  144. new_milestones = 2
  145. ms_reward = ms2_reward
  146. elif progress >= ms3_goal:
  147. new_milestones = 3
  148. ms_reward = ms3_reward
  149. else:
  150. new_milestones = 0
  151. if new_milestones > milestones: # If we're passing a milestone, get the reward
  152. cursor = db.execute(
  153. "UPDATE goals SET milestones = ? WHERE name = ?",
  154. (new_milestones, reward_name)
  155. )
  156. db.commit()
  157. return ms_reward
  158. else:
  159. return False
  160. return False
  161. except Error as wmrerror:
  162. current_app.logger.error(f'Couldn\'t check if a milestone was reached: {wmrerror.args[0]}')
  163. return False
  164. def was_goal_reached(db, reward_name): # Check if a goal was reached
  165. try:
  166. cursor = db.execute(
  167. "SELECT progress, target FROM goals WHERE name = ?",
  168. (reward_name,)
  169. )
  170. row = cursor.fetchone()
  171. if row is None:
  172. current_app.logger.error(f'{reward_name} not found in Goal table.')
  173. else:
  174. progress, target = row
  175. if progress == target:
  176. cursor = db.execute(
  177. "UPDATE goals SET complete = TRUE WHERE name = ?",
  178. (reward_name,)
  179. )
  180. db.commit()
  181. return True
  182. return False
  183. except Error as wgrerror:
  184. current_app.logger.error(f'Couldn\'t mark goal met: {wgrerror.args[0]}')
  185. return False
  186. def all_votes(db): # Get all the votes
  187. try:
  188. cursor = db.execute(
  189. "SELECT votes.name, votes.count, votes.info FROM votes"
  190. )
  191. return cursor.fetchall()
  192. except Error as aterror:
  193. current_app.logger.error(f'Couldn\'t select all votes: {aterror.args[0]}')
  194. def refund_reward(db, reward_id): # Refund a user for a particular reward
  195. reward_id = reward_id
  196. try:
  197. cursor = db.execute(
  198. "UPDATE reward_queue SET refunded = 1 WHERE id = ?",
  199. (reward_id,)
  200. )
  201. db.commit()
  202. except Error as rferror:
  203. current_app.logger.error(f'Couldn\'t refund reward id {reward_id}: {rferror.args[0]}')
  204. return False
  205. def fulfill_reward(db, reward_id): # Mark a reward as fulfilled in the database
  206. reward_id = reward_id
  207. try:
  208. cursor = db.execute(
  209. "UPDATE reward_queue SET fulfilled = 1 WHERE id = ?",
  210. (reward_id,)
  211. )
  212. db.commit()
  213. except Error as frerror:
  214. current_app.logger.error(f'Couldn\'t fulfill reward id {reward_id}: {frerror.args[0]}')
  215. return False
  216. def all_active_votes(db): # Get only active votes
  217. votes = all_votes(db)
  218. all_active_votes = []
  219. for name, count, info in votes:
  220. if is_reward_active(name):
  221. all_active_votes.append((name, count, info))
  222. return all_active_votes
  223. def all_goals(db): # Get all the goals
  224. try:
  225. cursor = db.execute(
  226. "SELECT name, progress, target, info FROM goals"
  227. )
  228. return cursor.fetchall()
  229. except Error as agerror:
  230. current_app.logger.error(f'Couldn\'t select all goals: {agerror.args[0]}')
  231. def all_active_goals(db): # Get only active goals
  232. goals = all_goals(db)
  233. all_active_goals = []
  234. for name, progress, target, info in goals:
  235. if is_reward_active(name):
  236. all_active_goals.append((name, progress, target, info))
  237. return all_active_goals
  238. def all_active_rewards(): # Get only active rewards
  239. rewards = current_app.config['REWARDS']
  240. all_active_rewards = {}
  241. for reward_name, reward_dict in rewards.items():
  242. if reward_dict.get('categories'): # If reward has empty categories list
  243. for category in reward_dict['categories']: # Compare each category to ACTIVE_CAT list
  244. if category in current_app.config['ACTIVE_CAT']:
  245. all_active_rewards[reward_name] = reward_dict
  246. break
  247. return all_active_rewards
  248. def save_rewards(reward_info): # Write rewards to rewards.py
  249. sorted_rewards = dict(sorted(reward_info.items(), key=sort_key))
  250. new_rewards = json.dumps(sorted_rewards, indent=4)
  251. rewards_file = os.path.join(current_app.instance_path, 'rewards.py')
  252. try:
  253. with open(rewards_file, 'w') as f:
  254. f.write(f'REWARDS = {new_rewards}')
  255. f.close()
  256. except Exception as srerror:
  257. current_app.logger.error(f'Couldn\'t save rewards.py: {srerror.args[0]}')
  258. return False
  259. return True
  260. def save_config(config_dict): # Write settings to config.py
  261. settings_file = os.path.join(current_app.instance_path, 'config.py')
  262. secret_key = current_app.config['SECRET_KEY']
  263. new_settings = f"# Owncast stuff. Needed to interact with your Owncast instance\n\
  264. ACCESS_TOKEN = '{config_dict['ACCESS_TOKEN']}'\n\
  265. OWNCAST_URL = '{config_dict['OWNCAST_URL']}'\n\
  266. \n\
  267. # OwnchatBot Configuration \n\
  268. SECRET_KEY = '{secret_key}' # Needed for internal Flask stuff. DO NOT DELETE.\n\
  269. POINTS_INTERVAL = {config_dict['POINTS_INTERVAL']} # How long, in seconds, between points awards\n\
  270. POINTS_AWARD = {config_dict['POINTS_AWARD']} # How many points awarded each interval?\n\
  271. GUNICORN = {config_dict['GUNICORN']} # Integrate OwnchatBot logging into Gunicorn\n\
  272. PREFIX = '{config_dict['PREFIX']}' # Preceeds commands, so OwnchatBot knows what is a command\n\
  273. MGMT_AUTH = '{config_dict['MGMT_AUTH']}' # Needed to access the OwnchatBot management panel. See README.md for more details.\n\
  274. 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\
  275. KOFI_INTEGRATION = {config_dict['KOFI_INTEGRATION']} # Integrate OwnchatBot with Ko-fi"
  276. try:
  277. with open(settings_file, 'w') as f:
  278. f.write(new_settings)
  279. f.close
  280. except Exception as scerror:
  281. current_app.logger.error(f'Couldn\'t save config.py: {saerror.args[0]}')
  282. return False
  283. current_app.config.from_pyfile('config.py', silent=True) # Reread config.py into the app
  284. return True
  285. def reread_categories(): # Read _CAT varaibles and write to categories.py
  286. categories_file = os.path.join(current_app.instance_path, 'categories.py')
  287. active_categories = current_app.config['ACTIVE_CAT']
  288. inactive_categories = current_app.config['INACTIVE_CAT']
  289. try:
  290. with open(categories_file, 'r', encoding='utf-8') as f: # Read categories.py, and set up lines to change
  291. category_data = f.readlines()
  292. category_data[0] = f'ACTIVE_CAT = {active_categories}\n'
  293. category_data[1] = f'INACTIVE_CAT = {inactive_categories}\n'
  294. f.close
  295. with open(categories_file, 'w', encoding='utf-8') as f: # Write changes to categories.py
  296. f.writelines(category_data)
  297. f.close
  298. current_app.config.from_pyfile('categories.py', silent=True) # Reread categories into the app
  299. except Error as rcerror:
  300. current_app.logger.error(f'Couldn\'t reread categories: {rcerror.args[0]}')
  301. def activate_category(category): # Move an item from the ACTIVE_CAT list to the INACTIVE_CAT list
  302. try:
  303. categories_file = os.path.join(current_app.instance_path, 'categories.py')
  304. active_categories = current_app.config['ACTIVE_CAT']
  305. inactive_categories = current_app.config['INACTIVE_CAT']
  306. active_categories.append(category) # Add to ACTIVE_CAT
  307. inactive_categories.remove(category) # Remove from INACTIVE_CAT
  308. reread_categories()
  309. except Error as acerror:
  310. current_app.logger.error(f'Couldn\'t activate {category}: {acerror.args[0]}')
  311. def deactivate_category(category): # Move an item from the INACTIVE_CAT list to the ACTIVE_CAT list
  312. try:
  313. categories_file = os.path.join(current_app.instance_path, 'categories.py')
  314. active_categories = current_app.config['ACTIVE_CAT']
  315. inactive_categories = current_app.config['INACTIVE_CAT']
  316. active_categories.remove(category) # Remove from ACTIVE_CAT
  317. inactive_categories.append(category) # Add to INACTIVE_CAT
  318. reread_categories()
  319. except Error as dcerror:
  320. current_app.logger.error(f'Couldn\'t deactivate {category}: {dcerror.args[0]}')
  321. def get_queue(db): # Get the reward queue and the username
  322. try:
  323. cursor = db.execute(
  324. """SELECT reward_queue.id, reward_queue.created, reward_queue.reward, reward_queue.user_id, reward_queue.fulfilled, reward_queue.refunded, points.name
  325. FROM reward_queue
  326. INNER JOIN points
  327. on reward_queue.user_id = points.id"""
  328. )
  329. return cursor.fetchall()
  330. except Error as gqerror:
  331. current_app.logger.error(f'Couldn\'t get queue: {gqerror.args[0]}')
  332. def is_reward_active(reward_name): # Check if reward is active
  333. active_categories = current_app.config['ACTIVE_CAT']
  334. reward_dict = current_app.config['REWARDS'].get(reward_name, None)
  335. try:
  336. if reward_dict:
  337. if 'categories' in reward_dict: # Is there a categories key at all?
  338. for category in reward_dict['categories']: # Cycle through categories and compare to active_categories
  339. if category in active_categories:
  340. return True
  341. return False
  342. elif reward_dict['categories'] == []: # If categories key is there but empty, return False
  343. return False
  344. else:
  345. return True
  346. return None
  347. except Error as iraerror:
  348. current_app.logger.error(f'Couldn\'t check if {reward_name} is active: {iraerror.args[0]}')