user.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. import csv
  2. from . import DBBit
  3. from .db import DB
  4. from tool.typing import *
  5. from tool.login import create_uid, randomPassword
  6. from tool.time import mysql_time
  7. from core.user import NormalUser, ManagerUser, User
  8. from conf import Config
  9. from . import garbage
  10. def get_rank_for_user(db: DB, limit, offset, order_by: str = "DESC"):
  11. cur = db.search(columns=['UserID', 'Name', 'Score', 'Reputation'],
  12. table='user',
  13. where='IsManager=0',
  14. order_by=[('Reputation', order_by), ('Score', order_by), ('UserID', order_by)],
  15. limit=limit,
  16. offset=offset)
  17. if cur is None:
  18. return None, None
  19. res = []
  20. for index in range(cur.rowcount):
  21. i = cur.fetchone()
  22. res.append((f"{offset + index + 1}", i[1], i[0][:Config.show_uid_len], str(i[3]), str(i[2])))
  23. return res
  24. def update_user_score(where: str, score: score_t, db: DB) -> int:
  25. if len(where) == 0 or score < 0:
  26. return -1
  27. cur = db.update(table="user", kw={"score": score}, where=where)
  28. if cur is None:
  29. return -1
  30. return cur.rowcount
  31. def update_user_reputation(where: str, reputation: score_t, db: DB) -> int:
  32. if len(where) == 0 or reputation <= 1 or reputation >= 1000:
  33. return -1
  34. cur = db.update(table="user", kw={"Reputation": reputation}, where=where)
  35. if cur is None:
  36. return -1
  37. return cur.rowcount
  38. def search_user_by_fields(columns, uid: uid_t, name: uname_t, phone: phone_t, db: DB):
  39. where = ""
  40. if uid is not None:
  41. where += f"UserID=‘{uid}’ AND "
  42. if name is not None:
  43. where += f"Name='{name}' AND "
  44. if phone is not None:
  45. where += f"Phone='{phone}' AND "
  46. if len(where) != 0:
  47. where = where[0:-4] # 去除末尾的AND
  48. return search_from_user_view(columns, where, db)
  49. def search_from_user_view(columns, where: str, db: DB):
  50. cur = db.search(columns=columns,
  51. table="user",
  52. where=where)
  53. if cur is None:
  54. return None
  55. return cur.fetchall()
  56. def find_user_by_id(uid: uid_t, db: DB) -> Optional[User]:
  57. cur = db.search(columns=["UserID", "Name", "IsManager", "Score", "Reputation"],
  58. table="user",
  59. where=f"UserID = '{uid}'")
  60. if cur is None or cur.rowcount == 0:
  61. return None
  62. assert cur.rowcount == 1
  63. res = cur.fetchone()
  64. assert len(res) == 5
  65. uid: uid_t = res[0]
  66. name: uname_t = str(res[1])
  67. manager: bool = res[2] == DBBit.BIT_1
  68. if manager:
  69. return ManagerUser(name, uid)
  70. else:
  71. score: score_t = res[3]
  72. reputation: score_t = res[4]
  73. rubbish: count_t = garbage.count_garbage_by_uid(uid, db)
  74. return NormalUser(name, uid, reputation, rubbish, score) # rubbish 实际计算
  75. def find_user_by_name(name: uname_t, passwd: passwd_t, db: DB) -> Optional[User]:
  76. uid = create_uid(name, passwd)
  77. return find_user_by_id(uid, db)
  78. def is_user_exists(uid: uid_t, db: DB) -> bool:
  79. cur = db.search(columns=["UserID"],
  80. table="user",
  81. where=f"UserID = '{uid}'")
  82. if cur is None or cur.rowcount == 0:
  83. return False
  84. assert cur.rowcount == 1
  85. return True
  86. def update_user(user: User, db: DB, not_commit: bool = False) -> bool:
  87. if not is_user_exists(user.get_uid(), db):
  88. return False
  89. uid = user.get_uid()
  90. info: Dict[str, str] = user.get_info()
  91. is_manager = info['manager']
  92. if is_manager == '1':
  93. cur = db.update(table="user",
  94. kw={"IsManager": is_manager},
  95. where=f"UserID = '{uid}'", not_commit=not_commit)
  96. else:
  97. score = info['score']
  98. reputation = info['reputation']
  99. cur = db.update(table="user",
  100. kw={"IsManager": is_manager,
  101. "Score": f"{score}",
  102. "Reputation": f"{reputation}"},
  103. where=f"UserID = '{uid}'", not_commit=not_commit)
  104. return cur is not None
  105. def create_new_user(name: Optional[uname_t], passwd: Optional[passwd_t], phone: phone_t,
  106. manager: bool, db: DB) -> Optional[User]:
  107. if name is None:
  108. name = f'User-{phone[-6:]}'
  109. if passwd is None:
  110. passwd = randomPassword()
  111. if len(phone) != 11:
  112. return None
  113. uid = create_uid(name, passwd)
  114. if is_user_exists(uid, db):
  115. return None
  116. is_manager = '1' if manager else '0'
  117. cur = db.insert(table="user",
  118. columns=["UserID", "Name", "IsManager", "Phone", "Score", "Reputation", "CreateTime"],
  119. values=f"'{uid}', '{name}', {is_manager}, '{phone}', {Config.default_score}, "
  120. f"{Config.default_reputation}, {mysql_time()}")
  121. if cur is None:
  122. return None
  123. if is_manager:
  124. return ManagerUser(name, uid)
  125. return NormalUser(name, uid, Config.default_reputation, 0, Config.default_score)
  126. def get_user_phone(uid: uid_t, db: DB) -> Optional[str]:
  127. cur = db.search(columns=["Phone"], table="user", where=f"UserID = '{uid}'")
  128. if cur is None or cur.rowcount == 0:
  129. return None
  130. assert cur.rowcount == 1
  131. return cur.fetchall()[0]
  132. def del_user(uid: uid_t, db: DB) -> bool:
  133. cur = db.search(columns=["GarbageID"], table="garbage_time", where=f"UserID = '{uid}'") # 确保没有引用
  134. if cur is None or cur.rowcount != 0:
  135. return False
  136. cur = db.delete(table="user", where=f"UserID = '{uid}'")
  137. if cur is None or cur.rowcount == 0:
  138. return False
  139. assert cur.rowcount == 1
  140. return True
  141. def del_user_from_where_scan(where: str, db: DB) -> int:
  142. cur = db.search(columns=["UserID"], table="user", where=where)
  143. if cur is None:
  144. return -1
  145. return cur.rowcount
  146. def del_user_from_where(where: str, db: DB) -> int:
  147. cur = db.search(columns=["GarbageID"], table="garbage_time", where=where) # 确保没有引用
  148. if cur is None or cur.rowcount != 0:
  149. return False
  150. cur = db.delete(table="user", where=where)
  151. if cur is None:
  152. return -1
  153. return cur.rowcount
  154. def creat_user_from_csv(path, db: DB) -> List[User]:
  155. res = []
  156. with open(path, "r") as f:
  157. reader = csv.reader(f)
  158. first = True
  159. name_index = 0
  160. passwd_index = 0
  161. phone_index = 0
  162. manager_index = 0
  163. for item in reader:
  164. if first:
  165. try:
  166. name_index = item.index('Name')
  167. passwd_index = item.index('Passwd')
  168. phone_index = item.index('Phone')
  169. manager_index = item.index('Manager')
  170. except (ValueError, TypeError):
  171. return []
  172. first = False
  173. continue
  174. name = item[name_index]
  175. passwd = item[passwd_index]
  176. phone = item[phone_index]
  177. if item[manager_index].upper() == "TRUE":
  178. is_manager = True
  179. elif item[manager_index].upper() == "FALSE":
  180. is_manager = False
  181. else:
  182. continue
  183. user = create_new_user(name, passwd, phone, is_manager, db)
  184. if user is not None:
  185. res.append(user)
  186. return res
  187. def creat_auto_user_from_csv(path, db: DB) -> List[User]:
  188. res = []
  189. with open(path, "r") as f:
  190. reader = csv.reader(f)
  191. first = True
  192. phone_index = 0
  193. for item in reader:
  194. if first:
  195. try:
  196. phone_index = item.index('Phone')
  197. except (ValueError, TypeError):
  198. return []
  199. first = False
  200. continue
  201. phone = item[phone_index]
  202. user = create_new_user(None, None, phone, False, db)
  203. if user is not None:
  204. res.append(user)
  205. return res
  206. def count_all_user(db: DB):
  207. cur = db.search(columns=['count(UserID)'], table='user')
  208. if cur is None:
  209. return 0
  210. assert cur.rowcount == 1
  211. return int(cur.fetchone()[0])