peng 2 жил өмнө
parent
commit
52e19d95bf
1 өөрчлөгдсөн 126 нэмэгдсэн , 283 устгасан
  1. 126 283
      Controller/CloudStorage.py

+ 126 - 283
Controller/CloudStorage.py

@@ -1,25 +1,11 @@
 #!/usr/bin/env python3
 # -*- coding: utf-8 -*-
-"""
-@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
-@AUTHOR: ASJRD018
-@NAME: AnsjerFormal
-@software: PyCharm
-@DATE: 2018/12/5 9:30
-@Version: python3.6
-@MODIFY DECORD:ansjer dev
-@file: cloudstorage.py
-@Contact: chanjunkai@163.com
-"""
 import base64
 import json
-import os
 import time
 from urllib.parse import quote, parse_qs, unquote
 
-import apns2
 import boto3
-import jpush
 import paypalrestsdk
 import datetime
 import logging
@@ -29,15 +15,12 @@ from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
 from django.db import transaction
 from django.views.generic.base import View
 import jwt
-from pyfcm import FCMNotification
-from Ansjer.config import SERVER_DOMAIN, PAYPAL_CRD, \
-    SERVER_DOMAIN_SSL, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_ARN, APNS_MODE, APNS_CONFIG, BASE_DIR, \
-    JPUSH_CONFIG, FCM_CONFIG, OAUTH_ACCESS_TOKEN_SECRET
+from Ansjer.config import SERVER_DOMAIN, PAYPAL_CRD, SERVER_DOMAIN_SSL, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, \
+    AWS_ARN, OAUTH_ACCESS_TOKEN_SECRET
 from Controller.CheckUserData import DataValid
 from Model.models import Device_Info, Order_Model, Store_Meal, VodHlsModel, UID_Bucket, StsCrdModel, \
-    ExperienceContextModel, Pay_Type, CDKcontextModel, Device_User, SysMsgModel, UidPushModel, \
-    Unused_Uid_Meal, PromotionRuleModel, VideoPlaybackTimeModel, CouponModel, \
-    VodBucketModel, VodHlsSummary
+    ExperienceContextModel, Pay_Type, CDKcontextModel, Device_User, SysMsgModel, Unused_Uid_Meal, PromotionRuleModel, \
+    VideoPlaybackTimeModel, CouponModel, VodBucketModel, VodHlsSummary
 from Object.AWS.S3Email import S3Email
 from Object.AliPayObject import AliPayObject
 from Object.AliSmsObject import AliSmsObject
@@ -53,21 +36,6 @@ from Controller.PaymentCycle import Paypal
 from decimal import Decimal
 from Service.PayService import PaymentService
 
-'''
-生成订单
-http://test.dvema.com/cloudstorage/createpayorder?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySUQiOiIxNTY3NzU4MjE4NjE5MTM4MDAxMzgwMDAiLCJleHAiOjE1ODk1MjM0OTIsIm1fY29kZSI6IjEyMzQxMzI0MzIxNCIsImxhbmciOiJlbiIsInVzZXIiOiIxMzExOTY1NzcxMyJ9.e2NdhJtbXrDngZTSmOX_52Y-oxyfUEXjZD_qNxg6VrU&uid=VVDHCVBYDKFMJRWA111A&channel=1&pay_type=0&commodity_code=aws_us_vod_7_val_30
-开启开关
-http://test.dvema.com/cloudstorage/changevodstatus?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySUQiOiIxNTY3NzU4MjE4NjE5MTM4MDAxMzgwMDAiLCJleHAiOjE1ODk1MjM0OTIsIm1fY29kZSI6IjEyMzQxMzI0MzIxNCIsImxhbmciOiJlbiIsInVzZXIiOiIxMzExOTY1NzcxMyJ9.e2NdhJtbXrDngZTSmOX_52Y-oxyfUEXjZD_qNxg6VrU&uid=VVDHCVBYDKFMJRWA111A&channel=1&status=1
-# 获取播放列表
-http://localhost:8077/cloudstorage/queryvodlist?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySUQiOiIxNTY3NzU4MjE4NjE5MTM4MDAxMzgwMDAiLCJleHAiOjE1ODk1MjM0OTIsIm1fY29kZSI6IjEyMzQxMzI0MzIxNCIsImxhbmciOiJlbiIsInVzZXIiOiIxMzExOTY1NzcxMyJ9.e2NdhJtbXrDngZTSmOX_52Y-oxyfUEXjZD_qNxg6VrU&uid=VVDHCVBYDKFMJRWA111A&startTime=1&endTime=1954687458&channel=1
-# 存储视频列表信息
-http://test.dvema.com/cloudstorage/storeplaylist?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJWVkRIQ1ZCWURLRk1KUldBMTExQSIsImNoYW5uZWwiOiIxIn0.eGwi5QKyrXi4WSKRbrUG7iFTChv_Utec2hSnqZkDKt8&time=1586940120&sec=20&fg=10
-# 获取订单列表
-http://localhost:8077/cloudstorage/queryorder?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOiIxNTY3NzU4MjE4NjE5MTM4MDAxMzgwMDAiLCJsYW5nIjoiZW4iLCJ1c2VyIjoiMTMxMTk2NTc3MTMiLCJtX2NvZGUiOiIxMjM0MTMyNDMyMTQiLCJleHAiOjE1ODk1OTIyNzh9.u211DHiMKg-pqhXv4b2yR__eNyOcSwBZCyPUGjsxFLU&page=1&line=10&uid=VVDHCVBYDKFMJRWA111A
-# commoditylist
-http://test.dvema.com/cloudstorage/commoditylist?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySUQiOiIxNTY3NzU4MjE4NjE5MTM4MDAxMzgwMDAiLCJleHAiOjE1ODk1MjM0OTIsIm1fY29kZSI6IjEyMzQxMzI0MzIxNCIsImxhbmciOiJlbiIsInVzZXIiOiIxMzExOTY1NzcxMyJ9.e2NdhJtbXrDngZTSmOX_52Y-oxyfUEXjZD_qNxg6VrU
-'''
-
 
 # 设备信息添加
 class CloudStorageView(View):
