def pay_notify(request): data = json.loads(request.body) cl = Client(settings.CENTRIFUGO_HOST, api_key=settings.CENTRIFUGO_API_KEY, timeout=1) status = data['event'] if status == 'refund.succeeded': return Response(status.HTTP_200_OK) order_id = int(data["object"]["description"].split("№")[1]) cl.publish(f'payment{order_id}', status) try: order = Order.objects.get(pk=order_id) except exceptions.ObjectDoesNotExist: return Response(status.HTTP_200_OK) if status == 'payment.succeeded': order.pay_notified = True order.paid = True send_template_email(subject=f'[HRSMNT] Заказ №{order_id}', template='emails/paid.html', context={'order_id': order_id}, to=[order.email]) elif status == 'payment.canceled': order.pay_notified = True order.save() response = HttpResponse() response.status_code = 200 return response
def post(self, request, channel_key): channels = Channel.objects.filter(key=channel_key, status=Channel.AVAILABLE) if not channels: return Response('Channel doesn\'t exist.', status=status.HTTP_404_NOT_FOUND) channel = channels[0] if channel.subscribers.filter(id=request.user.id): channel.subscribers.remove(request.user) response = { 'channel_key': channel.key, 'name': channel.name, 'is_active': False, } client = Client(settings.CENTRIFUGO_URL, api_key=settings.CENTRIFUGO_API_KEY, timeout=1) channel = f"subscriptions#{request.user.id}" client.publish(channel, response) return Response(response, status=status.HTTP_200_OK)
def publish_py(message, channel=None, event_class="default", data=None, site=SITE_NAME, target=None): cent_url = CENTRIFUGO_HOST + ":" + str(CENTRIFUGO_PORT) if CENTRIFUGO_PROXY is True: cent_url = CENTRIFUGO_HOST client = Client(cent_url, SECRET_KEY, timeout=1) channel = _get_channel(channel, target) if data is None: data = {} payload = { "message": message, "channel": channel, 'event_class': event_class, "data": data, "site": site } err = None try: client.publish(channel, payload) except CentException as e: err = str(e) if event_class.lower() == "debug": print("[DEBUG] ", str(json.dumps(payload))) return err
class CentClient(object): def __init__(self): print('Init connection') self.con = Client(CENT_URL, api_key=CENT_KEY, timeout=1) def send(self, token, message): self.con.publish(token, message)
def create_vote_for_object(obj_type, user_id, obj_id, mark): # TODO: make global client = Client('http://127.0.0.1:8000', api_key=app_settings.CENTRIFUGO_API_KEY, timeout=1) if obj_type == 'question': # TODO: current rating instead of mark! client.publish('question_vote', { 'user_id': user_id, 'question_id': obj_id, 'mark': mark }) return QuestionVote.objects.create(user_id=user_id, related_object_id=obj_id, mark=mark) else: # TODO: ограничить канал client.publish('answers_vote', { 'user_id': user_id, 'answer_id': obj_id, 'mark': mark }) return AnswerVote.objects.create(user_id=user_id, related_object_id=obj_id, mark=mark)
def delete_comment(request): comment_id = request.GET.get('comment_id') comment = request.user.comment_set.filter(pk=comment_id) if comment: comment.delete() data = {'type': 'del-comment', 'id': comment_id} client = Client(url, secret_key, timeout=1) client.publish('comment', data) status = 'ok' else: status = 'error' return JsonResponse({'status': status})
def question_page(request, pk): try: question = Question.objects.get(id=pk) except ObjectDoesNotExist: # question doesn't exist, should show 404 return render(request, '404_not_found.html') answers = question.answers.best_answers() answers = [add_vote_to_object(answer, request.user) for answer in answers] page = paginate(answers, request, 20) if not request.user.is_authenticated: # showing page without answer form return render( request, 'question_page.html', { 'question': add_vote_to_object(question, request.user), 'page_obj': page }) # формируем token для фронтенда channel_id = str(question.id) token = jwt.encode({"sub": channel_id}, app_settings.CENTRIFUGO_SECRET_KEY) if request.method == 'GET': form = AnswerForm() else: form = AnswerForm(data=request.POST) if form.is_valid(): answer = form.save(commit=False) answer.author = request.user.profile answer.related_question = question answer.save() response = redirect( reverse('question_page', kwargs={'pk': question.id})) response['Location'] += f'#ans{answer.id}' client = Client('http://127.0.0.1:8000', api_key=app_settings.CENTRIFUGO_API_KEY, timeout=1) client.publish('new_answer', {}) return response return render( request, 'question_page.html', { 'question': add_vote_to_object(question, request.user), 'page_obj': page, 'form': form, 'jwt_token': token })
def send_centrifuge(point): client = Client( getattr(settings, 'CENTRIFUGE_URL'), api_key=getattr(settings, 'CENTRIFUGE_APIKEY'), timeout=getattr(settings, 'CENTRIFUGE_TIMEOUT'), ) dict_point = ObjectSerializer(point).data if point.author is not None: dict_point['author'] = point.author.username try: client.publish('latest_points', dict_point) except CentException: return False return True
def post(self, request, video_key): if 'value' not in request.data or request.data['value'] not in [ -1, 0, 1 ]: return Response('Invalid request (or rating value).', status=status.HTTP_400_BAD_REQUEST) new_value = request.data['value'] ratings = Rating.objects.filter(video__key=video_key, video__status=Video.PUBLIC) if not ratings: return Response('Video doesn\'t exist.', status=status.HTTP_404_NOT_FOUND) rating = ratings[0] records = rating.records.filter(author=request.user) if not records: rating.counter += new_value record = RatingRecord(author=request.user, rating=rating, value=new_value) else: record = records[0] if record.value != new_value: if new_value == 0: rating.counter -= record.value elif record.value == 0: rating.counter += new_value else: rating.counter += 2 * new_value record.value = new_value record.save() rating.save() response = { 'counter': rating.counter, } client = Client(settings.CENTRIFUGO_URL, api_key=settings.CENTRIFUGO_API_KEY, timeout=1) channel = f"video/{video_key}/rating" client.publish(channel, response) return Response(response, status=status.HTTP_200_OK)
def check_favorites(request): dish_pk = request.GET['dish_pk'] dish = get_object_or_404(Dish, pk=dish_pk) favorite = dish.favorite_set.filter(author=request.user) if not favorite: dish.favorite_set.create(author=request.user) is_favorited = True type = 'favorite' else: dish.favorite_set.get(author=request.user).delete() is_favorited = False type = 'unfavorite' client = Client(url, secret_key, timeout=1) data = {"type": type, 'id': dish_pk} client.publish('home', data) return JsonResponse({'is_favorited': is_favorited})
def post(self, request, channel_key, video_key): channels = Channel.objects.filter(key=channel_key, status=Channel.AVAILABLE) if not channels: return Response("Wrong channel key.", status=status.HTTP_400_BAD_REQUEST) channel = channels[0] video = Video.objects.filter(key=video_key, status=Video.PUBLIC, owner=channel.owner) if not video: return Response("Wrong video key.", status=status.HTTP_400_BAD_REQUEST) video = video[0] serializer = CommentSerializer(data=request.data) if serializer.is_valid(): print(request.data) if 'parent_id' not in request.data or not request.data['parent_id']: parent = None else: parents = video.comments.filter(id=request.data['parent_id']) if not parents: return Response("Wrong comments id.", status=status.HTTP_400_BAD_REQUEST) parent = parents[0] comment = serializer.create() comment.video = video comment.author = request.user comment.parent = parent comment.save() client = Client(settings.CENTRIFUGO_URL, api_key=settings.CENTRIFUGO_API_KEY, timeout=1) channel = f"video/{video_key}/comments" data = { 'id': comment.id, 'author': comment.author.username, 'text': comment.text, 'created': str(comment.created), 'hide_children': False, 'children': [], 'parent_id': parent.id if parent else None, } client.publish(channel, data) return Response({ 'key': comment.id }, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class Centrifugo: def __init__(self): self.url = 'http://localhost:8000' file = open('../centrifugo/config.json', 'r') config = json.load(file) self.api_key = config['api_key'] file.close() self.client = Client(self.url, api_key=self.api_key, timeout=1) def run(self): channel = 'public:chat' data = {'input': 'test'} self.client.publish(channel, data) def send(self, chat_id, user_id, msg): channel = 'public:chat' data = {'chat_id': chat_id, 'user_id': user_id, 'msg': msg} self.client.publish(channel, data)
def publish_py(message, channel=None, event_class="default", data=None, site=SITE_NAME, target=None): cent_url = CENTRIFUGO_HOST + ":" + str(CENTRIFUGO_PORT) if CENTRIFUGO_PROXY is True: cent_url = CENTRIFUGO_HOST client = Client(cent_url, SECRET_KEY, timeout=1) channel = _get_channel(channel, target) if data is None: data = {} payload = {"message": message, "channel": channel, 'event_class': event_class, "data": data, "site": site} err = None try: client.publish(channel, payload) except CentException as e: err = str(e) if event_class.lower() == "debug": print("[DEBUG] ", str(json.dumps(payload))) return err
class CentrifugoClient: client: Client = None def init_app(self, url, api_key): self.client = Client(url, api_key=api_key, timeout=1, verify=False) @do_not_execute(return_value=None, raised_exception=False) def send_problem_run_updates(self, problem_id: int, run: Run): current_app.logger.debug( f'CentrifugoClient: send update for problem {problem_id}') channel = f'problem.{problem_id}' try: self.client.publish(channel, {'run': run.serialize()}) except AttributeError: current_app.logger.exception( f'CentrifugoClient: client is not initialized') except CentException: current_app.logger.exception( f'CentrifugoClient: can\'t send message to centrifugo')
def add_comment(request): if request.method == 'POST': dish_pk = request.POST.get('dish_id') form = CommentForm(request.POST) if form.is_valid(): comment = Comment() comment.text = bleach.clean(request.POST.get('text')) comment.author = request.user comment.dish_id = dish_pk comment.save() data = { 'type': 'new-comment', 'comment_pk': comment.pk, 'text': comment.text, 'author': request.user.username, 'avatar': request.user.profile.avatar.url, 'created_at': str(comment.created_at) } client = Client(url, secret_key, timeout=1) client.publish('comment', data) return JsonResponse({'status': 'ok'})
def post(self, request, video_key): video = Video.objects.filter(key=video_key, status=Video.PUBLIC) if not video: return Response('Video doesn\'t exist.', status=status.HTTP_404_NOT_FOUND) views = video[0].views views.counter += 1 views.save() response = { 'counter': views.counter, } client = Client(CENTRIFUGO_URL, api_key=CENTRIFUGO_API_KEY, timeout=1) channel = f"video/{video_key}/views" client.publish(channel, response) return Response(response, status=status.HTTP_200_OK)
def check_likes(request): obj_pk = request.GET['obj_pk'] obj_type = request.GET['obj_type'] if obj_type == 'comment': obj = get_object_or_404(Comment, pk=obj_pk) elif obj_type == 'dish': obj = get_object_or_404(Dish, pk=obj_pk) like = obj.likes.filter(author=request.user) if not like: obj.likes.create(author=request.user) is_liked = True type = 'like' else: obj.likes.get(author=request.user).delete() is_liked = False type = 'unlike' client = Client(url, secret_key, timeout=1) data = {"type": type, 'id': obj_pk} if obj_type == 'dish': client.publish('home', data) elif obj_type == 'comment': client.publish('comment', data) return JsonResponse({'is_liked': is_liked})
def main(): result = dict( changed=False, message=[] ) module = AnsibleModule( argument_spec=dict( url=dict(required=True), secret=dict(required=True), data=dict(required=True), channel=dict(required=True) ) ) if module.check_mode: return result url = module.params.get('url') secret = module.params.get('secret') data = module.params.get('data') data = json.loads(data.replace("'", '"')) channel = module.params.get('channel') client = Client(url, secret, timeout=1) try: response = client.publish(channel, data) result['message'].append(response) module.exit_json(**result) return True except Exception as e: module.fail_json(msg=str(e)) return False
args = parser.parse_args() print(args) # centrifugo url = "http://localhost:" + args.__dict__['p'] json_data = open(args.__dict__['c']).read() data = json.loads(json_data) api_key = data['api_key'] client = Client(url, api_key=api_key, timeout=5) inject.configure(base_config) inspector = BlockInspector() while True: block = inspector.get_next_block() txs = import_block(block) for txsData in txs: print(txs) for key in txsData.totals: u_channel = "totals#" + key c_clients = client.presence(u_channel) print(txsData.totals) if len(c_clients) > 0: for key1 in txsData.totals[key]: data = txsData.totals[key][key1] print(u_channel) client.publish(u_channel, data)