2021的特普通奖
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

316 lines
8.8 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. # -*- coding: utf-8 -*-
  2. from datetime import datetime
  3. from functools import wraps
  4. from flask import (Flask, request, render_template, send_from_directory, abort,
  5. redirect, session, Blueprint, url_for)
  6. from flask_sqlalchemy import SQLAlchemy
  7. from flask_limiter import Limiter
  8. from flask_limiter.util import get_remote_address
  9. from mastodon import Mastodon
  10. import random
  11. from config import C
  12. WRONG_ANS_HTML = '''<html>
  13. <head>
  14. <meta charset='UTF-8'>
  15. <meta name='viewport' content='width=device-width initial-scale=1'>
  16. <title></title>
  17. </head>
  18. <body>
  19. <h1></h1>
  20. <a href="##" onclick="window.history.back()">退</a>
  21. </body>
  22. </html>
  23. '''
  24. MIN_LIKE_NUM = 10
  25. app = Flask(__name__)
  26. app.config.from_object('config.C')
  27. app.secret_key = C.session_key
  28. MAST_LOGIN_URL = Mastodon(api_base_url=C.mast_base_uri).auth_request_url(
  29. client_id = C.mast_client_id,
  30. redirect_uris = C.mast_redirect_uri, scopes = ['read:accounts']
  31. )
  32. limiter = Limiter(
  33. app,
  34. key_func=get_remote_address,
  35. default_limits=["50 / minute"],
  36. )
  37. db = SQLAlchemy(app)
  38. class Story(db.Model):
  39. id = db.Column(db.Integer, primary_key=True)
  40. title = db.Column(db.String(30))
  41. avatar = db.Column(db.String(128))
  42. text = db.Column(db.Text)
  43. tail = db.Column(db.Integer) # 最后一个 Paragraph 的 id
  44. total_like_num = db.Column(db.Integer, default=0)
  45. is_tree = db.Column(db.Boolean, default=False)
  46. def text_abstract(self, limit=200):
  47. return self.text[:limit] + ("..." if len(self.text) > limit else "")
  48. class Paragraph(db.Model):
  49. id = db.Column(db.Integer, primary_key=True)
  50. parent_id = db.Column(db.Integer, default=0, index=True)
  51. story_id = db.Column(db.Integer, index=True)
  52. is_hidden = db.Column(db.Boolean, default=False)
  53. is_chosen = db.Column(db.Boolean, default=False)
  54. text = db.Column(db.Text)
  55. author = db.Column(db.String(30))
  56. time = db.Column(db.DateTime, default=datetime.now)
  57. like_num = db.Column(db.Integer, default=0, index=True)
  58. angry_num = db.Column(db.Integer, default=0)
  59. fun_num = db.Column(db.Integer, default=0)
  60. sweat_num = db.Column(db.Integer, default=0)
  61. @property
  62. def create_at(self):
  63. return self.time.strftime("%m-%d %H:%M")
  64. def reaction_status(self):
  65. user = session.get('username')
  66. return list(zip(
  67. '👍😡🤣😅👎',
  68. [self.like_num, self.angry_num, self.fun_num, self.sweat_num, 0],
  69. [
  70. user and bool(Reaction.query.filter_by(pid=self.id, user=user, kind=i).first())
  71. for i in range(1, 6)
  72. ],
  73. range(1, 6)
  74. ))
  75. class Reaction(db.Model):
  76. id = db.Column(db.Integer, primary_key=True)
  77. kind = db.Column(db.SmallInteger) # 1: like 2: angry 3: funny 4: sweat 5:dislike
  78. pid = db.Column(db.Integer, index=True) # id of paragraph
  79. user = db.Column(db.String(30)) # username of user
  80. def choose_new_next(min_like_num=MIN_LIKE_NUM):
  81. for story in Story.query.filter_by(is_tree=False).all():
  82. last_paragraph_id = story.tail
  83. next_one = Paragraph.query.filter_by(story_id=story.id, parent_id=last_paragraph_id, is_hidden=False)\
  84. .order_by(Paragraph.like_num.desc()).first()
  85. if next_one and next_one.like_num >= min_like_num:
  86. story.text += next_one.text
  87. story.total_like_num += next_one.like_num
  88. story.tail = next_one.id
  89. next_one.is_chosen = True
  90. for story in Story.query.filter_by(is_tree=True).all():
  91. _max = story.total_like_num
  92. _tail = story.tail
  93. _sum_dict = {}
  94. def _get_like_sum(p):
  95. if p.id in _sum_dict:
  96. return _sum_dict[p.id]
  97. s = p.like_num + (p.parent_id and _get_like_sum(Paragraph.query.get(p.parent_id)))
  98. _sum_dict[p.id] = s
  99. return s
  100. for p in Paragraph.query.filter(Paragraph.like_num >= min_like_num)\
  101. .filter_by(story_id=story.id, is_hidden=False).all():
  102. if _get_like_sum(p) > _max:
  103. _max = _get_like_sum(p)
  104. _tail = p.id
  105. p = Paragraph.query.get(_tail)
  106. _text = p.text
  107. while p.parent_id:
  108. p = Paragraph.query.get(p.parent_id)
  109. _text = p.text + _text
  110. story.total_like_num = _max
  111. story.tail = _tail
  112. story.text = _text
  113. db.session.commit()
  114. def sample_question(qs, n=3):
  115. random.seed(session['uid'])
  116. return random.sample(qs, n)
  117. def login_required(func):
  118. @wraps(func)
  119. def warp(*args, **kwargs):
  120. if not session.get('username'):
  121. abort(403)
  122. return func(*args, **kwargs)
  123. return warp
  124. bp = Blueprint('main_bp', __name__, url_prefix='/ordinary')
  125. @bp.before_request
  126. def set_uid():
  127. if 'uid' not in session:
  128. session['uid'] = random.randint(0, 10000000)
  129. @bp.route('/static/<path:path>')
  130. def send_static(path):
  131. return send_from_directory('static/', path)
  132. @bp.route('/guest_login', methods=['POST'])
  133. @limiter.limit("5 / hour")
  134. def guest_login():
  135. for name, ques, hint, ans in sample_question(C.verify_questions):
  136. if request.form.get(name) != ans:
  137. return WRONG_ANS_HTML, 401
  138. session['username'] = 'guest<%s>' % session['uid']
  139. session.pop('avatar', None)
  140. session.permanent = True
  141. return redirect(request.referrer)
  142. @bp.route('/mast_auth')
  143. def mast_login_auth():
  144. code = request.args.get('code')
  145. client = Mastodon(
  146. client_id=C.mast_client_id,
  147. client_secret=C.mast_client_sec,
  148. api_base_url=C.mast_base_uri
  149. )
  150. client.log_in(code=code, redirect_uri=C.mast_redirect_uri,
  151. scopes=['read:accounts'])
  152. info = client.account_verify_credentials()
  153. session['username'] = info.acct
  154. session['avatar'] = info.avatar
  155. session.permanent = True
  156. return redirect('.')
  157. @bp.route('/logout')
  158. def logout():
  159. session.pop('username', None)
  160. session.pop('avatar', None)
  161. return redirect('.')
  162. @bp.route('/')
  163. def home():
  164. stories = Story.query.order_by(Story.total_like_num.desc()).all()
  165. return render_template('home.html', **locals())
  166. @bp.route('/<int:story_id>')
  167. def story(story_id):
  168. story = Story.query.get_or_404(story_id)
  169. is_tree = story.is_tree
  170. if is_tree:
  171. tail = request.args.get('tail', story.tail, type=int)
  172. p_tail = Paragraph.query.get_or_404(tail)
  173. if p_tail.story_id != story_id:
  174. abort(404)
  175. paragraph_part = [p_tail]
  176. p = p_tail
  177. while p.parent_id:
  178. p = Paragraph.query.get_or_404(p.parent_id)
  179. paragraph_part.insert(0, p)
  180. else:
  181. tail = story.tail
  182. paragraph_part = Paragraph.query.filter_by(
  183. story_id=story_id, is_chosen=True, is_hidden=False
  184. ).all()
  185. sort_by = request.args.get('sort_by', 'time')
  186. q = Paragraph.query.filter_by(story_id=story_id, parent_id=tail, is_hidden=False)
  187. q = q.order_by(Paragraph.like_num.desc() if sort_by == 'like' else
  188. Paragraph.id.desc())
  189. pagination = q.paginate(max_per_page=100)
  190. username = session.get('username', '')
  191. avatar = session.get('avatar', C.guest_avatar)
  192. cs_login_url = MAST_LOGIN_URL
  193. guest_login_url = url_for('main_bp.guest_login')
  194. verify_questions = sample_question(C.verify_questions)
  195. min_like_num = MIN_LIKE_NUM
  196. email = C.email
  197. return render_template('story.html', **locals())
  198. @bp.route('/create', methods=['POST'])
  199. @login_required
  200. @limiter.limit("66 / hour")
  201. def create():
  202. story_id = request.form.get('story-id')
  203. text = request.form.get('text')
  204. if not text or len(text) > 140:
  205. abort(422)
  206. story = Story.query.get_or_404(story_id)
  207. if story.is_tree:
  208. parent_id = request.form.get('tail', type=int)
  209. else:
  210. parent_id = story.tail
  211. p = Paragraph(
  212. parent_id=parent_id,
  213. story_id=story_id,
  214. text=text,
  215. author=session['username']
  216. )
  217. db.session.add(p)
  218. db.session.commit()
  219. return redirect(story_id)
  220. @bp.route('/react', methods=['POST'])
  221. @login_required
  222. @limiter.limit("100 / minute")
  223. def react():
  224. kind = request.form.get('kind', type=int)
  225. pid = request.form.get('pid', type=int)
  226. if kind not in range(1, 6):
  227. abort(422)
  228. p = Paragraph.query.get_or_404(pid)
  229. d = dict(kind=kind, user=session['username'], pid=pid)
  230. if Reaction.query.filter_by(**d).first():
  231. return ''
  232. db.session.add(Reaction(**d))
  233. n = ''
  234. if kind == 1:
  235. p.like_num += 1
  236. n = p.like_num
  237. elif kind == 2:
  238. p.angry_num += 1
  239. n = p.angry_num
  240. elif kind == 3:
  241. p.fun_num += 1
  242. n = p.fun_num
  243. elif kind == 4:
  244. p.sweat_num += 1
  245. n = p.sweat_num
  246. db.session.commit()
  247. return str(n)
  248. app.register_blueprint(bp)
  249. if __name__ == '__main__':
  250. app.run(debug=True)