@@ -104,8 +72,6 @@ class CloudStorageView(View):
             return self.do_pay_ok(request_dict)
         elif operation == 'vodMsgEnd':  # 云存到期续费提醒   提前1天
             return self.do_vod_msg_end()
-        elif operation == 'vodMsgNotice':  # 云存操作系统消息
-            return self.do_vod_msg_Notice(request_dict)
         elif operation == 'doRefund':  # 退款
             return self.do_refund(request_dict, response)
 
@@ -132,7 +98,7 @@ class CloudStorageView(View):
             elif operation == 'experiencereset':  # 重置设备云存体验
                 return self.do_experience_reset(request_dict, response)
             elif operation == 'deletevodlist':  # 删除播放列表
-                return self.deleteVodList(request_dict, user_id, response)
+                return self.delete_vod_list(request_dict, user_id, response)
             elif operation == 'devicecommodity':  # 设备关联套餐列表
                 return self.device_commodity(request_dict, user_id, response)
             elif operation == 'switchdevicecommodity':  # 提前使用设备关联套餐
@@ -140,11 +106,12 @@ class CloudStorageView(View):
             elif operation == 'hasvod':  # APP的回放界面,日历表显示当天有无录像
                 return self.has_vod(request_dict, user_id, response)
             elif operation == 'videoPlaybackTime':  # 记录app播放时间
-                return self.videoPlaybackTime(request_dict, user_id, response)
+                return self.video_playback_time(request_dict, user_id, response)
             else:
                 return response.json(414)
 
-    def do_query_order(self, request_dict, user_id, response):  # 查询订单列表
+    @staticmethod
+    def do_query_order(request_dict, user_id, response):  # 查询订单列表
         status = request_dict.get('status', None)
         page = int(request_dict.get('page', None))
         line = int(request_dict.get('line', None))
@@ -158,10 +125,10 @@ class CloudStorageView(View):
         if not order_qs.exists():
             return response.json(173)
         count = order_qs.count()
-        order_ql = order_qs[(page - 1) * line:page * line]. \
-            values("orderID", "UID", "channel", "desc", "price", "currency",
-                   "addTime", "updTime", "endTime", "pay_url", "payType",
-                   "status", "commodity_type", "commodity_code")
+        order_ql = order_qs[(page - 1) * line:page * line].values("orderID", "UID", "channel", "desc", "price",
+                                                                  "currency", "addTime", "updTime", "endTime",
+                                                                  "pay_url", "payType", "status", "commodity_type",
+                                                                  "commodity_code")
         order_list = list(order_ql)
         data = []
         new_time = int(time.time())
@@ -169,20 +136,20 @@ class CloudStorageView(View):
         uid_list = []
         for od in order_list:
             uid_list.append(od['UID'])
-        didqs = Device_Info.objects.filter(userID_id=user_id, UID__in=uid_list). \
-            values('id', 'UID', 'Type')
+        did_qs = Device_Info.objects.filter(userID_id=user_id, UID__in=uid_list).values('id', 'UID', 'Type')
         for d in order_list:
             if d['status'] == 0:
                 if d['addTime'] + 3600 < new_time:
                     d['status'] = 3
-            for did in didqs:
+            for did in did_qs:
                 if d['UID'] == did['UID']:
                     d['did'] = did['id']
                     d['Type'] = did['Type']
                     data.append(d)
         return response.json(0, {'data': data, 'count': count})
 
-    def do_commodity_list(self, request_dict, response):  # 查询套餐列表
+    @staticmethod
+    def do_commodity_list(request_dict, response):  # 查询套餐列表
         mold = request_dict.get('mold', None)
         uid = request_dict.get('uid', None)
         lang = request_dict.get('lang', 'en')
@@ -260,14 +227,15 @@ class CloudStorageView(View):
         else:
             return response.json(0)
 
-    def do_sign_play_m3u8(self, request_dict, response):  # 根据sts播放m3u8 视频流
+    @staticmethod
+    def do_sign_play_m3u8(request_dict, response):  # 根据sts播放m3u8 视频流
         uid = request_dict.get('uid', None)
         uid = jwt.decode(uid, OAUTH_ACCESS_TOKEN_SECRET, algorithms='HS256').get('uid', '')
         channel = request_dict.get('channel', None)
         store_time = request_dict.get('time', None)
         now_time = int(time.time())
-        vh_qs = VodHlsModel.objects.filter(uid=uid, channel=channel, time=store_time, endTime__gte=now_time). \
-            values("sec", "fg", "bucket__bucket", "bucket__endpoint", "bucket__region", "bucket__mold")
+        vh_qs = VodHlsModel.objects.filter(uid=uid, channel=channel, time=store_time, endTime__gte=now_time).values(
+            "sec", "fg", "bucket__bucket", "bucket__endpoint", "bucket__region", "bucket__mold")
         if not vh_qs.exists():
             return response.json(173)
         fg = vh_qs[0]['fg']
@@ -281,9 +249,7 @@ class CloudStorageView(View):
             aws_secret_access_key=AWS_SECRET_ACCESS_KEY[vh_qs[0]["bucket__mold"]],
             region_name=bucket__region
         )
