zhangdongming 3 роки тому
батько
коміт
566a976377
3 змінених файлів з 211 додано та 17 видалено
  1. 118 17
      Controller/ComboCron/ComboCronPushController.py
  2. 1 0
      Model/models.py
  3. 92 0
      Object/AliyunSmsObject.py

+ 118 - 17
Controller/ComboCron/ComboCronPushController.py

@@ -13,7 +13,8 @@ import traceback
 from django.db.models import Q
 from django.views import View
 
-from Model.models import UnicomComboOrderInfo, UnicomDeviceInfo, GatewayPush, SysMsgModel
+from Model.models import UnicomComboOrderInfo, UnicomDeviceInfo, GatewayPush, SysMsgModel, UnicomFlowPush, Device_User
+from Object.AliyunSmsObject import AliyunSmsObject
 from Object.ResponseObject import ResponseObject
 from Service.GatewayService import GatewayPushService
 
@@ -36,6 +37,8 @@ class ComboCronPushView(View):
         response = ResponseObject()
         if operation == 'expire-push':
             return self.combo_expire_push(response)
+        elif operation == 'warning-push':
+            return self.flow_warning_push(response)
         else:
             return response.json(404)
 
@@ -71,7 +74,6 @@ class ComboCronPushView(View):
         消息推送
         """
         now_time = int(time.time())
-        logger = logging.getLogger('info')
         for item in combo_order_qs:
             iccid = item['iccid']
             device_info = UnicomDeviceInfo.objects.filter(iccid=iccid).values()
@@ -84,8 +86,7 @@ class ComboCronPushView(View):
 
             # 查询推送配置数据
             push_qs = GatewayPush.objects.filter(user_id=user_id, logout=False). \
-                values('user_id', 'app_bundle_id', 'app_type', 'push_type', 'token_val', 'm_code', 'lang', 'm_code',
-                       'tz')
+                values('user_id', 'app_bundle_id', 'app_type', 'push_type', 'token_val', 'm_code', 'lang', 'tz')
             if not push_qs.exists():
                 continue
             for push_vo in push_qs:
@@ -113,19 +114,7 @@ class ComboCronPushView(View):
                 kwargs['msg_title'] = msg_title
                 kwargs['msg_text'] = sys_msg_text
                 cls.sys_msg_save(user_id, nickname, now_time, sys_msg_text)
-                try:
-                    # ios apns
-                    if push_type == 0:
-                        GatewayPushService.ios_apns_push(**kwargs)
-                    # android gcm
-                    elif push_type == 1:
-                        GatewayPushService.android_fcm_push(**kwargs)
-                    # android 极光推送
-                    elif push_type == 2:
-                        GatewayPushService.android_jpush(**kwargs)
-
-                except Exception as e:
-                    logger.info('4G流量预警推送消息异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
+                if not cls.msg_push(push_type, **kwargs):
                     continue
         return True
 
@@ -141,3 +130,115 @@ class ComboCronPushView(View):
             SysMsgModel.objects.create(**data)
         except Exception as e:
             logger.info('---4G流量存库异常--- {}'.format(repr(e)))
+
+    @classmethod
+    def flow_warning_push(cls, response):
+        logger = logging.getLogger('info')
+        flow_push_qs = UnicomFlowPush.objects.filter(type=0, status=0)
+        if not flow_push_qs.exists():
+            return response.json(0)
+        for item in flow_push_qs:
+            try:
+                user_id = item.user_id
+                if not user_id:
+                    continue
+                user_push_qs = GatewayPush.objects.filter(user_id=user_id)
+                if not user_push_qs:
+                    continue
+                now_time = int(time.time())
+                # 查询推送配置数据
+                push_qs = GatewayPush.objects.filter(user_id=user_id, logout=False). \
+                    values('user_id', 'app_bundle_id', 'app_type', 'push_type', 'token_val', 'm_code', 'lang', 'tz')
+                if not push_qs.exists():
+                    continue
+                usage = cls.flow_split(item.flow_total_usage)
+                total = cls.flow_split(item.flow_total)
+                usable = cls.flow_split(item.flow_total - item.flow_total_usage)
+                user_qs = Device_User.objects.filter(userID=user_id).values('phone')
+                if user_qs.exists() and user_qs.first()['phone']:
+                    params = u'{"devname":"' + item.serial_no + '","usage":"流量' + usage + '","usable":"流量' + \
+                             usable + '"}'
+                    cls.send_aliyun_sms(user_qs.first()['phone'], params, 'SMS_246090429')
+
+                for push_vo in push_qs:
+                    kwargs = {
+                        'n_time': now_time,
+                        'event_type': 1,
+                        'nickname': item.serial_no,
+                    }
+                    push_type = push_vo['push_type']
+                    token_val = push_vo['token_val']
+                    lang = push_vo['lang']
+                    app_bundle_id = push_vo['app_bundle_id']
+
+                    # 获取推送所需数据
+                    msg_title = GatewayPushService.get_msg_title(app_bundle_id, item.serial_no)
+                    sys_msg_text = cls.get_msg_text(item.serial_no, lang, total, usage, usable)
+                    kwargs['app_bundle_id'] = app_bundle_id
+                    kwargs['token_val'] = token_val
+                    kwargs['msg_title'] = msg_title
+                    kwargs['msg_text'] = sys_msg_text
+                    cls.sys_msg_save(user_id, item.serial_no, now_time, sys_msg_text)
+                    if not cls.msg_push(push_type, **kwargs):
+                        continue
+                # 修改推送状态
+                UnicomFlowPush.objects.filter(id=item.id).update(status=1)
+            except Exception as e:
+                logger.info('出错了~4G流量10%预警推送消息异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
+                continue
+        return response.json(0)
+
+    @staticmethod
+    def get_msg_text(serial_no, lang, total, usage, usable):
+        """
+        app消息推送内容
+        """
+        if lang == 'cn':
+            sys_msg_text = "温馨提示:尊敬的客户,您" + serial_no + "设备当前套餐总流量共" + total + ",已使用" + \
+                           usage + "" + ",剩余" + usable + ""
+        else:
+            sys_msg_text = 'Warm tip: Dear customer, the total traffic of your ' + serial_no + \
+                           ' device is ' + total + 'g in the current package. ' + usage + \
+                           ' has been used and ' + usable + ' is left'
+        return sys_msg_text
+
+    @staticmethod
+    def msg_push(push_type, **kwargs):
+        """
+        app推送
+        """
+        logger = logging.getLogger('info')
+        try:
+            # ios apns
+            if push_type == 0:
+                GatewayPushService.ios_apns_push(**kwargs)
+            # android gcm
+            elif push_type == 1:
+                GatewayPushService.android_fcm_push(**kwargs)
+            # android 极光推送
+            elif push_type == 2:
+                GatewayPushService.android_jpush(**kwargs)
+            return True
+        except Exception as e:
+            logger.info('流量预警推送异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
+            return False
+
+    @staticmethod
+    def send_aliyun_sms(phone, params, temp_code):
+        """
+        推送阿里云国内短信通知
+        """
+        sign = '周视'
+        ali_sms = AliyunSmsObject()
+        ali_sms.send_code_sms_cloud(phone, params, sign, temp_code)
+
+    @staticmethod
+    def flow_split(flow):
+        """
+        流量保留两位小数并带单位
+        """
+        if flow >= 1024:
+            flow = flow / 1024
+            return str(round(flow, 2)) + "G"
+        else:
+            return str(round(flow, 2)) + "M"

+ 1 - 0
Model/models.py

@@ -2362,3 +2362,4 @@ class UnicomFlowPush(models.Model):
         db_table = 'unicom_flow_push'
         verbose_name = '联通流量用量推送'
         verbose_name_plural = verbose_name
+        app_label = 'db2'

+ 92 - 0
Object/AliyunSmsObject.py

@@ -0,0 +1,92 @@
+# -*- encoding: utf-8 -*-
+"""
+@File    : AliyunSmsObject.py
+@Time    : 2022/7/19 8:50
+@Author  : stephen
+@Email   : zhangdongming@asj6.wecom.work
+@Software: PyCharm
+"""
+import json
+# -*- coding: utf-8 -*-
+import uuid
+
+from aliyunsdkcore.client import AcsClient
+from aliyunsdkcore.profile import region_provider
+from aliyunsdkdysmsapi.request.v20170525 import SendSmsRequest
+
+"""
+短信业务调用接口示例,版本号:v20170525
+Created on 2017-06-12
+"""
+
+
+class AliyunSmsObject(object):
+
+    def __init__(self):
+        # 注意:不要更改
+        REGION = "cn-hangzhou"
+        PRODUCT_NAME = "Dysmsapi"
+        DOMAIN = "dysmsapi.aliyuncs.com"
+        ali_sms = {
+            'ACCESS_KEY_ID': 'LTAIDFtlwLdttWiX',
+            'ACCESS_KEY_SECRET': 'Siu6SolsTN5A3evXUkFLyyr0QZ3iiT',
+        }
+        self.acs_client = AcsClient(ali_sms['ACCESS_KEY_ID'], ali_sms['ACCESS_KEY_SECRET'], REGION)
+        region_provider.add_endpoint(PRODUCT_NAME, REGION, DOMAIN)
+
+    def do_send_sms(self, business_id, phone_numbers, sign_name, template_code, template_param=None):
+        smsRequest = SendSmsRequest.SendSmsRequest()
+        # 申请的短信模板编码,必填
+        smsRequest.set_TemplateCode(template_code)
+
+        # 短信模板变量参数
+        if template_param is not None:
+            smsRequest.set_TemplateParam(template_param)
+
+        # 设置业务请求流水号,必填。
+        smsRequest.set_OutId(business_id)
+
+        # 短信签名
+        smsRequest.set_SignName(sign_name)
+
+        # 数据提交方式
+        # smsRequest.set_method(MT.POST)
+
+        # 数据提交格式
+        # smsRequest.set_accept_format(FT.JSON)
+
+        # 短信发送的号码列表,必填。
+        smsRequest.set_PhoneNumbers(phone_numbers)
+
+        # 调用短信发送接口,返回json
+        smsResponse = self.acs_client.do_action_with_exception(smsRequest)
+
+        # TODO 业务处理
+
+        return smsResponse
+
+    # 发送验证码
+    def send_code_sms(self, phone, code, sign_name, temp_msg):
+        __business_id = uuid.uuid1()
+        params = "{\"code\":\"" + str(code) + "\"}"
+        res = self.do_send_sms(__business_id, phone, sign_name, temp_msg, params)
+        res_json = json.loads(res.decode('utf-8'))
+        return res_json
+
+        # 发送验证码
+
+    def send_code_sms_cloud(self, phone, params, sign_name, temp_msg):
+        __business_id = uuid.uuid1()
+        params = params
+        res = self.do_send_sms(__business_id, phone, sign_name, temp_msg, params)
+        res_json = json.loads(res.decode('utf-8'))
+        return res_json
+
+
+if __name__ == '__main__':
+    pass
+    # sign = '周视'
+    # ali_sms = AliyunSmsObject()
+    # params = u'{"devname":"DKOGER11A","usage":"流量365M","usable":"流量12M"}'
+    # res = ali_sms.send_code_sms_cloud('15768812162', params, sign, 'SMS_246090429')
+    # print(ali_sms)