1
0

utils.py 11 KB

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