-        '''
-            http://test.dvema.com/cloudstorage/signplaym3u8?uid=VVDHCVBYDKFMJRWA111A&channel=1&time=1586940120&sign=tktktktk
-        '''
+
         conn = session.client('s3')
         playlist_entries = []
         fg = int(fg)
@@ -293,8 +259,7 @@ class CloudStorageView(View):
             shift = (i + 1) * 4
             duration = (fg >> shift) & 0xf
             if duration > 0:
-                ts_file = '{uid}/vod{channel}/{time}/ts{i}.ts'. \
-                    format(uid=uid, channel=channel, time=store_time, i=i)
+                ts_file = '{uid}/vod{channel}/{time}/ts{i}.ts'.format(uid=uid, channel=channel, time=store_time, i=i)
                 response_url = conn.generate_presigned_url(
                     'get_object',
                     Params={
@@ -314,7 +279,8 @@ class CloudStorageView(View):
         response['Content-Disposition'] = 'attachment;filename="play.m3u8"'
         return response
 
-    def do_get_sign_sts(self, request_dict, ip, response):  # 获取sts令牌
+    @staticmethod
+    def do_get_sign_sts(request_dict, ip, response):  # 获取sts令牌
         uid_token = request_dict.get('uidToken', None)
         utko = UidTokenObject(uid_token)
         if utko.flag is False:
@@ -324,13 +290,13 @@ class CloudStorageView(View):
         print(channel)
         print(uid)
         now_time = int(time.time())
-        ubqs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time, channel=channel).values("bucket__mold",
-                                                                                                 "bucket__bucket",
-                                                                                                 "bucket__endpoint",
-                                                                                                 "bucket__region",
-                                                                                                 "endTime").order_by(
+        ub_qs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time, channel=channel).values("bucket__mold",
+                                                                                                  "bucket__bucket",
+                                                                                                  "bucket__endpoint",
+                                                                                                  "bucket__region",
+                                                                                                  "endTime").order_by(
             'addTime')[:1]
-        if ubqs.exists():
+        if ub_qs.exists():
             # 亚马逊 s3 sts
             sts_qs = StsCrdModel.objects.filter(uid=uid, channel=channel). \
                 values("addTime", "data")
@@ -343,19 +309,18 @@ class CloudStorageView(View):
                     return JsonResponse(status=200, data=res)
                 # 套餐id
             storage = '{uid}/vod{channel}/'.format(uid=uid, channel=channel)
-            bucket_name = ubqs[0]['bucket__bucket']
-            endpoint = ubqs[0]['bucket__endpoint']
-            region_id = ubqs[0]['bucket__region']
+            bucket_name = ub_qs[0]['bucket__bucket']
+            endpoint = ub_qs[0]['bucket__endpoint']
+            region_id = ub_qs[0]['bucket__region']
 
             try:
-                aws_access_key_id = AWS_ACCESS_KEY_ID[ubqs[0]["bucket__mold"]]
-                aws_secret_access_key = AWS_SECRET_ACCESS_KEY[ubqs[0]["bucket__mold"]]
-                aws_arn = AWS_ARN[ubqs[0]["bucket__mold"]]
+                aws_access_key_id = AWS_ACCESS_KEY_ID[ub_qs[0]["bucket__mold"]]
+                aws_secret_access_key = AWS_SECRET_ACCESS_KEY[ub_qs[0]["bucket__mold"]]
+                aws_arn = AWS_ARN[ub_qs[0]["bucket__mold"]]
             except:
                 res = {'code': 404, 'msg': 'mold not exists!'}
                 return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
 
-            ###############
             boto3_sts = boto3.client(
                 'sts',
                 aws_access_key_id=aws_access_key_id,
@@ -378,7 +343,6 @@ class CloudStorageView(View):
                 Policy=json.dumps(policy),
                 DurationSeconds=7200
             )
-            ##############
             res = {
                 'AccessKeyId': response['Credentials']['AccessKeyId'],
                 'AccessKeySecret': response['Credentials']['SecretAccessKey'],
@@ -390,10 +354,10 @@ class CloudStorageView(View):
                 'arn': response['FederatedUser']['Arn'],
                 'code': 0,
                 'storage': storage,
-                'endTime': ubqs[0]['endTime'],
+                'endTime': ub_qs[0]['endTime'],
                 'ip': ip,
                 'region': region_id,
-                'bucket_mold': ubqs[0]['bucket__mold']
+                'bucket_mold': ub_qs[0]['bucket__mold']
             }
             if sts_qs.exists():
                 sts_qs.update(data=json.dumps(res, default=str), addTime=now_time)
@@ -404,7 +368,8 @@ class CloudStorageView(View):
         res = {'code': 405, 'msg': 'Not purchased or expired!'}
         return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
 
-    def do_query_vod_list(self, request_dict, user_id, response):  # 获取视频播放列表
+    @staticmethod
+    def do_query_vod_list(request_dict, user_id, response):  # 获取视频播放列表
         logger = logging.getLogger('info')
         into_time = int(time.time())
 
@@ -476,7 +441,7 @@ class CloudStorageView(View):
             region_name=bucket_region
         )
         conn = session.client('s3')
