-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstreamer_resource.py
179 lines (148 loc) · 6.52 KB
/
streamer_resource.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
from flask_restful import Resource, reqparse
from flask import jsonify, abort
from db import db_session
from db.models import *
from loader_controller import ApiError, StreamerController
from flask_login import login_required, current_user
from utils import get_platform
game_parser = reqparse.RequestParser()
game_parser.add_argument('name', required=True, type=str, location='form')
def admin_required(func):
def wrapper(*args, **kwargs):
if current_user.role != 'admin':
return jsonify({'error': 'вы не администратор'})
return func(*args, **kwargs)
return wrapper
def provide_session(func):
def wrapper(*args, **kwargs):
session = db_session.create_session()
try:
result = func(*args, session=session, **kwargs)
session.close()
return result
except:
print('db api error in', func.__name__)
return abort(500)
return wrapper
class GameResource(Resource):
@login_required
@provide_session
def get(self, session=None):
games = session.query(Game).all()
return jsonify([game.to_dict(only=('id', 'name', 'streamers.id', 'streamers.name', 'streamers.activity', 'streamers.is_online')) for game in games])
@login_required
@admin_required
@provide_session
def post(self, session=None):
args = game_parser.parse_args()
game = session.query(Game).filter(Game.name == args.name).one_or_none()
if game:
return jsonify({'error': 'игра с таким названием уже существует'})
game = Game(name=args.name)
session.add(game)
session.commit()
return jsonify(game.to_dict(only=('id', 'name')))
streamer_parser = reqparse.RequestParser()
streamer_parser.add_argument('name', required=True, type=str, location='form')
streamer_parser.add_argument('game', required=True, type=str, location='form')
class StreamerResource(Resource):
@login_required
@provide_session
def get(self, id, session=None):
session = db_session.create_session()
streamer = session.query(Streamer).get(id)
if not streamer:
return jsonify({'error': 'стримера с таким id нет'})
json = streamer.to_dict(only=('id', 'game_id', 'name', 'activity', 'is_online', 'clips.id', 'clips.activity', 'clips.time_created'))
for clip in json['clips']:
clip['image'] = f'static/screenshots/{streamer.name}_{clip["id"]}.jpg'
clip['video'] = f'static/clips/{streamer.name}_{clip["id"]}.mp4'
return jsonify(json)
@login_required
@admin_required
@provide_session
def delete(self, id, session=None):
session = db_session.create_session()
streamer = session.query(Streamer).get(id)
if not streamer:
return jsonify({'error': 'стримера с таким id нет'})
StreamerController().delete_streamer(streamer)
session.delete(streamer)
session.commit()
return jsonify({'success': 'OK'})
class StreamerListResource(Resource):
@login_required
@provide_session
def get(self, session=None):
streamers = session.query(Streamer).order_by(Streamer.activity.desc()).all()
return jsonify([streamer.to_dict(only=('id', 'name', 'platform', 'activity', 'is_online', 'game.id', 'game.name')) for streamer in streamers])
@login_required
@admin_required
@provide_session
def post(self, session=None):
args = streamer_parser.parse_args()
platform, platform_id = get_platform(args.name)
if platform is None:
return jsonify({'error': 'не удалось определить платформу. Проверьте правильность ссылки'})
game = session.query(Game).filter(Game.name == args.game).one_or_none()
if not game:
game = Game(name=args.game)
session.add(game)
streamer = session.query(Streamer).filter(Streamer.platform_id == platform_id).one_or_none()
if streamer:
return jsonify({'error': f'стример с id {platform_id} уже существует'})
controller = StreamerController()
try:
name = controller.check_streamer_exist(platform, platform_id)
if not name:
return jsonify({'error': f'стример с id {platform_id} не найден'})
except ApiError:
return jsonify({'error': 'ошибка в api при проверке пользователя. Повторите попытку.'})
streamer = Streamer(name=name, platform=platform, platform_id=platform_id)
game.streamers.append(streamer)
session.commit()
json = streamer.to_dict(only=('id', 'name', 'platform', 'is_online', 'game.id', 'game.name'))
session.expunge_all()
controller.add_streamer(streamer)
return jsonify(json)
phraze_parser = reqparse.RequestParser()
phraze_parser.add_argument('text', required=True, type=str, location='body')
class PhrazeListResource(Resource):
@login_required
@provide_session
def get(self, session=None):
phrazes = session.query(Trigger).all()
return jsonify([phraze.to_dict(only=('id', 'name')) for phraze in phrazes])
@login_required
@admin_required
@provide_session
def post(self, session=None):
args = phraze_parser.parse_args()
trigger = Trigger(name=args.text)
session.add(trigger)
session.commit()
return jsonify(trigger.to_dict())
class PhrazeResource(Resource):
@login_required
@provide_session
def get(self, id, session=None):
phraze = session.query(Trigger).get(id)
if not phraze:
return jsonify({'error': 'фразы с таким id не существует'})
return jsonify(phraze.to_dict(only=('id', 'name')))
@login_required
@admin_required
@provide_session
def delete(self, id, session=None):
phraze = session.query(Trigger).get(id)
if not phraze:
return jsonify({'error': 'фразы с таким id не существует'})
session.delete(phraze)
session.commit()
return jsonify({'success': 'OK'})
class UserListResource(Resource):
@login_required
@provide_session
def get(self, session=None):
users = session.query(Users).all()
return jsonify([user.to_dict(only=('id', 'login', 'role')) for user in users])