#!/usr/bin/env python # -*- coding: utf-8 -*- # 推送信息构建 from collections import ( Counter, defaultdict, ) from itertools import chain from django.conf import settings from gm_protocol import GmProtocol from gm_rpcd.internals.exceptions import RPCDFaultException from gm_types.gaia import ( GM_PROTOCOL_JUMP_SOURCE, INDEX_CARD_TYPE, ) from gm_types.mimas import ( PUSH_ACTION_TYPE, ) from gm_types.push import ( AUTOMATED_PUSH, PUSH_INFO_TYPE) from gm_upload.utils.image_utils import Picture from talos.models.diary import DiaryTagV3, DiaryTag, Diary from talos.models.topic import Problem, TopicImage from talos.models.tractate import TractateImages, TractateTagV3, TractateTag from talos.services import UserService, TagV3Service, TagService from talos.services.tractate import TractateService from utils.common import gm_decode_html from utils.protocol import gm_protocol from social.models import SocialInfo from .push_base import ( hour, minute, ParamsBuilderBase, ) from qa.models import ( Answer, AnswerVote, AnswerReply, Question, AnswerImage, QuestionImage, AnswerTagV3, ) from social.models import UserFollow from .tag_v3_2_group_topic import Tag2GroupTopic class TimelyPushParamsBuilder(ParamsBuilderBase): """ 及时推送构建 """ # 以下是具体的各种推送逻辑 @classmethod def answer_vote(cls, **kwargs): """ :return: """ answer_id = kwargs.get("answer_id", 0) content = kwargs.get("content", "") user_ids = kwargs.get("user_ids", []) user_nick_name = kwargs.get("nick_name", "") # alert = u'{}赞了你的回复{}'.format( # user_nick_name, cls.truncate_push_content(content, limit=25)) # alert = u"你的回复收到了一个点赞,快去看看吧>>" # 2019.01.09 灌水推送文案调整 # push_url = gm_protocol.get_answer_list(answer=answer_id) # 2020.01.15 灌水推送文案调整 # 2020.01.27 更新,数量改为点赞总数 social_info = SocialInfo(uid=user_ids[0]) question = Question.objects.filter(pk=kwargs.get('question_id', 0)).first() vote_nums = AnswerVote.objects.filter( answer_id=answer_id ).count() title = "@{}刚刚给你点了新赞同".format(user_nick_name) alert = "你在「{question_title}」下的回答已获得{vote_nums}位朋友点赞,并有{fans_num}个人已经关注了你,快看看他们是谁吧>>".format( question_title=cls.truncate_push_content( rich_text=(question and question.title or "") ), fans_num=(social_info.fans_count or 1), vote_nums=(vote_nums or 1) ) push_url = gm_protocol.get_index_type_info(type_k="message", source=GM_PROTOCOL_JUMP_SOURCE.KYC_PUSH) return cls._build_params(**{ "alert": alert, "push_url": push_url, "push_type": AUTOMATED_PUSH.ANSWER_GET_VOTE, "others": { "title": title, "alert": alert, }, }) @classmethod def create_answer_push_to_fans(cls, **kwargs): """ 创建回答, 推给粉丝 :return: """ user_ids = kwargs.get("user_ids", []) answer_id = kwargs.get("answer_id", 0) question_title = kwargs.get("question_title", "") user_nick_name = kwargs.get("nick_name", "") if user_nick_name.startswith(u'更美用户'): user_nick_name = u'匿名美人' alert = u'你关注的 @{user_name} 刚刚在“{question_name}”下进行了回答'.format( user_name=user_nick_name, question_name=question_title) return cls._build_params(**{ "alert": alert, "push_url": gm_protocol.get_answer_list(answer=answer_id), "push_type": AUTOMATED_PUSH.FOLLOWED_USER_IS_ANSWER_A_POST, }) @classmethod def create_answer_push_to_question_author(cls, **kwargs): """ 创建回答, 推给问题的作者 :return: """ user_ids = kwargs.get("user_ids", []) answer_id = kwargs.get("answer_id", 0) question_title = kwargs.get("question_title", "") user_nick_name = kwargs.get("nick_name", "") alert = u'{user_name} 刚刚回答了你的问题"{question_title}"'.format( user_name=user_nick_name, question_title=question_title), return cls._build_params(**{ "alert": alert, "push_url": gm_protocol.get_answer_list(answer=answer_id), "labels": { 'event_type': 'push', 'event': 'question_received_answer', }, "push_type": AUTOMATED_PUSH.QUESTION_POSTED_ANSWER, }) @classmethod def create_answer_reply_push_to_commented_author(cls, **kwargs): """ 回答创建评论,推给被评论者。如果是一级评论则推给回答作者 :return: """ user_ids = kwargs.get("user_ids", []) user_nick_name = kwargs.get("nick_name", "") content = kwargs.get("content", "") answer_id = kwargs.get("answer_id", 0) comment_id = kwargs.get("comment_id", 0) is_commented_reply = kwargs.get("is_commented_reply", False) # alert = u'{author_name}评论了你:{content}'.format( # author_name=user_nick_name, # content=cls.truncate_push_content(content, limit=25) # ) # alert = u"您有1条新评论,快来看看吧>>" # 2019.01.09 灌水推送文案调整 # 2020.01.15 灌水推送文案调整 # 2020.01.27 更新 数量改成一级评论总数 question = Question.objects.filter(pk=kwargs.get('question_id', 0)).first() first_reply_nums = AnswerReply.objects.filter( answer_id=answer_id, is_online=True, first_reply=None ).count() title = "@{}刚刚给你写了新评论".format(user_nick_name) alert = "你对「{question_title}」的回答已经获得了{reply_nums}条评论,快来看看吧>>".format( question_title=cls.truncate_push_content( rich_text=(question and question.title or "") ), reply_nums=(first_reply_nums or 1) ) push_url = gm_protocol.get_index_type_info(type_k="message", source=GM_PROTOCOL_JUMP_SOURCE.KYC_PUSH) if is_commented_reply: # push_url = gm_protocol.get_answer_reply_list( # answer=answer_id, # comment_id=comment_id # ) push_type = AUTOMATED_PUSH.COMMENT_RECEIVED_REPLY else: # push_url = gm_protocol.get_answer_list( # answer=answer_id, # comment_id=comment_id, # is_push=1 # ) push_type = AUTOMATED_PUSH.ANSWER_RECEIVED_COMMENTS return cls._build_params(**{ "alert": alert, "push_url": push_url, "labels": { 'event_type': 'push', 'event': 'received_qa_comments', }, "push_type": push_type, "others": { "title": title, "alert": alert, }, }) @classmethod def user_add_follow(cls, **kwargs): """ 用户加关注 :return: """ user_ids = kwargs.get("user_ids", []) user_id = user_ids and user_ids[0] or 0 # alert = u'{user_name}关注了你,你在站内贡献得到了更多人喜欢~'.format( # user_name=kwargs.get("user_name", "") # ) # alert = u"有新的小伙伴关注了你,去看看ta是谁>>" # 2019.01.09 灌水推送文案调整 # push_url = user_ids and gm_protocol.get_fan_lst(f_type='fans', user_id=user_id) or "" # 2020.01.15 灌水推送文案调整 social_info = SocialInfo(uid=user_id) title = "@{}刚刚关注了你".format(kwargs.get("user_name", "")) alert = u"已经有{}位朋友关注你了,快来看看他们是谁吧>>".format(social_info.fans_count or 1) push_url = gm_protocol.get_index_type_info(type_k="message", source=GM_PROTOCOL_JUMP_SOURCE.KYC_PUSH) return cls._build_params(**{ "alert": alert, "push_url": push_url, "push_type": AUTOMATED_PUSH.USER_IS_CONCERNED, "others": { "title": title, "alert": alert, }, }) class AggregationPushParamsBuilder(ParamsBuilderBase): """ 聚合推送构建 """ @classmethod def __get_valid_info_by_answer_ids(cls, answer_ids): """ 通过回答id,获取有效的数据 :param answer_ids: :return: """ result = { "mix_dic": {}, "total_count": 0, } if not answer_ids: return result _infos = Answer.objects.filter( pk__in=answer_ids, is_online=True, question__is_online=True, ).using(settings.SLAVE_DB_NAME).values("id", "question_id", "question__title") _mix_dic = {} for item in _infos: _q_id = item["question_id"] if _q_id not in _mix_dic: _mix_dic[_q_id] = { "answer_ids": [], "title": item["question__title"], } _mix_dic[_q_id]["answer_ids"].append(item["id"]) valid_answer_ids = [info.get("answer_ids", []) for info in _mix_dic.values()] cos = Counter(answer_ids) _nums = sum(cos.get(a_id, 0) for a_id in chain(*valid_answer_ids)) return { "mix_dic": _mix_dic, "total_count": _nums, } @classmethod def aggregation_answer_vote(cls, **kwargs): """ 回答点赞聚合 :param kwargs: :return: """ record_ids = kwargs.get("record_ids", []) if not all([record_ids, kwargs.get("user_ids", [])]): return answer_ids = list(AnswerVote.objects.filter( pk__in=record_ids, unread=True ).using(settings.SLAVE_DB_NAME).values_list("answer_id", flat=True)) # 获取未读的回答数量 alert_text = "" _info_dic = cls.__get_valid_info_by_answer_ids(answer_ids) _mix_dic = _info_dic.get("mix_dic", {}) _vote_nums = _info_dic.get("total_count", 0) if len(_mix_dic) > 1: alert_text = "刚刚有{nums}个用户点赞了你的内容,快来看看吧>>".format(nums=_vote_nums) elif len(_mix_dic) == 1: alert_text = "你在「{question_title}」下的回答已获得{nums}位朋友点赞,快看看他们是谁吧>>".format( question_title=cls.truncate_push_content( list(_mix_dic.values())[0].get("title", ""), limit=24 ), nums=_vote_nums ) if alert_text: return cls._build_params(**{ "user_ids": kwargs.get("user_ids", []), "push_url": gm_protocol.get_index_type_info(type_k="message"), "alert": alert_text, "push_type": AUTOMATED_PUSH.ANSWER_GET_VOTE, }) @classmethod def aggregation_answer_reply(cls, **kwargs): """ 回答评论聚合 :param kwargs: :return: """ record_ids = kwargs.get("record_ids", []) if not all([record_ids, kwargs.get("user_ids", [])]): return answer_ids = list(AnswerReply.objects.filter( pk__in=record_ids, is_read=False ).using(settings.SLAVE_DB_NAME).values_list("answer_id", flat=True)) # 获取未读的回答数量 alert_text = "" _info_dic = cls.__get_valid_info_by_answer_ids(answer_ids) _mix_dic = _info_dic.get("mix_dic", {}) _reply_nums = _info_dic.get("total_count", 0) if len(_mix_dic) > 1: alert_text = "刚刚有{nums}个用户评论了你的内容,快来看看吧>>".format(nums=_reply_nums) elif len(_mix_dic) == 1: alert_text = "你对「{question_title}」的回答已经获得了{nums}条评论,快来看看吧>>".format( question_title=cls.truncate_push_content( list(_mix_dic.values())[0].get("title", ""), limit=24 ), nums=_reply_nums ) if alert_text: return cls._build_params(**{ "user_ids": kwargs.get("user_ids", []), "push_url": gm_protocol.get_index_type_info(type_k="message"), "alert": alert_text, "push_type": AUTOMATED_PUSH.ANSWER_RECEIVED_COMMENTS, }) @classmethod def aggregation_user_add_follow(cls, **kwargs): """ 用户增加关注聚合 :param kwargs: :return: """ user_ids = kwargs.get("user_ids", []) record_ids = kwargs.get("record_ids", []) if all([user_ids, record_ids]): counts = UserFollow.objects.filter( pk__in=record_ids, follow_id=user_ids[0], bond=True).using(settings.SLAVE_DB_NAME).count() if counts: alert = "刚刚有{}个用户关注了你,快来看看他们是谁吧>>".format(counts) return cls._build_params(**{ "user_ids": user_ids, "alert": alert, "push_url": user_ids and gm_protocol.get_fan_lst(f_type='fans', user_id=user_ids[0]) or "", "push_type": AUTOMATED_PUSH.USER_IS_CONCERNED, }) class PushEvents(object): """ push事件 """ push_control = settings.PUSH_RATE_LIMIT_SETTINGS.get("sub_control", {}) # 实时推送配置 timely_push_handlers = { PUSH_ACTION_TYPE.ANSWER_RECV_VOTE: { # 回答点赞 "params_builder": TimelyPushParamsBuilder.answer_vote, "limit_rate": True, # 单位时间控制 速率限制开关 "limit_whole": True, # 总时间控制 速率限制开关 "rate_limit_unit_times": push_control.get("answer_vote"), # 单位时间内推送次数控制 }, PUSH_ACTION_TYPE.ANSWER_RECV_REPLY: { # 回答下发评论 "params_builder": TimelyPushParamsBuilder.create_answer_reply_push_to_commented_author, "limit_rate": True, # 单位时间控制 速率限制开关 "limit_whole": True, # 总时间控制 速率限制开关 "rate_limit_unit_times": push_control.get("answer_reply"), # 单位时间内推送次数控制 }, PUSH_ACTION_TYPE.ANSWER_CREATE_PUSH_TO_QUESTION_AUTHOR: { # 创建回答, 推送给问题作者 "params_builder": TimelyPushParamsBuilder.create_answer_push_to_question_author, "limit_rate": False, # 单位时间控制 速率限制开关 "limit_whole": False, # 总时间控制 速率限制开关 }, PUSH_ACTION_TYPE.ANSWER_CREATE_PUSH_TO_FANS: { # 创建回答, 推送给粉丝 "params_builder": TimelyPushParamsBuilder.create_answer_push_to_fans, "limit_rate": False, # 单位时间控制 速率限制开关 "limit_whole": False, # 总时间控制 速率限制开关 }, PUSH_ACTION_TYPE.USER_RECV_FOLLOW: { # 用户加关注 "params_builder": TimelyPushParamsBuilder.user_add_follow, "limit_rate": True, # 单位时间控制 速率限制开关 "limit_whole": True, # 总时间控制 速率限制开关 "rate_limit_unit_times": push_control.get("user_follow"), # 单位时间内推送次数控制 }, } # 聚合推送配置 aggregation_push_handlers = { PUSH_ACTION_TYPE.ANSWER_RECV_VOTE: { # 回答点赞 "params_builder": AggregationPushParamsBuilder.aggregation_answer_vote, "limit_rate": True, # 单位时间控制 速率限制开关 "limit_whole": True, # 总时间控制 速率限制开关 }, PUSH_ACTION_TYPE.ANSWER_RECV_REPLY: { # 回答下发评论 "params_builder": AggregationPushParamsBuilder.aggregation_answer_reply, "limit_rate": True, # 单位时间控制 速率限制开关 "limit_whole": True, # 总时间控制 速率限制开关 }, PUSH_ACTION_TYPE.USER_RECV_FOLLOW: { # 用户加关注 "params_builder": AggregationPushParamsBuilder.aggregation_user_add_follow, "limit_rate": True, # 单位时间控制 速率限制开关 "limit_whole": True, # 总时间控制 速率限制开关 }, } # 聚合类型推送规则 aggregation_push_rule = { "answer": { # 聚合方式,就是个key 没实际意义 "aggregation_push_types": [ # 聚合推送类型 注意: 聚合的类型不能完全一致!!! PUSH_ACTION_TYPE.ANSWER_RECV_VOTE, PUSH_ACTION_TYPE.ANSWER_RECV_REPLY, PUSH_ACTION_TYPE.USER_RECV_FOLLOW, ], "delay_times": hour * 1, # 聚合时间 --> 可以推算异步任务触发时间 }, } class CtrPushContentFormat(object): @classmethod def ctr_tractate(cls, content_id, push_type): try: tractate = TractateService.healthy(content_id) except RPCDFaultException: return {} tractate_tag = TractateTagV3.objects.using(settings.SLAVE_DB_NAME).filter( tractate_id=tractate.id, ).first() tag_name = '' push_url = GmProtocol().get_tractate_detail(tractate_id=tractate.id) if tractate_tag: tag_info = TagV3Service.get_tags_by_tag_v3_ids([tractate_tag.tag_v3_id]) tag_info = tag_info.get(tractate_tag.tag_v3_id, {}) if tag_info: tag_name = TagV3Service.format_tag_v3(tag_info).get('tag_name') tag_id = TagV3Service.format_tag_v3(tag_info).get('id') topic_list = Tag2GroupTopic.get_topic_ids_with_tag_v3(tag_id) if topic_list: push_url = GmProtocol().get_group_topic_detail( topic_id=topic_list[0]['id'], target_id=content_id, target_type=INDEX_CARD_TYPE.TRACTATE ) if not tag_name: tractate_tag = TractateTag.objects.using(settings.SLAVE_DB_NAME).filter( tractate_id=tractate.id, ).first() if tractate_tag: tags = TagService.get_tags_by_tag_ids([tractate_tag.tag_id]) tag_name = tags and tags[0].name or '' push_title = "#{} 今天有好看新帖子,快来看!".format(tag_name) # author = UserService.get_user_by_user_id(tractate.user_id) # alert = "@{}: {}".format(author.nickname, content) content = gm_decode_html(tractate.content)[:25] images = list(TractateImages.objects.using(settings.SLAVE_DB_NAME).filter( tractate_id=tractate.id ).values_list('image_url', flat=True)) push_image = images and Picture(images[0]).watermarked or '' kwargs = { "push_type": push_type, "platform": None, "extra": { "type": PUSH_INFO_TYPE.GM_PROTOCOL, "pushUrl": push_url, "push_url": push_url, 'image': push_image, 'push_image': push_image, }, "alert": content, "others": { "title": push_title, "alert": content, } } return kwargs @classmethod def ctr_answer(cls, content_id, push_type): try: answer = Answer.objects.using(settings.SLAVE_DB_NAME).select_related('question').get(id=content_id) except Answer.DoesNotExist: return {} push_title = answer.question.title[:25] author = UserService.get_user_by_user_id(answer.user_id) content = gm_decode_html(answer.content)[:25] alert = "@{}: {}".format(author.nickname, content) images = list(AnswerImage.objects.using(settings.SLAVE_DB_NAME).filter( answer_id=answer.id ).values_list('image_url', flat=True)) push_image = images and Picture(images[0]).watermarked or '' push_url = GmProtocol().get_answer_list(answer=answer.id) # answer_tag_v3 = AnswerTagV3.objects.using(settings.SLAVE_DB_NAME).filter( # answer_id=answer.id, # ).first() # if answer_tag_v3: # tag_info = TagV3Service.get_tags_by_tag_v3_ids([answer_tag_v3.tag_v3_id]) # tag_info = tag_info.get(answer_tag_v3.tag_v3_id, {}) # if tag_info: # tag_id = TagV3Service.format_tag_v3(tag_info).get('id') # topic_list = Tag2GroupTopic.get_topic_ids_with_tag_v3(tag_id) # if topic_list: # push_url = GmProtocol().get_group_topic_detail( # topic_id=topic_list[0], # target_id=answer.question_id, # target_type=INDEX_CARD_TYPE.QUESTION # todo: 不支持问题 # ) kwargs = { "push_type": push_type, "platform": None, "extra": { "type": PUSH_INFO_TYPE.GM_PROTOCOL, "pushUrl": push_url, "push_url": push_url, 'image': push_image, 'push_image': push_image, }, "alert": alert, "others": { "title": push_title, "alert": alert, } } return kwargs @classmethod def ctr_diary(cls, content_id, push_type): try: diary = Diary.objects.using(settings.SLAVE_DB_NAME).get(id=content_id) except Diary.DoesNotExist: return {} topic = Problem.objects.using(settings.SLAVE_DB_NAME).filter( diary_id=diary.id, is_online=True ).first() if not topic: return {} diary_tag = DiaryTagV3.objects.using(settings.SLAVE_DB_NAME).filter( diary_id=diary.id, ).first() tag_name = '' push_url = GmProtocol().get_diary_detail(id=diary.id) if diary_tag: tag_info = TagV3Service.get_tags_by_tag_v3_ids([diary_tag.tag_v3_id]) tag_info = tag_info.get(diary_tag.tag_v3_id, {}) if tag_info: tag_v3_info = TagV3Service.format_tag_v3(tag_info) tag_name = tag_v3_info.get('tag_name') topic_list = Tag2GroupTopic.get_topic_ids_with_tag_v3(tag_v3_info.get('id')) if topic_list: push_url = GmProtocol().get_group_topic_detail( topic_id=topic_list[0]['id'], target_id=content_id, target_type=INDEX_CARD_TYPE.DIARY # todo: 此处找社区确认,改为枚举 ) if not tag_name: diary_tag = DiaryTag.objects.using(settings.SLAVE_DB_NAME).filter( diary_id=diary.id, ).first() if diary_tag: tags = TagService.get_tags_by_tag_ids([diary_tag.tag_id]) tag_name = tags and tags[0].name or '' push_title = "今日份的{}精选日记".format(tag_name) author = UserService.get_user_by_user_id(topic.user_id) content = gm_decode_html(topic.content)[:25] alert = "@{}: {}".format(author.nickname, content) images = list(TopicImage.objects.using(settings.SLAVE_DB_NAME).filter( topic_id=topic.id ).values_list('image_url', flat=True)) push_image = images and Picture(images[0]).watermarked or '' kwargs = { "push_type": push_type, "platform": None, "extra": { "type": PUSH_INFO_TYPE.GM_PROTOCOL, "pushUrl": push_url, "push_url": push_url, 'image': push_image, 'push_image': push_image, }, "alert": alert, "others": { "title": push_title, "alert": alert, } } return kwargs @classmethod def ctr_question(cls, content_id, push_type, tag_name): try: question = Question.objects.using(settings.SLAVE_DB_NAME).get(id=content_id) except Question.DoesNotExist: return {} push_title = "有人向你请教{}的问题".format(tag_name) author = UserService.get_user_by_user_id(question.user_id) content = gm_decode_html(question.title)[:25] alert = "@{}: {}".format(author.nickname, content) images = list(QuestionImage.objects.using(settings.SLAVE_DB_NAME).filter( question_id=question.id ).values_list('image_url', flat=True)) push_image = images and Picture(images[0]).watermarked or '' kwargs = { "push_type": push_type, "platform": None, "extra": { "type": PUSH_INFO_TYPE.GM_PROTOCOL, "pushUrl": GmProtocol().get_question_detail(question_id=question.id), "push_url": GmProtocol().get_question_detail(question_id=question.id), 'image': push_image, 'push_image': push_image, }, "alert": alert, "others": { "title": push_title, "alert": alert, } } return kwargs