-        uidToken = TokenObject().encryption(data={'uid': uid})
+        uid_token = TokenObject().encryption(data={'uid': uid})
 
         aws_object_over_time = int(time.time())
         logger.info({
@@ -489,8 +454,7 @@ class CloudStorageView(View):
 
         for vod in vh_qs:
             bucket_name = regroup_bucket_qs[vod['bucket_id']]['bucket']
-            thumbs_png = '{uid}/vod{channel}/{time}/Thumb.jpeg'. \
-                format(uid=uid, channel=channel, time=vod['time'])
+            thumbs_png = '{uid}/vod{channel}/{time}/Thumb.jpeg'.format(uid=uid, channel=channel, time=vod['time'])
             response_url = conn.generate_presigned_url(
                 'get_object',
                 Params={
@@ -501,7 +465,7 @@ class CloudStorageView(View):
             )
             vod_url = '{server_domain}/cloudstorage/signplaym3u8?' \
                       'uid={uid}&channel={channel}&time={time}&sign=tktktktk'. \
-                format(server_domain=SERVER_DOMAIN_SSL, uid=uidToken, channel=channel, time=vod['time'])
+                format(server_domain=SERVER_DOMAIN_SSL, uid=uid_token, channel=channel, time=vod['time'])
             ts_num = int(vod['fg']) & 0xf
             vod_play_list.append({
                 'start_time': vod['time'],
@@ -525,7 +489,8 @@ class CloudStorageView(View):
 
         return response.json(0, vod_play_list)
 
-    def do_store_playlist(self, request_dict, response):  # 设备调用,上传视频到s3,同时把视频数据信息传给服务器,服务器存储播放内容
+    @staticmethod
+    def do_store_playlist(request_dict, response):  # 设备调用,上传视频到s3,同时把视频数据信息传给服务器,服务器存储播放内容
         uid_token = request_dict.get('uidToken', None)
         store_time = request_dict.get('time', None)
         sec = request_dict.get('sec', None)
@@ -592,14 +557,15 @@ class CloudStorageView(View):
             res = {'code': 404, 'msg': '设备未购买'}
             return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
 
-    def do_change_vod_status(self, request_dict, user_id, response):  # 修改云存状态
+    @staticmethod
+    def do_change_vod_status(request_dict, user_id, response):  # 修改云存状态
         uid = request_dict.get('uid', None)
         status = request_dict.get('status', None)
         channel = request_dict.get('channel', None)
         if not uid or not status or not channel:
             return response.json(444, 'uid,status,channel')
-        dv_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1) \
-            .values('vodPrimaryUserID')
+        dv_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1).values(
+            'vodPrimaryUserID')
         if not dv_qs.exists() or dv_qs[0]['vodPrimaryUserID'] != user_id:
             return response.json(12)
         ub_qs = UID_Bucket.objects.filter(channel=channel, uid=uid)
@@ -619,12 +585,14 @@ class CloudStorageView(View):
             format(uidToken=utko.token, SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
         return response.json(0, {'uidTkUrl': uid_tk_url, 'storeHlsUrl': store_hls_url})
 
-    def do_pay_error(self):
+    @staticmethod
+    def do_pay_error():
         response = HttpResponse()
         response.content = PaymentService.get_pay_error_content()
         return response
 
-    def do_pay_ok(self, request_dict):  # 支付成功
+    @staticmethod
+    def do_pay_ok(request_dict):  # 支付成功
         response = HttpResponse()
         lang = request_dict.get('lang', 'en')
         pay_type = request_dict.get('paytype', None)
@@ -670,8 +638,7 @@ class CloudStorageView(View):
                 if not sm_qs.exists():
                     return response.json(173)
                 ub_qs = UID_Bucket.objects.filter(uid=uid).values("id", "bucket_id", "bucket__storeDay",
-                                                                  "bucket__region",
-                                                                  "endTime", "use_status")
+                                                                  "bucket__region", "endTime", "use_status")
                 expire = sm_qs[0]['expire']
                 if order_list[0]['isSelectDiscounts'] == 1:
                     expire = sm_qs[0]['expire'] * 2
@@ -737,7 +704,7 @@ class CloudStorageView(View):
                     sys_msg_text_list = ['温馨提示:尊敬的客户,您的' + device_name + '设备在' + date_time + '已成功购买云存套餐',
                                          'Dear customer,you already subscribed the cloud storage package successfully for device ' + device_name + ' on ' + time.strftime(
                                              "%b %dth,%Y", time.localtime())]
-                    self.do_vod_msg_Notice(uid, channel, userid, lang, sys_msg_text_list, 'SMS_219738485')
+                    self.do_vod_msg_notice(uid, channel, userid, lang, sys_msg_text_list, 'SMS_219738485')
                     red_url = "{SERVER_DOMAIN_SSL}web/paid2/success.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
                     if lang != 'cn':
                         red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_success.html".format(
@@ -805,15 +772,13 @@ class CloudStorageView(View):
             print("Payment execute successfully")
 
             order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
-                                         "userID__userID",
-                                         "userID__username", "coupon_id")
+                                         "userID__userID", "userID__username", "coupon_id")
             userid = order_list[0]['userID__userID']
             username = order_list[0]['userID__username']
             uid = order_list[0]['UID']
             channel = order_list[0]['channel']
             rank = order_list[0]['rank']
-            sm_qs = Store_Meal.objects.filter(id=rank). \
-                values("day", "bucket_id", "bucket__storeDay", "expire")
+            sm_qs = Store_Meal.objects.filter(id=rank).values("day", "bucket_id", "bucket__storeDay", "expire")
             bucket_id = sm_qs[0]['bucket_id']
             if not sm_qs.exists():
                 return response.json(173)
@@ -883,7 +848,7 @@ class CloudStorageView(View):
                                      'Dear customer,you already subscribed the cloud storage package successfully for device ' + device_name + ' on ' + time.strftime(
                                          "%b %dth,%Y", time.localtime())]
 
-                self.do_vod_msg_Notice(uid, channel, userid, lang, sys_msg_text_list, 'SMS_219738485')
+                self.do_vod_msg_notice(uid, channel, userid, lang, sys_msg_text_list, 'SMS_219738485')
 
                 red_url = "{SERVER_DOMAIN_SSL}web/paid2/success.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
                 if lang != 'cn':
