utils.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. import datetime
  2. from enum import Enum
  3. from typing import List
  4. import myanimebot.globals as globals
  5. # TODO Redo all of the desc/status system
  6. # Media Status colors
  7. CURRENT_COLOR = "00CC00"
  8. PLANNING_COLOR = "BFBFBF"
  9. COMPLETED_COLOR = "0000CC"
  10. DROPPED_COLOR = "CC0000"
  11. PAUSED_COLOR = "DDDD00"
  12. REPEATING_COLOR = "007700"
  13. class Service(Enum):
  14. MAL=globals.SERVICE_MAL
  15. ANILIST=globals.SERVICE_ANILIST
  16. @staticmethod
  17. def from_str(label: str):
  18. if label is None: raise TypeError
  19. if label.upper() in ('MAL', 'MYANIMELIST', globals.SERVICE_MAL.upper()):
  20. return Service.MAL
  21. elif label.upper() in ('AL', 'ANILIST', globals.SERVICE_ANILIST.upper()):
  22. return Service.ANILIST
  23. else:
  24. raise NotImplementedError('Error: Cannot convert "{}" to a Service'.format(label))
  25. class MediaType(Enum):
  26. ANIME="ANIME"
  27. MANGA="MANGA"
  28. @staticmethod
  29. def from_str(label: str):
  30. if label is None: raise TypeError
  31. if label.upper() in ('ANIME', 'ANIME_LIST'):
  32. return MediaType.ANIME
  33. elif label.upper() in ('MANGA', 'MANGA_LIST'):
  34. return MediaType.MANGA
  35. else:
  36. raise NotImplementedError('Error: Cannot convert "{}" to a MediaType'.format(label))
  37. def get_media_count_type(self):
  38. if self == MediaType.ANIME:
  39. return 'episodes'
  40. elif self == MediaType.MANGA:
  41. return 'chapters'
  42. else:
  43. raise NotImplementedError('Unknown MediaType "{}"'.format(self))
  44. class MediaStatus(Enum):
  45. CURRENT = CURRENT_COLOR
  46. PLANNING = PLANNING_COLOR
  47. COMPLETED = COMPLETED_COLOR
  48. DROPPED = DROPPED_COLOR
  49. PAUSED = PAUSED_COLOR
  50. REPEATING = REPEATING_COLOR
  51. @staticmethod
  52. def from_str(label: str):
  53. if label is None: raise TypeError
  54. first_word = label.split(' ')[0].upper()
  55. if first_word in ['READ', 'READING', 'WATCHED', 'WATCHING']:
  56. return MediaStatus.CURRENT
  57. elif first_word in ['PLANS', 'PLAN']:
  58. return MediaStatus.PLANNING
  59. elif first_word in ['COMPLETED']:
  60. return MediaStatus.COMPLETED
  61. elif first_word in ['DROPPED']:
  62. return MediaStatus.DROPPED
  63. elif first_word in ['PAUSED', 'ON-HOLD']:
  64. return MediaStatus.PAUSED
  65. elif first_word in ['REREAD', 'REREADING', 'REWATCHED', 'REWATCHING', 'RE-READING', 'RE-WATCHING', 'RE-READ', 'RE-WATCHED']:
  66. return MediaStatus.REPEATING
  67. else:
  68. raise NotImplementedError('Error: Cannot convert "{}" to a MediaStatus'.format(label))
  69. class User():
  70. data = None
  71. def __init__(self,
  72. id : int,
  73. service_id : int,
  74. name : str,
  75. servers : List[int]):
  76. self.id = id
  77. self.service_id = service_id
  78. self.name = name
  79. self.servers = servers
  80. class Media():
  81. def __init__(self,
  82. name : str,
  83. url : str,
  84. episodes : str,
  85. image : str,
  86. type : MediaType):
  87. self.name = name
  88. self.url = url
  89. self.episodes = episodes
  90. self.image = image
  91. self.type = type
  92. class Feed():
  93. def __init__(self,
  94. service : Service,
  95. date_publication : datetime.datetime,
  96. user : User,
  97. status : MediaStatus,
  98. description : str, # TODO Need to change
  99. progress : str,
  100. media : Media
  101. ):
  102. self.service = service
  103. self.date_publication = date_publication
  104. self.user = user
  105. self.status = status
  106. self.media = media
  107. self.description = description
  108. self.progress = progress
  109. def get_status_str(self):
  110. if self.status == MediaStatus.CURRENT \
  111. or self.status == MediaStatus.REPEATING:
  112. if self.media.type == MediaType.ANIME:
  113. status_str = 'Watching'
  114. elif self.media.type == MediaType.MANGA:
  115. status_str = 'Reading'
  116. else:
  117. raise NotImplementedError('Unknown MediaType: {}'.format(self.media.type))
  118. # Add prefix if rewatching
  119. if self.status == MediaStatus.REPEATING:
  120. status_str = 'Re-{}'.format(status_str.lower())
  121. elif self.status == MediaStatus.COMPLETED:
  122. status_str = 'Completed'
  123. elif self.status == MediaStatus.PAUSED:
  124. status_str = 'Paused'
  125. elif self.status == MediaStatus.DROPPED:
  126. status_str = 'Dropped'
  127. elif self.status == MediaStatus.PLANNING:
  128. if self.media.type == MediaType.ANIME:
  129. media_type_label = 'watch'
  130. elif self.media.type == MediaType.MANGA:
  131. media_type_label = 'read'
  132. else:
  133. raise NotImplementedError('Unknown MediaType: {}'.format(self.media.type))
  134. status_str = 'Plans to {}'.format(media_type_label)
  135. else:
  136. raise NotImplementedError('Unknown MediaStatus: {}'.format(self.status))
  137. return status_str
  138. def replace_all(text : str, replace_dic : dict) -> str:
  139. '''Replace multiple substrings from a string'''
  140. if text is None or replace_dic is None:
  141. return text
  142. for replace_key, replace_value in replace_dic.items():
  143. text = text.replace(replace_key, replace_value)
  144. return text
  145. def filter_name(name : str) -> str:
  146. '''Escapes special characters from name'''
  147. dic = {
  148. "♥": "\♥",
  149. "♀": "\♀",
  150. "♂": "\♂",
  151. "♪": "\♪",
  152. "☆": "\☆"
  153. }
  154. return replace_all(name, dic)
  155. # Check if the show's name ends with a show type and truncate it
  156. def truncate_end_show(media_name : str):
  157. '''Check if a show's name ends with a show type and truncate it'''
  158. if media_name is None: return None
  159. show_types = (
  160. '- TV',
  161. '- Movie',
  162. '- Special',
  163. '- OVA',
  164. '- ONA',
  165. '- Manga',
  166. '- Manhua',
  167. '- Manhwa',
  168. '- Novel',
  169. '- One-Shot',
  170. '- Doujinshi',
  171. '- Music',
  172. '- OEL',
  173. '- Unknown',
  174. '- Light Novel'
  175. )
  176. for show_type in show_types:
  177. if media_name.endswith(show_type):
  178. new_show = media_name[:-len(show_type)]
  179. # Check if space at the end
  180. if new_show.endswith(' '):
  181. new_show = new_show[:-1]
  182. return new_show
  183. return media_name
  184. def build_description_string(feed : Feed):
  185. '''Build and returns a string describing the feed'''
  186. media_type_count = feed.media.type.get_media_count_type()
  187. status_str = feed.get_status_str()
  188. # Build the string
  189. return '{} | {} of {} {}'.format(status_str, feed.progress, feed.media.episodes, media_type_count)
  190. def get_channels(server_id: int) -> dict:
  191. '''Returns the registered channels for a server'''
  192. if server_id is None: return None
  193. # TODO Make generic execute
  194. cursor = globals.conn.cursor(buffered=True, dictionary=True)
  195. cursor.execute("SELECT channel FROM t_servers WHERE server = %s", [server_id])
  196. channels = cursor.fetchall()
  197. cursor.close()
  198. return channels
  199. def is_server_in_db(server_id : str) -> bool:
  200. '''Checks if server is registered in the database'''
  201. if server_id is None:
  202. return False
  203. cursor = globals.conn.cursor(buffered=True)
  204. cursor.execute("SELECT server FROM t_servers WHERE server=%s", [server_id])
  205. data = cursor.fetchone()
  206. cursor.close()
  207. return data is not None
  208. def get_users() -> List[dict]:
  209. '''Returns all registered users'''
  210. cursor = globals.conn.cursor(buffered=True, dictionary=True)
  211. cursor.execute('SELECT {}, service, servers FROM t_users'.format(globals.DB_USER_NAME))
  212. users = cursor.fetchall()
  213. cursor.close()
  214. return users
  215. def get_user_servers(user_name : str, service : Service) -> str:
  216. '''Returns a list of every registered servers for a user of a specific service, as a string'''
  217. if user_name is None or service is None:
  218. return
  219. cursor = globals.conn.cursor(buffered=True, dictionary=True)
  220. cursor.execute("SELECT servers FROM t_users WHERE LOWER({})=%s AND service=%s".format(globals.DB_USER_NAME),
  221. [user_name.lower(), service.value])
  222. user_servers = cursor.fetchone()
  223. cursor.close()
  224. if user_servers is not None:
  225. return user_servers["servers"]
  226. return None
  227. def remove_server_from_servers(server : str, servers : str) -> str:
  228. '''Removes the server from a comma-separated string containing multiple servers'''
  229. servers_list = servers.split(',')
  230. # If the server is not found, return None
  231. if server not in servers_list:
  232. return None
  233. # Remove every occurence of server
  234. servers_list = [x for x in servers_list if x != server]
  235. # Build server-free string
  236. return ','.join(servers_list)
  237. def delete_user_from_db(user_name : str, service : Service) -> bool:
  238. '''Removes the user from the database'''
  239. if user_name is None or service is None:
  240. globals.logger.warning("Error while trying to delete user '{}' with service '{}'".format(user_name, service))
  241. return False
  242. cursor = globals.conn.cursor(buffered=True)
  243. cursor.execute("DELETE FROM t_users WHERE LOWER({}) = %s AND service=%s".format(globals.DB_USER_NAME),
  244. [user_name.lower(), service.value])
  245. globals.conn.commit()
  246. cursor.close()
  247. return True
  248. def update_user_servers_db(user_name : str, service : Service, servers : str) -> bool:
  249. if user_name is None or service is None or servers is None:
  250. globals.logger.warning("Error while trying to update user's servers. User '{}' with service '{}' and servers '{}'".format(user_name, service, servers))
  251. return False
  252. cursor = globals.conn.cursor(buffered=True)
  253. cursor.execute("UPDATE t_users SET servers = %s WHERE LOWER({}) = %s AND service=%s".format(globals.DB_USER_NAME),
  254. [servers, user_name.lower(), service.value])
  255. globals.conn.commit()
  256. cursor.close()
  257. return True
  258. def insert_user_into_db(user_name : str, service : Service, servers : str) -> bool:
  259. '''Add the user to the database'''
  260. if user_name is None or service is None or servers is None:
  261. globals.logger.warning("Error while trying to add user '{}' with service '{}' and servers '{}'".format(user_name, service, servers))
  262. return False
  263. cursor = globals.conn.cursor(buffered=True)
  264. cursor.execute("INSERT INTO t_users ({}, service, servers) VALUES (%s, %s, %s)".format(globals.DB_USER_NAME),
  265. [user_name, service.value, servers])
  266. globals.conn.commit()
  267. cursor.close()
  268. return True
  269. def get_allowed_role(server : int) -> int:
  270. '''Return the allowed role for a given server'''
  271. cursor = globals.conn.cursor(buffered=True)
  272. cursor.execute("SELECT admin_group FROM t_servers WHERE server=%s LIMIT 1", [str(server)])
  273. allowedRole = cursor.fetchone()
  274. cursor.close()
  275. return allowedRole[0]