utils.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. import datetime
  2. from enum import Enum
  3. from typing import List
  4. import myanimebot.globals as globals
  5. class Service(Enum):
  6. MAL=globals.SERVICE_MAL
  7. ANILIST=globals.SERVICE_ANILIST
  8. @staticmethod
  9. def from_str(label: str):
  10. if label.upper() in ('MAL', 'MYANIMELIST', globals.SERVICE_MAL.upper()):
  11. return Service.MAL
  12. elif label.upper() in ('AL', 'ANILIST', globals.SERVICE_ANILIST.upper()):
  13. return Service.ANILIST
  14. else:
  15. raise NotImplementedError('Error: Cannot convert "{}" to a Service'.format(label))
  16. class MediaType(Enum):
  17. ANIME="ANIME"
  18. MANGA="MANGA"
  19. @staticmethod
  20. def from_str(label: str):
  21. if label.upper() in ('ANIME', 'ANIME_LIST'):
  22. return MediaType.ANIME
  23. elif label.upper() in ('MANGA', 'MANGA_LIST'):
  24. return MediaType.MANGA
  25. else:
  26. raise NotImplementedError('Error: Cannot convert "{}" to a MediaType'.format(label))
  27. class User():
  28. data = None
  29. def __init__(self,
  30. id : int,
  31. service_id : int,
  32. name : str,
  33. servers : List[int]):
  34. self.id = id
  35. self.service_id = service_id
  36. self.name = name
  37. self.servers = servers
  38. class Media():
  39. def __init__(self,
  40. name : str,
  41. url : str,
  42. episodes : str,
  43. image : str,
  44. type : MediaType):
  45. self.name = name
  46. self.url = url
  47. self.episodes = episodes
  48. self.image = image
  49. self.type = type
  50. @staticmethod
  51. def get_number_episodes(activity):
  52. media_type = MediaType.from_str(activity["type"])
  53. episodes = '?'
  54. if media_type == MediaType.ANIME:
  55. episodes = activity["media"]["episodes"]
  56. elif media_type == MediaType.MANGA:
  57. episodes = activity["media"]["chapters"]
  58. else:
  59. raise NotImplementedError('Error: Unknown media type "{}"'.format(media_type))
  60. if episodes is None:
  61. episodes = '?'
  62. return episodes
  63. class Feed():
  64. def __init__(self,
  65. service : Service,
  66. date_publication : datetime.datetime,
  67. user : User,
  68. status : str, # TODO Need to change
  69. description : str, # TODO Need to change
  70. media : Media
  71. ):
  72. self.service = service
  73. self.date_publication = date_publication
  74. self.user = user
  75. self.status = status
  76. self.media = media
  77. self.description = description
  78. def replace_all(text : str, replace_dic : dict) -> str:
  79. ''' Replace multiple substrings from a string '''
  80. for replace_key, replace_value in replace_dic.items():
  81. text = text.replace(replace_key, replace_value)
  82. return text
  83. def filter_name(name : str) -> str:
  84. ''' Escapes special characters from name '''
  85. dic = {
  86. "♥": "\♥",
  87. "♀": "\♀",
  88. "♂": "\♂",
  89. "♪": "\♪",
  90. "☆": "\☆"
  91. }
  92. return replace_all(name, dic)
  93. # Check if the show's name ends with a show type and truncate it
  94. def truncate_end_show(show):
  95. show_types = (
  96. '- TV',
  97. '- Movie',
  98. '- Special',
  99. '- OVA',
  100. '- ONA',
  101. '- Manga',
  102. '- Manhua',
  103. '- Manhwa',
  104. '- Novel',
  105. '- One-Shot',
  106. '- Doujinshi',
  107. '- Music',
  108. '- OEL',
  109. '- Unknown'
  110. )
  111. for show_type in show_types:
  112. if show.endswith(show_type):
  113. new_show = show[:-len(show_type)]
  114. # Check if space at the end
  115. if new_show.endswith(' '):
  116. new_show = new_show[:-1]
  117. return new_show
  118. return show
  119. def get_channels(server_id: int) -> dict:
  120. ''' Returns the registered channels for a server '''
  121. if server_id is None:
  122. return None
  123. # TODO Make generic execute
  124. cursor = globals.conn.cursor(buffered=True, dictionary=True)
  125. cursor.execute("SELECT channel FROM t_servers WHERE server = %s", [server_id])
  126. channels = cursor.fetchall()
  127. cursor.close()
  128. return channels
  129. def is_server_in_db(server_id : str) -> bool:
  130. ''' Checks if server is registered in the database '''
  131. if server_id is None:
  132. return False
  133. cursor = globals.conn.cursor(buffered=True)
  134. cursor.execute("SELECT server FROM t_servers WHERE server=%s", [server_id])
  135. data = cursor.fetchone()
  136. cursor.close()
  137. return data is not None
  138. def get_users() -> List[dict]:
  139. ''' Returns all registered users '''
  140. cursor = globals.conn.cursor(buffered=True, dictionary=True)
  141. cursor.execute('SELECT {}, service, servers FROM t_users'.format(globals.DB_USER_NAME))
  142. users = cursor.fetchall()
  143. cursor.close()
  144. return users
  145. def get_user_servers(user_name : str, service : Service) -> str:
  146. ''' Returns a list of every registered servers for a user of a specific service, as a string '''
  147. if user_name is None or service is None:
  148. return
  149. cursor = globals.conn.cursor(buffered=True, dictionary=True)
  150. cursor.execute("SELECT servers FROM t_users WHERE LOWER({})=%s AND service=%s".format(globals.DB_USER_NAME),
  151. [user_name.lower(), service.value])
  152. user_servers = cursor.fetchone()
  153. cursor.close()
  154. if user_servers is not None:
  155. return user_servers["servers"]
  156. return None
  157. def remove_server_from_servers(server : str, servers : str) -> str:
  158. ''' Removes the server from a comma-separated string containing multiple servers '''
  159. servers_list = servers.split(',')
  160. # If the server is not found, return None
  161. if server not in servers_list:
  162. return None
  163. # Remove every occurence of server
  164. servers_list = [x for x in servers_list if x != server]
  165. # Build server-free string
  166. return ','.join(servers_list)
  167. def delete_user_from_db(user_name : str, service : Service) -> bool:
  168. ''' Removes the user from the database '''
  169. if user_name is None or service is None:
  170. globals.logger.warning("Error while trying to delete user '{}' with service '{}'".format(user_name, service))
  171. return False
  172. cursor = globals.conn.cursor(buffered=True)
  173. cursor.execute("DELETE FROM t_users WHERE LOWER({}) = %s AND service=%s".format(globals.DB_USER_NAME),
  174. [user_name.lower(), service.value])
  175. globals.conn.commit()
  176. cursor.close()
  177. return True
  178. def update_user_servers_db(user_name : str, service : Service, servers : str) -> bool:
  179. if user_name is None or service is None or servers is None:
  180. globals.logger.warning("Error while trying to update user's servers. User '{}' with service '{}' and servers '{}'".format(user_name, service, servers))
  181. return False
  182. cursor = globals.conn.cursor(buffered=True)
  183. cursor.execute("UPDATE t_users SET servers = %s WHERE LOWER({}) = %s AND service=%s".format(globals.DB_USER_NAME),
  184. [servers, user_name.lower(), service.value])
  185. globals.conn.commit()
  186. cursor.close()
  187. return True
  188. def insert_user_into_db(user_name : str, service : Service, servers : str) -> bool:
  189. ''' Add the user to the database '''
  190. if user_name is None or service is None or servers is None:
  191. globals.logger.warning("Error while trying to add user '{}' with service '{}' and servers '{}'".format(user_name, service, servers))
  192. return False
  193. cursor = globals.conn.cursor(buffered=True)
  194. cursor.execute("INSERT INTO t_users ({}, service, servers) VALUES (%s, %s, %s)".format(globals.DB_USER_NAME),
  195. [user_name, service.value, servers])
  196. globals.conn.commit()
  197. cursor.close()
  198. return True
  199. # TODO Create a Feed class instead of sending a lot of parameters