@@ -1008,7 +973,7 @@ class CloudStorageView(View):
                     sys_msg_text_list = ['温馨提示:尊敬的客户,您的' + device_name + '设备在' + date_time + '已成功购买云存套餐',
                                          'Dear customer,you already subscribed the cloud storage package successfully for device ' + device_name + ' on ' + time.strftime(
                                              "%b %dth,%Y", time.localtime())]
-                    self.do_vod_msg_Notice(uid, channel, userid, lang, sys_msg_text_list, 'SMS_219738485')
+                    self.do_vod_msg_notice(uid, channel, userid, lang, sys_msg_text_list, 'SMS_219738485')
                     redis_obj.del_data(key=order_id + 'do_notify')
                     return HttpResponse("<xml>\
                       <return_code><![CDATA[SUCCESS]]></return_code>\
@@ -1026,7 +991,8 @@ class CloudStorageView(View):
             redis_obj.del_data(key=order_id + 'do_notify')
             return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': repr(e)}))
 
-    def do_create_pay_order(self, request_dict, userID, ip, response):  # 创建支付订单
+    @staticmethod
+    def do_create_pay_order(request_dict, user_id, ip, response):  # 创建支付订单
         logger = logging.getLogger('info')
         uid = request_dict.get('uid', None)
         channel = request_dict.get('channel', None)
@@ -1035,9 +1001,9 @@ class CloudStorageView(View):
         is_select_discount = request_dict.get('is_select_discount', 0)
         coupon_id = request_dict.get('coupon_id', 0)
         lang = request_dict.get('lang', 'en')
-        if not uid or not channel or not pay_type or not rank:
+        if not all([uid, channel, pay_type, rank]):
             return response.json(444)
-        dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False, isExist=1).values(
+        dv_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1).values(
             'vodPrimaryUserID',
             'vodPrimaryMaster')
         if not dv_qs.exists():
@@ -1046,16 +1012,21 @@ class CloudStorageView(View):
         dvq = Device_Info.objects.filter(UID=uid)
         dvq = dvq.filter(~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
         if dvq.exists():
-            if dvq[0]['vodPrimaryUserID'] != userID:
+            if dvq[0]['vodPrimaryUserID'] != user_id:
                 return response.json(10033)
 
         now_time = int(time.time())
         sm_qs = Store_Meal.objects.filter(id=rank, pay_type=pay_type, lang__lang=lang, is_show=0). \
-            values('currency', 'price', 'lang__content', 'day',
-                   'commodity_type', 'lang__title',
-                   'expire', 'commodity_code', 'discount_price', 'bucket__mold', 'cycle_config_id')
+            values('currency', 'price', 'lang__content', 'day', 'commodity_type', 'lang__title', 'expire',
+                   'commodity_code', 'discount_price', 'bucket__mold', 'cycle_config_id')
         if not sm_qs.exists():
             return response.json(173)
+        store_meal_qs = Store_Meal.objects.filter(id=rank, lang__lang='cn', is_show=0).values('lang__title',
+                                                                                              'lang__content')
+        if store_meal_qs.exists():
+            store_meal_name = store_meal_qs[0]['lang__title'] + '-' + store_meal_qs[0]['lang__content']
+        else:
+            store_meal_name = '未知套餐'
         currency = sm_qs[0]['currency']
         price = sm_qs[0]['price']
         if is_select_discount == '1':
@@ -1094,19 +1065,13 @@ class CloudStorageView(View):
             # 订阅周期扣款
             if sm_qs[0]['cycle_config_id']:
                 # 查询是否有订阅过,活跃状态
-                check_has_subscribe = Paypal.checkSubscriptions(userID, uid, rank)
+                check_has_subscribe = Paypal.checkSubscriptions(user_id, uid, rank)
                 if check_has_subscribe is False:
                     return response.json(10050)
                 sub_info = Paypal.subscriptions(store_info=sm_qs[0], lang=lang, orderID=order_id, price=price)
                 if not sub_info:
                     return response.json(10048)
-                store_meal_qs = Store_Meal.objects.filter(id=rank, lang__lang='cn', is_show=0).values('lang__title',
-                                                                                                      'lang__content')
-                if store_meal_qs.exists():
-                    store_meal_name = store_meal_qs[0]['lang__title'] + '-' + store_meal_qs[0]['lang__content']
-                else:
-                    store_meal_name = '未知套餐'
-                Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=userID,
+                Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=user_id,
                                            desc=content, payType=pay_type, payTime=now_time,
                                            price=price, currency=currency, addTime=now_time, updTime=now_time,
                                            pay_url=sub_info['url'], isSelectDiscounts=is_select_discount,
@@ -1147,13 +1112,7 @@ class CloudStorageView(View):
                 if link.rel == "approval_url":
                     approval_url = str(link.href)
                     print("Redirect for approval: %s" % approval_url)
-                    store_meal_qs = Store_Meal.objects.filter(id=rank, lang__lang='cn', is_show=0).values('lang__title',
-                                                                                                          'lang__content')
-                    if store_meal_qs.exists():
-                        store_meal_name = store_meal_qs[0]['lang__title'] + '-' + store_meal_qs[0]['lang__content']
-                    else:
-                        store_meal_name = '未知套餐'
-                    Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=userID,
+                    Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=user_id,
                                                desc=content, payType=pay_type, payTime=now_time,
                                                price=price, currency=currency, addTime=now_time, updTime=now_time,
                                                pay_url=approval_url, isSelectDiscounts=is_select_discount,
@@ -1184,15 +1143,8 @@ class CloudStorageView(View):
             else:
                 if order_string:
                     redirect_url = ali_pay_obj.alipay_prefix + order_string
-                    print('---------tttt')
                     print(redirect_url)
-                    store_meal_qs = Store_Meal.objects.filter(id=rank, lang__lang='cn', is_show=0).values('lang__title',
-                                                                                                          'lang__content')
-                    if store_meal_qs.exists():
-                        store_meal_name = store_meal_qs[0]['lang__title'] + '-' + store_meal_qs[0]['lang__content']
-                    else:
-                        store_meal_name = '未知套餐'
-                    Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=userID,
+                    Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=user_id,
                                                desc=content, payType=pay_type, payTime=now_time,
                                                price=price, currency=currency, addTime=now_time, updTime=now_time,
                                                pay_url=redirect_url, isSelectDiscounts=is_select_discount,
@@ -1220,13 +1172,7 @@ class CloudStorageView(View):
             if not response:
                 return response.json(10, '生成订单错误.')
             # 回调函数
-            store_meal_qs = Store_Meal.objects.filter(id=rank, lang__lang='cn', is_show=0).values('lang__title',
-                                                                                                  'lang__content')
-            if store_meal_qs.exists():
-                store_meal_name = store_meal_qs[0]['lang__title'] + '-' + store_meal_qs[0]['lang__content']
-            else:
-                store_meal_name = '未知套餐'
-            Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=userID,
+            Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=user_id,
                                        desc=content, payType=pay_type, payTime=now_time,
                                        price=price, currency=currency, addTime=now_time, updTime=now_time,
                                        pay_url=notify_url, isSelectDiscounts=is_select_discount,
@@ -1247,6 +1193,8 @@ class CloudStorageView(View):
         cdk = request_dict.get('cdk', None)
         lang = request_dict.get('lang', 'en')
 
+        if not all([uid]):
+            return response.json(444)
         redis_obj = RedisObject()
         is_lock = redis_obj.CONN.setnx(uid + 'do_experience_order', 1)
         redis_obj.CONN.expire(uid + 'do_experience_order', 60)
@@ -1287,13 +1235,13 @@ class CloudStorageView(View):
 
         order_id = CommonService.createOrderID()
         now_time = int(time.time())
-        sm_qs = Store_Meal.objects.filter(id=rank, lang__lang=lang, is_show=0). \
-            values("day", "bucket_id", "bucket__storeDay", "expire", 'lang__content', 'price', 'currency',
-                   'commodity_type')
+        sm_qs = Store_Meal.objects.filter(id=rank, lang__lang=lang, is_show=0).values("day", "bucket_id",
+                                                                                      "bucket__storeDay", "expire",
+                                                                                      'lang__content', 'price',
+                                                                                      'currency', 'commodity_type')
         if not sm_qs.exists():
             return response.json(173)
         bucket_id = sm_qs[0]['bucket_id']
-        # ##
         ub_qs = UID_Bucket.objects.filter(uid=uid).values("id", "bucket_id", "bucket__storeDay", "bucket__region",
                                                           "endTime", "use_status")
         expire = sm_qs[0]['expire']
@@ -1386,7 +1334,7 @@ class CloudStorageView(View):
                                              "%b %dth,%Y", time.localtime())]
                     sms = 'SMS_219748439'
 
