Skip to content

Instantly share code, notes, and snippets.

@VladimirPal
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VladimirPal/ba55bbd70ddeb92dab46 to your computer and use it in GitHub Desktop.
Save VladimirPal/ba55bbd70ddeb92dab46 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
import json
import tornado.ioloop
import tornado.web
from toredis import Client
import sockjs.tornado
from util.utils import AESCipher
from util.coin_api import config
import run_celery
class RouterConnection(sockjs.tornado.SockJSConnection):
participants = set()
user_id = None
user_type = None
def on_open(self, info):
# Send that someone joined
print '-----'
self.broadcast(self.participants, "Someone joined.")
# Add client to the clients list
self.participants.add(self)
def on_message(self, row_message):
message = json.loads(row_message)
data = message['data']
data_type = message['type']
if data_type == 'auth':
# Проверить на существование пользователя
aes = AESCipher()
token = aes.decrypt(data['token']).split('_')
self.user_id = int(token[0])
self.user_type = token[1]
self.email = token[2]
elif data_type == 'new_credit_wallet':
if self.user_id:
self.send_all_managers(message)
message['type'] = 'notify'
data = {
'html': u'<a href="/admin/credits/%s/">Новая кредитная заявка №%s</a>' %
(data['wallet_id'], data['wallet_id']),
'text': '',
'type': 'success',
'element': '.bottom-left',
'fadeOut': False,
'delay': 0
}
message['data'] = data
self.send_all_managers(message)
elif data_type == 'new_withdraw':
if self.user_id:
self.send_all_managers(message)
message['type'] = 'notify'
data = {
'html': u'<a href="/admin/withdraw/%s/">Новая заявка на вывод №%s</a>' %
(data['withdraw_id'], data['withdraw_id']),
'text': '',
'type': 'success',
'element': '.bottom-left',
'fadeOut': False,
'delay': 0
}
message['data'] = data
self.send_all_managers(message)
elif data_type in ['manager_change_credit', 'manager_change_withdraw']:
if self.user_id:
self.send_all_managers(message)
def on_close(self):
self.participants.remove(self)
def send_all_managers(self, message):
managers = [x for x in self.participants if (x.user_type != 'client' and x.user_id and x.user_id != self.user_id)]
self.broadcast(managers, message)
def rate_change(message):
if message[0] == 'message':
rate = message[2]
data = {
'type': 'rate_change',
'data': json.loads(rate)
}
for client in RouterConnection.participants:
client.broadcast(RouterConnection.participants, data)
break
def redis_event(message):
if message[0] == 'message':
message_dict = json.loads(message[2])
new_msg = {}
try:
new_msg['type'] = message_dict['event']
except KeyError:
pass
if new_msg:
if new_msg['type'] == 'notify':
data = {
'text': message_dict['event_text'],
'event_id': message_dict['event_id'],
'type': message_dict['event_type'],
'element': '.bottom-left',
'fadeOut': False,
'delay': 0
}
new_msg['data'] = data
send_client_email = True
for participant in RouterConnection.participants:
if participant.user_id == message_dict['cid']:
if new_msg:
participant.send(new_msg)
participant.send({'type': message_dict['chaplin_event'], 'data': message_dict})
if send_client_email:
if 'event_text' in message_dict:
email_message = u"""
%s\n
""" % (message_dict['event_text'])
send_email(
{
'email': message_dict['user_email'],
'theme': u'Уведомление LarkBank',
'message': email_message
}
)
def send_email(mail):
pass
# run_celery.send_email.apply_async((mail['email'], mail['theme'], mail['message']))
if __name__ == "__main__":
import logging
logging.getLogger().setLevel(logging.DEBUG)
# 1. Create chat router
ChatRouter = sockjs.tornado.SockJSRouter(RouterConnection, '/sock')
# 2. Create Tornado application
app = tornado.web.Application(ChatRouter.urls)
# 3. Make Tornado app listen on port 8083
try:
address = config.LOCAL_ADDRESS
except AttributeError:
address = '127.0.0.1'
app.listen(port=8083, address=address)
# 4. Start IOLoop
client = Client()
client.connect()
client.subscribe("redis_event", callback=redis_event)
client_rate = Client()
client_rate.connect()
client_rate.subscribe("rate_change", callback=rate_change)
tornado.ioloop.IOLoop.instance().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment