reward_handlers.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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. from ownchatbot.owncast_com import send_chat
  8. def sort_key(item): # Sort rewards by price
  9. price = item[1].get('price')
  10. return (price is None, price)
  11. def check_vote(db, vote_name, user_id): # Check if user has already voted on this vote
  12. try:
  13. cursor = db.execute(
  14. "SELECT voters FROM votes WHERE name = ?",
  15. (vote_name,)
  16. )
  17. row = cursor.fetchone()
  18. if row is None:
  19. current_app.logger.error(f'\"{vote_name}\" not found in vote table.')
  20. return False
  21. if row[0] == user_id:
  22. return True
  23. except Error as cverror:
  24. current_app.logger.error(f'Couldn\'t check if {user_id} already voted on \"{vote_name}\": {cverror.args[0]}')
  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. ms1_goal = ms2_goal = ms3_goal = float('inf') # To avoid referencing unassigned variables, in case there aren't any milestones set
  122. ms1_reward = ms2_reward = ms3_reward = None # Initialize to None
  123. if len(milestones_info['milestone1']) > 1 and milestones_info['milestone1'][1]: # Check that there is a value for the milestone
  124. ms1_goal = milestones_info['milestone1'][1]
  125. ms1_reward = f'🚩 \"{milestones_info["milestone1"][0]}\"'
  126. if len(milestones_info['milestone2']) > 1 and milestones_info['milestone2'][1]:
  127. ms2_goal = milestones_info['milestone2'][1]
  128. ms2_reward = f'🚩🚩 \"{milestones_info["milestone2"][0]}\"'
  129. if len(milestones_info['milestone3']) > 1 and milestones_info['milestone3'][1]:
  130. ms3_goal = milestones_info['milestone3'][1]
  131. ms3_reward = f'🚩🚩🚩 \"{milestones_info["milestone3"][0]}\"'
  132. cursor = db.execute(
  133. "SELECT progress, milestones FROM goals WHERE name = ?",
  134. (reward_name,)
  135. ) # Get progress and milestones info from database
  136. row = cursor.fetchone()
  137. if row is None:
  138. current_app.logger.error(f'{reward_name} not found in Goal table.')
  139. else:
  140. progress = int(row['progress'])
  141. milestones = int(row['milestones'])
  142. if progress >= ms1_goal and progress < ms2_goal:
  143. new_milestones = 1
  144. ms_reward = ms1_reward
  145. elif progress >= ms2_goal and progress < ms3_goal:
  146. new_milestones = 2
  147. ms_reward = ms2_reward
  148. elif progress >= ms3_goal:
  149. new_milestones = 3
  150. ms_reward = ms3_reward
  151. else:
  152. new_milestones = 0
  153. if new_milestones > milestones: # If we're passing a milestone, get the reward
  154. cursor = db.execute(
  155. "UPDATE goals SET milestones = ? WHERE name = ?",
  156. (new_milestones, reward_name)
  157. )
  158. db.commit()
  159. current_app.logger.info(f'new_milestone: {new_milestones}') # TESTING
  160. if new_milestones < 3: # If there is another milestone
  161. next_milestone = new_milestones + 1 # Get the number of the next milestone
  162. next_milestone = f'milestone{next_milestone}' # Set up the dict entry name
  163. if next_milestone:
  164. next_milestone = milestones_info[next_milestone][0] # Get the name of the next milestone
  165. else:
  166. next_milestone = "Done"
  167. current_app.logger.info(f'The next milestone is \"{next_milestone}\"') # TESTING
  168. return ms_reward, next_milestone
  169. else:
  170. return False
  171. return False
  172. except Error as wmrerror:
  173. current_app.logger.error(f'Couldn\'t check if a milestone was reached: {wmrerror.args[0]}')
  174. return False
  175. def was_goal_reached(db, reward_name): # Check if a goal was reached
  176. try:
  177. cursor = db.execute(
  178. "SELECT progress, target FROM goals WHERE name = ?",
  179. (reward_name,)
  180. )
  181. row = cursor.fetchone()
  182. if row is None:
  183. current_app.logger.error(f'{reward_name} not found in Goal table.')
  184. else:
  185. progress, target = row
  186. if progress == target:
  187. cursor = db.execute(
  188. "UPDATE goals SET complete = TRUE WHERE name = ?",
  189. (reward_name,)
  190. )
  191. db.commit()
  192. return True
  193. return False
  194. except Error as wgrerror:
  195. current_app.logger.error(f'Couldn\'t mark goal met: {wgrerror.args[0]}')
  196. return False
  197. def all_votes(db): # Get all the votes
  198. try:
  199. cursor = db.execute(
  200. "SELECT votes.name, votes.count, votes.info FROM votes"
  201. )
  202. return cursor.fetchall()
  203. except Error as aterror:
  204. current_app.logger.error(f'Couldn\'t select all votes: {aterror.args[0]}')
  205. def refund_reward(db, reward_id): # Refund a user for a particular reward
  206. reward_id = reward_id
  207. try:
  208. cursor = db.execute(
  209. "UPDATE reward_queue SET refunded = 1 WHERE id = ?",
  210. (reward_id,)
  211. )
  212. db.commit()
  213. except Error as rferror:
  214. current_app.logger.error(f'Couldn\'t refund reward id {reward_id}: {rferror.args[0]}')
  215. return False
  216. def fulfill_reward(db, reward_id): # Mark a reward as fulfilled in the database
  217. reward_id = reward_id
  218. try:
  219. cursor = db.execute(
  220. "UPDATE reward_queue SET fulfilled = 1 WHERE id = ?",
  221. (reward_id,)
  222. )
  223. db.commit()
  224. except Error as frerror:
  225. current_app.logger.error(f'Couldn\'t fulfill reward id {reward_id}: {frerror.args[0]}')
  226. return False
  227. def all_active_votes(db): # Get only active votes
  228. votes = all_votes(db)
  229. all_active_votes = []
  230. for name, count, info in votes:
  231. if is_reward_active(name):
  232. all_active_votes.append((name, count, info))
  233. return all_active_votes
  234. def all_goals(db): # Get all the goals
  235. try:
  236. cursor = db.execute(
  237. "SELECT name, progress, target, info FROM goals"
  238. )
  239. return cursor.fetchall()
  240. except Error as agerror:
  241. current_app.logger.error(f'Couldn\'t select all goals: {agerror.args[0]}')
  242. def all_active_goals(db): # Get only active goals
  243. goals = all_goals(db)
  244. all_active_goals = []
  245. for name, progress, target, info in goals:
  246. if is_reward_active(name):
  247. all_active_goals.append((name, progress, target, info))
  248. return all_active_goals
  249. def all_active_rewards(): # Get only active rewards
  250. rewards = current_app.config['REWARDS']
  251. all_active_rewards = {}
  252. for reward_name, reward_dict in rewards.items():
  253. if reward_dict.get('categories'): # If reward has empty categories list
  254. for category in reward_dict['categories']: # Compare each category to ACTIVE_CAT list
  255. if category in current_app.config['ACTIVE_CAT']:
  256. all_active_rewards[reward_name] = reward_dict
  257. break
  258. return all_active_rewards
  259. def save_alerts(alerts_dict): # Write alerts to alerts.py
  260. alerts_dict = json.dumps(alerts_dict, indent=4)
  261. alerts_file = os.path.join(current_app.instance_path, 'alerts.py')
  262. new_alerts = f"ALERTS = {alerts_dict}"
  263. try:
  264. with open(alerts_file, 'w') as af:
  265. af.write(new_alerts)
  266. af.close
  267. current_app.logger.info('Saved new alerts.py.')
  268. except Exception as saerror:
  269. current_app.logger.error(f'Couldn\'t save alerts.py: {saerror.args[0]}')
  270. return False
  271. current_app.config.from_pyfile('alerts.py', silent=True) # Reread alerts.py into the app
  272. return True
  273. def del_alert_file(alert_file):
  274. filepath = os.path.join(current_app.config['ASSETS_FOLDER'], alert_file)
  275. try:
  276. os.remove(filepath)
  277. current_app.logger.info(f"Successfully removed \"{alert_file}\" from alerts folder.")
  278. return True
  279. except FileNotFoundError:
  280. current_app.logger.error(f"Couldn't delet \"{alert_file}\": File not found.")
  281. return False
  282. except PermissionError:
  283. current_app.logger.error(f"No permission to delete file: \"{alert_file}\"")
  284. return False
  285. except Exception as daferror:
  286. current_app.logger.error(f"An error occurred: {daferror}")
  287. return False
  288. def save_rewards(reward_info): # Write rewards to rewards.py
  289. sorted_rewards = dict(sorted(reward_info.items(), key=sort_key))
  290. new_rewards = json.dumps(sorted_rewards, indent=4)
  291. rewards_file = os.path.join(current_app.instance_path, 'rewards.py')
  292. try:
  293. with open(rewards_file, 'w') as rf:
  294. rf.write(f'REWARDS = {new_rewards}')
  295. rf.close()
  296. except Exception as srerror:
  297. current_app.logger.error(f'Couldn\'t save rewards.py: {srerror.args[0]}')
  298. return False
  299. return True
  300. def save_config(config_dict): # Write settings to config.py
  301. settings_file = os.path.join(current_app.instance_path, 'config.py')
  302. secret_key = current_app.config['SECRET_KEY']
  303. new_settings = f"# Owncast stuff. Needed to interact with your Owncast instance\n\
  304. ACCESS_ID = '{config_dict['ACCESS_ID']}'\n\
  305. ACCESS_TOKEN = '{config_dict['ACCESS_TOKEN']}'\n\
  306. OWNCAST_URL = '{config_dict['OWNCAST_URL']}'\n\
  307. \n\
  308. # OwnchatBot Configuration \n\
  309. SECRET_KEY = '{secret_key}' # Needed for internal Flask stuff. DO NOT DELETE.\n\
  310. POINTS_INTERVAL = {config_dict['POINTS_INTERVAL']} # How long, in seconds, between points awards\n\
  311. POINTS_AWARD = {config_dict['POINTS_AWARD']} # How many points awarded each interval?\n\
  312. GUNICORN = {config_dict['GUNICORN']} # Integrate OwnchatBot logging into Gunicorn\n\
  313. PREFIX = '{config_dict['PREFIX']}' # Preceeds commands, so OwnchatBot knows what is a command\n\
  314. 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\
  315. KOFI_INTEGRATION = {config_dict['KOFI_INTEGRATION']} # Integrate OwnchatBot with Ko-fi"
  316. try:
  317. with open(settings_file, 'w') as cf:
  318. cf.write(new_settings)
  319. cf.close
  320. except Exception as scerror:
  321. current_app.logger.error(f'Couldn\'t save config.py: {scerror.args[0]}')
  322. return False
  323. current_app.config.from_pyfile('config.py', silent=True) # Reread config.py into the app
  324. return True
  325. def reread_categories(): # Read _CAT varaibles and write to categories.py
  326. categories_file = os.path.join(current_app.instance_path, 'categories.py')
  327. active_categories = current_app.config['ACTIVE_CAT']
  328. inactive_categories = current_app.config['INACTIVE_CAT']
  329. try:
  330. with open(categories_file, 'r', encoding='utf-8') as f: # Read categories.py, and set up lines to change
  331. category_data = f.readlines()
  332. category_data[0] = f'ACTIVE_CAT = {active_categories}\n'
  333. category_data[1] = f'INACTIVE_CAT = {inactive_categories}\n'
  334. f.close
  335. with open(categories_file, 'w', encoding='utf-8') as f: # Write changes to categories.py
  336. f.writelines(category_data)
  337. f.close
  338. current_app.config.from_pyfile('categories.py', silent=True) # Reread categories into the app
  339. except Error as rcerror:
  340. current_app.logger.error(f'Couldn\'t reread categories: {rcerror.args[0]}')
  341. def activate_category(category): # Move an item from the ACTIVE_CAT list to the INACTIVE_CAT list
  342. try:
  343. categories_file = os.path.join(current_app.instance_path, 'categories.py')
  344. active_categories = current_app.config['ACTIVE_CAT']
  345. inactive_categories = current_app.config['INACTIVE_CAT']
  346. active_categories.append(category) # Add to ACTIVE_CAT
  347. inactive_categories.remove(category) # Remove from INACTIVE_CAT
  348. reread_categories()
  349. except Error as acerror:
  350. current_app.logger.error(f'Couldn\'t activate {category}: {acerror.args[0]}')
  351. def deactivate_category(category): # Move an item from the INACTIVE_CAT list to the ACTIVE_CAT list
  352. try:
  353. categories_file = os.path.join(current_app.instance_path, 'categories.py')
  354. active_categories = current_app.config['ACTIVE_CAT']
  355. inactive_categories = current_app.config['INACTIVE_CAT']
  356. active_categories.remove(category) # Remove from ACTIVE_CAT
  357. inactive_categories.append(category) # Add to INACTIVE_CAT
  358. reread_categories()
  359. except Error as dcerror:
  360. current_app.logger.error(f'Couldn\'t deactivate {category}: {dcerror.args[0]}')
  361. def get_queue(db): # Get the reward queue and the username
  362. try:
  363. cursor = db.execute(
  364. """SELECT reward_queue.id, reward_queue.created, reward_queue.reward, reward_queue.user_id, reward_queue.fulfilled, reward_queue.refunded, points.name
  365. FROM reward_queue
  366. INNER JOIN points
  367. on reward_queue.user_id = points.id"""
  368. )
  369. return cursor.fetchall()
  370. except Error as gqerror:
  371. current_app.logger.error(f'Couldn\'t get queue: {gqerror.args[0]}')
  372. def is_reward_active(reward_name): # Check if reward is active
  373. active_categories = current_app.config['ACTIVE_CAT']
  374. reward_dict = current_app.config['REWARDS'].get(reward_name, None)
  375. try:
  376. if reward_dict:
  377. if 'categories' in reward_dict: # Is there a categories key at all?
  378. for category in reward_dict['categories']: # Cycle through categories and compare to active_categories
  379. if category in active_categories:
  380. return True
  381. return False
  382. elif reward_dict['categories'] == []: # If categories key is there but empty, return False
  383. return False
  384. else:
  385. return True
  386. return None
  387. except Error as iraerror:
  388. current_app.logger.error(f'Couldn\'t check if {reward_name} is active: {iraerror.args[0]}')