-                self.do_vod_msg_Notice(uid, channel, user_id, lang, sys_msg_text_list, sms)
+                self.do_vod_msg_notice(uid, channel, user_id, lang, sys_msg_text_list, sms)
                 result = return_url
                 redis_obj.del_data(key=uid + 'do_experience_order')
                 return response.json(0, result)
@@ -1396,7 +1344,8 @@ class CloudStorageView(View):
             return response.json(474)
 
     # 重置设备云存体验
-    def do_experience_reset(self, request_dict, response):
+    @staticmethod
+    def do_experience_reset(request_dict, response):
         bid = request_dict.get("id", None)
         ubq = UID_Bucket.objects.filter(id=bid)
         if ubq:
@@ -1413,10 +1362,11 @@ class CloudStorageView(View):
 
         return response.json(0, '重置云存体验成功')
 
-    def deleteVodList(self, request_dict, user_id, response):  # 删除播放列表
+    @staticmethod
+    def delete_vod_list(request_dict, user_id, response):  # 删除播放列表
         uid = request_dict.get('uid', None)
-        dv_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1) \
-            .values('vodPrimaryUserID')
+        dv_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1).values(
+            'vodPrimaryUserID')
         if not dv_qs.exists() or dv_qs[0]['vodPrimaryUserID'] != user_id:
             return response.json(12)
         vod_id_list = json.loads(request_dict.get('vod_id_list', None))
@@ -1434,11 +1384,12 @@ class CloudStorageView(View):
             return response.json(0)
 
     # 设备关联套餐列表
-    def device_commodity(self, request_dict, user_id, response):
+    @staticmethod
+    def device_commodity(request_dict, user_id, response):
         uid = request_dict.get('uid', None)
         lang = request_dict.get('lang', 'en')
-        dv_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1) \
-            .values('vodPrimaryUserID', 'serial_number', 'Type')
+        dv_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1).values(
+            'vodPrimaryUserID', 'serial_number', 'Type')
         if not dv_qs.exists() or dv_qs[0]['vodPrimaryUserID'] != user_id:
             return response.json(12)
         now_time = int(time.time())
@@ -1464,8 +1415,10 @@ class CloudStorageView(View):
         store_list.append(uid_bucket[0])
         bucket_id_list.append(uid_bucket[0]['bucket__id'])
         if has_unused == 1:
-            unuseds = Unused_Uid_Meal.objects.filter(uid=uid).annotate(unused_id=F('id')) \
-                .values("unused_id", "uid", "bucket__content", "num", "bucket__id", "expire")
+            unuseds = Unused_Uid_Meal.objects.filter(uid=uid).annotate(unused_id=F('id')).values("unused_id", "uid",
+                                                                                                 "bucket__content",
+                                                                                                 "num", "bucket__id",
+                                                                                                 "expire")
             month = 'month' if lang != 'cn' else '个月'
             for ub in unuseds:
                 storage_time = ub['num'] * ub['expire']
@@ -1495,10 +1448,11 @@ class CloudStorageView(View):
         return response.json(0, list(store_list))
 
     # 提前使用设备关联套餐
-    def switch_device_commodity(self, request_dict, user_id, response):
+    @staticmethod
+    def switch_device_commodity(request_dict, user_id, response):
         uid = request_dict.get('uid', None)
-        dv_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1) \
-            .values('vodPrimaryUserID')
+        dv_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1).values(
+            'vodPrimaryUserID')
         if not dv_qs.exists() or dv_qs[0]['vodPrimaryUserID'] != user_id:
             return response.json(12)
         unused_id = request_dict.get('switch_commodity_id', None)
@@ -1516,8 +1470,8 @@ class CloudStorageView(View):
                 with transaction.atomic():
                     count_unused = Unused_Uid_Meal.objects.filter(uid=uid).count()
                     has_unused = 1 if count_unused > 1 else 0
-                    endTime = CommonService.calcMonthLater(unused['expire'] * unused['num'])
-                    UID_Bucket.objects.filter(uid=uid).update(channel=unused['channel'], endTime=endTime,
+                    end_time = CommonService.calcMonthLater(unused['expire'] * unused['num'])
+                    UID_Bucket.objects.filter(uid=uid).update(channel=unused['channel'], endTime=end_time,
                                                               bucket_id=unused['bucket_id']
                                                               , updateTime=now_time, use_status=1,
                                                               has_unused=has_unused)
@@ -1529,7 +1483,8 @@ class CloudStorageView(View):
             return response.json(0)
         return response.json(444)
 
-    def has_vod(self, request_dict, user_id, response):
+    @staticmethod
+    def has_vod(request_dict, user_id, response):
         uid = request_dict.get('uid', None)
         channel = request_dict.get('channel', 1)
         dv_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False).values('vodPrimaryUserID',
@@ -1558,7 +1513,8 @@ class CloudStorageView(View):
 
         return response.json(0, had_vod_list)
 
-    def videoPlaybackTime(self, request_dict, user_id, response):
+    @staticmethod
+    def video_playback_time(request_dict, user_id, response):
         parms = request_dict.get('parms', None)
 
         if not parms:
@@ -1583,7 +1539,7 @@ class CloudStorageView(View):
             return response.json(500, repr(e))
 
     # 云存操作系统消息
-    def do_vod_msg_Notice(self, uid, channel, user_id, lang, sys_msg_text_list, sms):
+    def do_vod_msg_notice(self, uid, channel, user_id, lang, sys_msg_text_list, sms):
         try:
             logger = logging.getLogger('log')
             logger.info('进来了')
@@ -1614,9 +1570,7 @@ class CloudStorageView(View):
                         device_name = uid
                     params = u'{"devname":"' + device_name + '","submittime":"' + time.strftime("%Y-%m-%d",
                                                                                                 time.localtime()) + '"}'
-                    self.sendMessage(username, params, sms)
-
-                self.pushApp(now_time, uid, channel, sys_msg_text)
+                    self.send_message(username, params, sms)
 
             logger.info('出去了')
         except Exception as e:
@@ -1663,12 +1617,11 @@ class CloudStorageView(View):
                     else:
                         device_name = uid
                     if ub['bucket__area'] == 'cn':
-                        sys_msg_text = "温馨提示:尊敬的客户,您" + device_name + "设备的云存套餐将在" + time.strftime("%Y-%m-%d",
-                                                                                                  time.localtime(ub[
-                                                                                                                     'endTime'])) + "到期"
+                        sys_msg_text = "温馨提示:尊敬的客户,您%s设备的云存套餐将在%s到期" % (
+                            device_name, time.strftime("%Y-%m-%d", time.localtime(ub['endTime'])))
                     else:
-                        sys_msg_text = 'Dear customer,the cloud storage package for your device ' + device_name + ' will expire on ' + time.strftime(
-                            '%m-%d-%y', time.localtime(ub['endTime']))
+                        sys_msg_text = 'Dear customer,the cloud storage package for your device %s will expire on %s' % \
+                                       (device_name, time.strftime('%m-%d-%y', time.localtime(ub['endTime'])))
                     uq_list.append(SysMsgModel(
                         userID_id=oo['userID_id'],
                         addTime=now_time,
@@ -1688,137 +1641,27 @@ class CloudStorageView(View):
                         if data_valid.email_validate(username):
                             S3Email().faEmail(sys_msg_text, username)
                         elif data_valid.mobile_validate(username):
-                            params = u'{"devname":"' + device_name + '","submittime":"' + time.strftime("%Y-%m-%d",
-                                                                                                        time.localtime(
-                                                                                                            ub[
-                                                                                                                'endTime'])) + '"}'
-                            self.sendMessage(username, params, 'SMS_219748440')
-
-                        self.pushApp(now_time, ub['uid'], ub['channel'], sys_msg_text)
-
-    def pushApp(self, now_time, uid, channel, sys_msg_text):
-        n_time = now_time
-
-        kwag_args = {
-            'uid': uid,
-            'channel': channel,
-            'event_type': 0,
-            'n_time': n_time
-        }
-
-        # 从数据库查询出来
-        uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
-            values('token_val', 'app_type', 'appBundleId', 'm_code',
-                   'push_type', 'userID_id', 'userID__NickName',
-                   'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
-                   'uid_set__channel')
-        print(uid_push_qs)
-        # 新建一个list接收数据
-        redis_list = []
-        # 把数据库数据追加进redis_list
-        for qs in uid_push_qs:
-            redis_list.append(qs)
-
-        nickname = redis_list[0]['uid_set__nickname']
-
-        for up in redis_list:
-            push_type = up['push_type']
-            app_bundle_id = up['appBundleId']
-            token_val = up['token_val']
-
-            package_title_config = FCM_CONFIG[app_bundle_id]
-            if app_bundle_id in package_title_config.keys():
-                msg_title = package_title_config[app_bundle_id] + '(' + nickname + ')'
-            else:
-                msg_title = nickname
-
-            # 发送内容
-            msg_text = sys_msg_text
-            kwag_args['appBundleId'] = app_bundle_id
-            kwag_args['token_val'] = token_val
-            kwag_args['msg_title'] = msg_title
-            kwag_args['msg_text'] = msg_text
-            # 推送
-            if push_type == 0:  # ios apns
-
-                try:
-                    cli = apns2.APNSClient(mode=APNS_MODE,
-                                           client_cert=os.path.join(BASE_DIR,
-                                                                    APNS_CONFIG[app_bundle_id]['pem_path']))
-
-                    push_data = {"alert": "Motion ", "event_time": n_time, "event_type": 0, "msg": "",
-                                 "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1",
-                                 "channel": channel}
-                    alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
-                    payload = apns2.Payload(alert=alert, custom=push_data)
-
-                    n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
-                    res = cli.push(n=n, device_token=token_val, topic=app_bundle_id)
-                    print(res.status_code)
-                    if res.status_code == 200:
-                        return res.status_code
-                    else:
-                        print('apns push fail')
-                        print(res.reason)
-                        return res.status_code
-                except (ValueError, ArithmeticError):
-                    return 'The program has a numeric format exception, one of the arithmetic exceptions'
-                except Exception as e:
-                    print(repr(e))
-                    return repr(e)
-
-            elif push_type == 1:  # android gcm
-                try:
-                    server_key = FCM_CONFIG[app_bundle_id]
-                except Exception as e:
-                    return 'serverKey abnormal'
-                push_service = FCMNotification(api_key=server_key)
-                data = {"alert": "Motion ", "event_time": n_time, "event_type": 0, "msg": "",
-                        "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
-                result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
-                                                           message_body=msg_text, data_message=data,
-                                                           extra_kwargs={
-                                                               'default_vibrate_timings': True,
-                                                               'default_sound': True,
-                                                               'default_light_settings': True
-                                                           })
-                print('fcm push ing')
-                print(result)
-                return result
-            elif push_type == 2:  # android jpush
-                print('do_jpush')
-                app_key = JPUSH_CONFIG[app_bundle_id]['Key']
-                master_secret = JPUSH_CONFIG[app_bundle_id]['Secret']
-                # 此处换成各自的app_key和master_secre
-                _jpush = jpush.JPush(app_key, master_secret)
-                push = _jpush.create_push()
-                push.audience = jpush.registration_id(token_val)
-                push_data = {"alert": "Motion ", "event_time": n_time, "event_type": 0, "msg": "",
-                             "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
-                android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
-                                        big_text=msg_text, title=msg_title,
-                                        extras=push_data)
-                push.notification = jpush.notification(android=android)
-                push.platform = jpush.all_
-                res = push.send()
-                print(res)
-                return res.status_code
-
-    def sendMessage(self, phone, params, temp_msg):
+                            params = u'{"devname":"%s","submittime":"%s"}' % (
+                                device_name, time.strftime("%Y-%m-%d", time.localtime(ub['endTime'])))
+                            self.send_message(username, params, 'SMS_219748440')
+
+    @staticmethod
+    def send_message(phone, params, temp_msg):
         # 购买成功
         sign_ms = '周视'
         # 发送手机验证码
         ali_sms = AliSmsObject()
         ali_sms.send_code_sms_cloud(phone=phone, params=params, sign_name=sign_ms, temp_msg=temp_msg)
 
-    def do_refund(self, request_dict, response):
+    @staticmethod
+    def do_refund(request_dict, response):
         order_id = request_dict.get('orderID', None)  # 商户订单号
         refund_amount = request_dict.get('refund_amount', None)  # 退款金额
         if not all([order_id, refund_amount]):
             return response.json(444)
         try:
-            order_qs = Order_Model.objects.filter(orderID=order_id). \
-                values('status', 'payType', 'price', 'refunded_amount', 'currency', 'paymentID')
+            order_qs = Order_Model.objects.filter(orderID=order_id).values('status', 'payType', 'price',
+                                                                           'refunded_amount', 'currency', 'paymentID')
             if not order_qs.exists():
                 return response.json(173)
 
@@ -1858,8 +1701,8 @@ class CloudStorageView(View):
                 sale = related_resources[0]['sale']
                 print('sale: ', sale)
                 # 没退款过 'state' 不为 'completed' 或 已退款过但 'state' 不为 'partially_refunded'
-                if (refunded_amount == 0 and sale['state'] != 'completed') or \
-                        (refunded_amount != 0 and sale['state'] != 'partially_refunded'):
+                if (refunded_amount == 0 and sale['state'] != 'completed') or (
+                        refunded_amount != 0 and sale['state'] != 'partially_refunded'):
                     return response.json(805)
                 sale_id = sale['id']
                 paypal_sale = paypalrestsdk.Sale.find(sale_id)