| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053 | #!/usr/bin/env python3# -*- coding: utf-8 -*-"""@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.@AUTHOR: ASJRD018@NAME: Ansjer@software: PyCharm@DATE: 2018/5/22 13:58@Version: python3.6@MODIFY DECORD:ansjer dev@file: Test.py@Contact: chanjunkai@163.com"""import osimport tracebackimport botocoreimport cv2from botocore import clientfrom django.db import transactionfrom Ansjer.cn_config.config_formal import CONFIG_INFOfrom Ansjer.config import CONFIG_INFOfrom Controller.DeviceConfirmRegion import Device_Regionfrom Object.AWS.AmazonS3Util import AmazonS3Utilfrom Object.RedisObject import RedisObjectfrom Service.VodHlsService import SplitVodHlsObject'''http://192.168.136.40:8077/Test'''import jsonimport timeimport urllibimport requestsfrom Object.AliPayObject import AliPayObjectimport boto3from boto3.session import Sessionimport oss2import paypalrestsdkimport loggingfrom django.http import JsonResponse, HttpResponsefrom django.utils.decorators import method_decoratorfrom django.views.decorators.csrf import csrf_exemptfrom django.views.generic.base import Viewfrom django.contrib.auth.hashers import make_password  # 对密码加密模块from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, AWS_ACCESS_KEY_ID, \    AWS_SECRET_ACCESS_KEY, SERVER_TYPE, AWS_SES_ACCESS_REGIONfrom Model.models import Order_Model, Store_Meal, DeviceLogModel, VodBucketModel, \    TestSerialRepetition, UIDCompanySerialModel, CompanySerialModel, LogModelfrom Object.ResponseObject import ResponseObjectfrom Object.TokenObject import TokenObjectfrom Service.CommonService import CommonServicefrom Object.m3u8generate import PlaylistGeneratorfrom Model.models import Device_Info, UID_Bucket, UID_Preview, UidSetModelfrom Ansjer.config import SERVER_DOMAIN_SSLSERVER_DOMAIN = 'http://test.dvema.com/'ACCESS_KEY = "AKIA2E67UIMD3CYTIWPA"SECRET_KEY = "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"LOGGER = logging.getLogger('info')# 测试接口sdkclass testView(View):    @method_decorator(csrf_exempt)    def dispatch(self, *args, **kwargs):        return super(testView, self).dispatch(*args, **kwargs)    def get(self, request, *args, **kwargs):        request.encoding = 'utf-8'        operation = kwargs.get('operation')        return self.validation(request.GET, request, operation)    def post(self, request, *args, **kwargs):        request.encoding = 'utf-8'        operation = kwargs.get('operation')        return self.validation(request.POST, request, operation)    def put(self, request, *args, **kwargs):        request.encoding = 'utf-8'        operation = kwargs.get('operation')        response = ResponseObject()        return response.json(0, request.body)    def validation(self, request_dict, request, operation):        response = ResponseObject()        # operation => cloudVod/path        if operation is None:            return response.json(444, 'error path')        elif operation == 'tests':            logger = logging.getLogger('info')            logger.info('测试打印')            res = make_password(123456)            return JsonResponse(status=200, data=res, safe=False)        elif operation == 'testMiddleWare':            a = int('a')            return JsonResponse(status=200, safe=False)        elif operation == 'testMiddleWare2':            try:                a = int('a')                return JsonResponse(status=200, safe=False)            except Exception as e:                return response.json(500, repr(e))        elif operation == 'cbu':            return self.createBucket()        elif operation == 'vodList':            ip = CommonService.get_ip_address(request)            userID = '158943594633713800138000'            return self.do_test_query_vod_list(userID, ip, request_dict, response)        elif operation == 'signplaym3u8':            return self.do_sign_play_m3u8(request_dict, response)        elif operation == 'get_sign_sts':            ip = CommonService.get_ip_address(request)            return self.do_test_get_sign_sts(request_dict, ip, response)        elif operation == 'eqi_query':            userID = '158943594633713800138000'            return self.queryInterface(request_dict, userID, response)        elif operation == 'getAlexa':            userID = '158943594633713800138000'            return self.queryInterface(request_dict, userID, response)        elif operation == 'generateToken':            userID = '158943604783713800138000'            return self.generate_token(request_dict, userID)        elif operation == 'test_upload_s3':            userID = '158943604783713800138000'            return self.test_upload_s3(request_dict, response)        elif operation == 'rekognition':            userID = '158943604783713800138000'            return self.testRekognition(request, request_dict)        elif operation == 'ip':            return self.ip(response)        elif operation == 'configType':            return self.configType(response)        elif operation == 'createData':            return self.createData(request_dict, response)        elif operation == 'findPaypalOrder':            return self.findPaypalOrder(request_dict, response)        elif operation == 'comb':            return self.do_comb(request_dict, response)        elif operation == 'count_ts':            return self.count_ts(request_dict, response)        elif operation == 'upload-s3':            return self.file_upload_s3(request, request_dict, response)        elif operation == 'v2/upload-s3':            return self.file_upload_s3_v2(request, request_dict, response)        elif operation == 'download-s3':            return self.file_download_s3(request_dict, response)        elif operation == 'acl-put':            return self.s3_acl_put(request_dict, response)        elif operation == 's3-object-delete':            return self.object_delete(request_dict, response)        elif operation == 'head-bucket':            return self.head_bucket(request_dict, response)        elif operation == 'write_redis_list':            return self.write_redis_list(response)        elif operation == 'read_redis_list':            return self.read_redis_list(response)        elif operation == 'playM3u8':            return self.play_m3u8(request_dict, response)        elif operation == 'generate_video':            return self.generate_video(request_dict, response)        elif operation == 'serial-repetition':  # 用与测试序列号重复接口            response = ResponseObject('cn')            return response.json(475)        elif operation == 'v2/serial-repetition':  # 用与测试序列号重复接口            response = ResponseObject('cn')            return self.serial_repetition_test_v2(request_dict, response)        elif operation == 'getSerialNumberInfo':  # 序列号信息查询            return self.getSerialNumberInfo(request_dict, response)        elif operation == 'get-serial-details':  # 序列号信息查询            return self.get_serial_details(request_dict, response, request)        elif operation == 'checkOrderExist':  # 检查paypal订单是否存在            return self.checkOrderExist(request_dict, response)        else:            return 123    @classmethod    def serial_repetition_test_v2(cls, request_dict, response):        try:            serial_no = request_dict.get('serialNo', None)            phone_model = request_dict.get('phoneModel', None)            if not serial_no:                return response.json(444)            with transaction.atomic():                first_serial = serial_no[:6]                first_serial_qs = TestSerialRepetition.objects.filter(serial_number__icontains=first_serial)                if first_serial_qs.exists():                    result = {'serialNumber': first_serial_qs.first().serial_number,                              'phoneModel': first_serial_qs.first().phone_model,                              'createdTime': first_serial_qs.first().created_time}                    return response.json(174, result)                serial_qs = TestSerialRepetition.objects.filter(serial_number=serial_no)                if not serial_qs.exists():                    n_time = int(time.time())                    params = {'serial_number': serial_no, 'created_time': n_time}                    if phone_model:                        params['phone_model'] = phone_model                    TestSerialRepetition.objects.create(**params)                    return response.json(0)                else:                    return response.json(174)        except Exception as e:            logging.info('异常错误,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))            return response.json(178, e)    @classmethod    def serial_repetition_test(cls, request_dict, response):        return response.json()        # try:        #     serial_no = request_dict.get('serialNo', None)        #     if not serial_no:        #         return response.json(444)        #     with transaction.atomic():        #         first_serial = serial_no[:6]        #         first_serial_qs = TestSerialRepetition.objects.filter(serial_number__icontains=first_serial)        #         if first_serial_qs.exists():        #             return response.json(174)        #         serial_qs = TestSerialRepetition.objects.filter(serial_number=serial_no)        #         if not serial_qs.exists():        #             n_time = int(time.time())        #             params = {'serial_number': serial_no, 'created_time': n_time}        #             TestSerialRepetition.objects.create(**params)        #             return response.json(0)        #         else:        #             return response.json(174)        # except Exception as e:        #     logging.info('异常错误,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))        #     return response.json(178, e)    @classmethod    def generate_video(cls, request_dict, response):        # 设计抽取图片规则通过消息随机还是时间随机,调试copy S3对象查询是否携带失效时间        try:            DIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))            arr_list = ['1666756086.jpeg', '1666831275.jpeg', '1666841492.jpeg']            s3 = AmazonS3Util(AWS_ACCESS_KEY_ID[0], AWS_SECRET_ACCESS_KEY[0], 'cn-northwest-1')            bucket = 'push-cloud-photo'            for item in arr_list:                path = DIR + r'\Ansjer\file\{}'.format(item)                s3_key = 'HA154GVEDH41RY8Y111A/1/{}'.format(item)                s3.download_object(bucket, s3_key, path)            video_dir = DIR + r'\Ansjer\file\result.mp4'  # 输出视频的保存路径            fps = 0.5  # 帧率            img_size = (1920, 1080)  # 图片尺寸            fourcc = cv2.VideoWriter_fourcc(*"mp4v")            videoWriter = cv2.VideoWriter(video_dir, fourcc, fps, img_size)            for i in arr_list:                img_path = DIR + r'\Ansjer\file\{}'.format(i)                frame = cv2.imread(img_path)                frame = cv2.resize(frame, img_size)  # 生成视频   图片尺寸和设定尺寸相同                videoWriter.write(frame)  # 将图片写进视频里                os.remove(img_path)            videoWriter.release()  # 释放资源            data = open(video_dir, 'rb')            key = 'HA154GVEDH41RY8Y111A/1/20221027.mp4'            s3.upload_file_obj(bucket, key, data)            response_url = s3.generate_file_obj_url(bucket, key)            os.remove(video_dir)        except Exception as e:            print(e)            ex = traceback.format_exc()            LOGGER.info('--->抽取推送图片异常:{}'.format(ex))            return response.json(177, ex)        return response.json(0, response_url)    @classmethod    def head_bucket(cls, request_dict, response):        bucket_name = request_dict.get('bucket', None)        s3 = AmazonS3Util('AKIA2E67UIMD45Y3HL53', 'ckYLg4Lo9ZXJIcJEAKkzf2rWvs8Xth1FCjqiAqUw', 'us-east-1')        s3.bucket_exists(bucket_name)        return response.json(0)    @classmethod    def file_upload_s3(cls, request, request_dict, response):        file = request.FILES.get('file', None)        file_name = file.name        file_name = 'app/images/{}'.format(file_name)        cls.upload_s3(file, file_name)        return response.json(0)    @classmethod    def file_upload_s3_v2(cls, request, request_dict, response):        """        'private' | 'public-read' | 'public-read-write' | 'authenticated-read'        """        file = request.FILES.get('file', None)        file_name = file.name        # S3下文件夹路径+文件名 组成对象key        file_key = 'app/images/{}'.format(file_name)        s3 = AmazonS3Util(AWS_ACCESS_KEY_ID[1], AWS_SECRET_ACCESS_KEY[1], AWS_SES_ACCESS_REGION)        # 存储桶        bucket = 'ansjerfilemanager'        s3.upload_file_obj(bucket, file_key, file, {'ContentType': file.content_type, 'ACL': 'public-read'})        return response.json(0)    @classmethod    def object_delete(cls, request_dict, response):        file_name = request_dict.get('key', None)        file_key = 'app/images/{}'.format(file_name)        s3 = AmazonS3Util('AKIA2E67UIMD45Y3HL53', 'ckYLg4Lo9ZXJIcJEAKkzf2rWvs8Xth1FCjqiAqUw', 'us-east-1')        bucket = "ansjerfilemanager"        s3.delete_obj(bucket, file_key)        return response.json(0)    @staticmethod    def upload_s3(data, upload_path):        """        上传对象到对应存储桶        @param data:        @param upload_path:        @return:        """        try:            aws_key = "AKIA2E67UIMD45Y3HL53"  # 【你的 aws_access_key】            aws_secret = "ckYLg4Lo9ZXJIcJEAKkzf2rWvs8Xth1FCjqiAqUw"  # 【你的 aws_secret_key】            session = Session(aws_access_key_id=aws_key,                              aws_secret_access_key=aws_secret,                              region_name="us-east-1")            s3 = session.resource("s3")            # client = session.client("s3")            bucket = "ansjerfilemanager"  # 【你 bucket 的名字】 # 首先需要保.证 s3 上已经存在该存储桶,否则报错            # upload_key = "test"            s3.Bucket(bucket).put_object(Key=upload_path, Body=data)            return True        except Exception as e:            print(repr(e))            return False    @classmethod    def s3_acl_put(cls, request_dict, response):        """        S3通过存储桶对象设置Acl权限        @param request_dict:        @param response:        @return:        """        try:            key = request_dict.get('key', None)            aws_key = "AKIA2E67UIMD45Y3HL53"  # 【你的 aws_access_key】            aws_secret = "ckYLg4Lo9ZXJIcJEAKkzf2rWvs8Xth1FCjqiAqUw"  # 【你的 aws_secret_key】            session = Session(aws_access_key_id=aws_key,                              aws_secret_access_key=aws_secret,                              region_name="us-east-1")            s3 = session.resource("s3")            # client = session.client("s3")            bucket = "ansjerfilemanager"  # 【你 bucket 的名字】 # 首先需要保.证 s3 上已经存在该存储桶,否则报错            # upload_key = "test"            obj = s3.Object(bucket, key)            obj.Acl().put(ACL='public-read')            return response.json(0)        except Exception as e:            print(repr(e))            return False    @classmethod    def file_download_s3(cls, request_dict, response):        """        S3通过签名获取对象URL        @param request_dict:        @param response:        @return:        """        key = request_dict.get('key', None)        s3_client = AmazonS3Util('AKIA2E67UIMD45Y3HL53', 'ckYLg4Lo9ZXJIcJEAKkzf2rWvs8Xth1FCjqiAqUw', 'us-east-1')        bucket = "ansjerfilemanager"        response_url = s3_client.generate_file_obj_url(bucket, key)        return response.json(0, response_url)    def do_comb(self, request_dict, response):        import itertools        list1 = [1, 2, 3, 4]        list2 = []        for i in range(1, len(list1) + 1):            iter = itertools.combinations(list1, i)            list2.append(list(iter))        list3 = []        for list_ in list2:            for val in list_:                print('-------------list')                print(type(val))                comb = [str(i) for i in val]                comb_int = int("".join(comb))                list3.append(comb_int)        return HttpResponse(json.dumps(list3))    def findPaypalOrder(self, request_dict, response):        PAYPAL_CRD = {            "mode": "sandbox",  # sandbox or live            "client_id": "AVLoQVq3xHZ6FrF4mxHwlCPgVBAw4Fw5RtMkuxmYd23SkUTIY643n2g3KdK-Al8wV05I28lza5uoQbAA",            "client_secret": "EO8kRc8yioDk0i2Qq-QMcVFfwkmyMJorTvBSLDTnxDJJ_wb9VoM_0jkUY9iEng2Flp1ze8wQOGpH5nB2"        }        paypalrestsdk.configure(PAYPAL_CRD)        billing_agreement = paypalrestsdk.BillingAgreement.find('I-7P8BCCKE45HY')        # json_str = json.dumps(billing_agreement, default=lambda o: o.__dict__)        # return HttpResponse(json_str)        print(repr(billing_agreement))        return HttpResponse(repr(billing_agreement))        return response.json(json.dumps(list(payment)))        logger = logging.getLogger('info')        logger.info('------记录aws bucket init时间')        logger.info(int(time.time()))        aws_access_key_id = AWS_ACCESS_KEY_ID[1]        aws_secret_access_key = AWS_SECRET_ACCESS_KEY[1]        session = Session(            aws_access_key_id=aws_access_key_id,            aws_secret_access_key=aws_secret_access_key,            region_name='us-east-1'        )        conn = session.client('s3')        logger.info(int(time.time()))        exit()        # related_resources = payment['transactions'][0]['related_resources']        # if not related_resources:        #     return response.json(805)        # sale = related_resources[0]['sale']        # print(related_resources)        # return HttpResponse(sale)    def createBucket(self):        # 查看桶列表        # url = "https://azvod1.s3-ap-northeast-1.amazonaws.com"        # session = Session(ACCESS_KEY, SECRET_KEY)        # s3_client = session.client('s3', endpoint_url=url)        # results = s3_client.list_buckets()        # return JsonResponse(status=200, data={'code': 200, 'msg': results['Buckets']})        # Create bucket        session = Session(ACCESS_KEY, SECRET_KEY)        s3_client = session.client('s3')        # 上传        # s3_client.put_object(Bucket="azvod1", Key="file/rule.txt", Body=open(r"E:\download\Shadowsocks-4.1.10.0\user-rule.txt", 'rb').read())        # 下载        resp = s3_client.get_object(Bucket="azvod1", Key="file/rule.txt")        with open('local.txt', 'wb') as f:            f.write(resp['Body'].read())    # 新查询设备字段    def queryInterface(self, request_dict, userID, response):        page = request_dict.get('page', None)        line = request_dict.get('line', None)        NickName = request_dict.get('NickName', None)        uid = request_dict.get('uid', None)        page = int(page)        line = int(line)        response.lang = 'cn'        userID = userID        dvqs = Device_Info.objects.filter(userID_id=userID)        # # 已重置的设备        # dvqs = dvqs.filter(~Q(isExist=2))        if NickName:            dvqs = dvqs.filter(NickName__icontains=NickName)        if uid:            dvqs = dvqs.filter(UID=uid)        # count = dvqs.count()        # 分页        dvql = dvqs[(page - 1) * line:page * line].values('id', 'userID', 'NickName', 'UID', 'View_Account',                                                          'View_Password', 'ChannelIndex', 'Type', 'isShare',                                                          'primaryUserID', 'primaryMaster', 'data_joined',                                                          'version',                                                          'isVod', 'isExist', 'NotificationMode')        dvls = CommonService.qs_to_list(dvql)        uid_list = []        for dvl in dvls:            uid_list.append(dvl['UID'])            # if dvl['isShare'] is False:            #     uid_list.append(dvl['UID'])        ubqs = UID_Bucket.objects.filter(uid__in=uid_list). \            values('bucket__content', 'status', 'channel', 'endTime', 'uid')        upqs = UID_Preview.objects.filter(uid__in=uid_list).order_by('channel').values('id', 'uid', 'channel')        auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)        bucket = oss2.Bucket(auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')        nowTime = int(time.time())        data = []        # 设备拓展信息表        us_qs = UidSetModel.objects.filter(uid__in=uid_list). \            values('uid', 'version', 'nickname', 'detect_interval')        uv_dict = {}        for us in us_qs:            uv_dict[us['uid']] = {'version': us['version'],                                  'nickname': us['nickname'],                                  'detect_interval': us['detect_interval']}        for p in dvls:            p['vod'] = []            for dm in ubqs:                if p['UID'] == dm['uid']:                    if dm['endTime'] > nowTime:                        p['vod'].append(dm)            p['preview'] = []            for up in upqs:                if p['UID'] == up['uid']:                    obj = 'uid_preview/{uid}/channel_{channel}.png'. \                        format(uid=up['uid'], channel=up['channel'])                    img_sign = bucket.sign_url('GET', obj, 300)                    p['preview'].append(img_sign)            p_uid = p['UID']            if p_uid in uv_dict:                # 设备版本号                p['uid_version'] = uv_dict[p_uid]['version']                p['detect_interval'] = uv_dict[p_uid]['detect_interval']                # 设备昵称 调用影子信息昵称,先阶段不可                if uv_dict[p_uid]['nickname']:                    p['NickName'] = uv_dict[p_uid]['nickname']            else:                # 设备版本号                p['uid_version'] = ''            data.append(p)        return response.json(0, data)    # 获取播放列表    def do_test_query_vod_list(self, userID, ip, request_dict, response):        uid = 'GZL2PEFJPLY7W6BG111A'        channel = 2        userID = '158943594633713800138000'        dv_qs = Device_Info.objects.filter(UID=uid, userID_id=userID, isShare=False)        if not dv_qs.exists():            return response.json(12)        vod_play_list = []        bucket_name = 'azvod1'        aws_access_key_id = 'AKIA2E67UIMD45Y3HL53'        aws_secret_access_key = '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'        session = Session(            aws_access_key_id=aws_access_key_id,            aws_secret_access_key=aws_secret_access_key,            region_name='ap-northeast-1'        )        conn = session.client('s3')        thumbspng = '{uid}/vod{channel}/{time}/thumbs.png'. \            format(uid=uid, channel=channel, time=1590485548)        response_url = conn.generate_presigned_url(            'get_object',            Params={                'Bucket': bucket_name,                'Key': thumbspng            },            ExpiresIn=3600        )        # m3u8 = '{uid}/vod{channel}/{time}/{time}.m3u8'. \        #     format(uid=uid, channel=channel, time=vod['time'])        thumb_url = response_url        vod_url = 'http://192.168.136.191:8000/testApi/signplaym3u8?' \                  'uid={uid}&channel={channel}&time={time}&sign=tktktktk'. \            format(ip=ip, uid=uid, channel=channel, time=1590485548)        vod_play_list.append({            'name': 1590485548,            'sign_url': vod_url,            'thumb': thumb_url,            'sec': 12})        return response.json(0, vod_play_list)    # 生成m3u8列表    def do_sign_play_m3u8(self, request_dict, response):        uid = 'GZL2PEFJPLY7W6BG111A'        channel = 2        storeTime = 1591344070        fg = 6        bucket__region = 'ap-northeast-1'        bucket_name = 'azvod1'        aws_access_key_id = 'AKIA2E67UIMD45Y3HL53'        aws_secret_access_key = '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'        session = Session(            aws_access_key_id=aws_access_key_id,            aws_secret_access_key=aws_secret_access_key,            region_name=bucket__region        )        '''            http://test.dvema.com/cloudstorage/signplaym3u8?uid=VVDHCVBYDKFMJRWA111A&channel=1&time=1586940120&sign=tktktktk        '''        conn = session.client('s3')        playlist_entries = []        for i in range(fg):            thumbspng = '{uid}/vod{channel}/{time}/ts{i}.ts'. \                format(uid=uid, channel=channel, time=storeTime, i=i)            response_url = conn.generate_presigned_url(                'get_object',                Params={                    'Bucket': bucket_name,                    'Key': thumbspng                },                ExpiresIn=86400            )            # m3u8 = '{uid}/vod{channel}/{time}/{time}.m3u8'. \            #     format(uid=uid, channel=channel, time=vod['time'])            playlist_entries.append({                'name': response_url,                'duration': 10,            })        playlist = PlaylistGenerator(playlist_entries).generate()        response = HttpResponse(playlist)        response['Content-Type'] = 'application/octet-stream'        response['Content-Disposition'] = 'attachment;filename="play.m3u8"'        return response        # return HttpResponse(playlist)        # response = HttpResponse(playlist, content_type="application/vnd.apple.mpegurl")        # # response = HttpResponse(playlist, content_type="application/octet-stream")        # return response        # return HttpResponse(status=200, content=playlist)    def do_pay_by_ali(self, request_dict, userID, response):        uid = request_dict.get('uid', None)        rank = request_dict.get('rank', None)        channel = request_dict.get('channel', None)        qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False)        if not qs.exists():            return response.json(12)        if not channel or not rank:            return response.json(444, 'channel,rank')        smqs = Store_Meal.objects.filter(id=rank). \            values("currency", "price", "content", "day", "bucket__storeDay", "bucket__region", "type")        if not smqs.exists():            # 套餐不存在            return response.json(173)        if smqs[0]['type'] != 1:            return response.json(10, '不支持支付宝支付')        currency = smqs[0]['currency']        price = smqs[0]['price']        content = smqs[0]['content']        day = smqs[0]['day']        nowTime = int(time.time())        ubqs = UID_Bucket.objects.filter(uid=uid, channel=channel, endTime__gte=nowTime). \            values("bucket__storeDay", "bucket__region")        if ubqs.exists():            if ubqs[0]['bucket__region'] != smqs[0]['bucket__region']:                return response.json(712)  # 区域不一致            elif ubqs[0]['bucket__storeDay'] != smqs[0]['bucket__storeDay']:                return response.json(713)  # 不可更改套餐            # 续费流程        nowTime = int(time.time())        # 新增流程        orderID = CommonService.createOrderID()        try:            aliPayObj = AliPayObject()            alipay = aliPayObj.conf()            order_string = alipay.api_alipay_trade_wap_pay(                out_trade_no=orderID,                total_amount=price,                subject="测试哟",                return_url="{SERVER_DOMAIN_SSL}cloudVod/payOK".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL),                notify_url="{SERVER_DOMAIN_SSL}cloudVod/aliPayCallback".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)                # return_url="http://192.168.136.40/cloudVod/payOK",                # notify_url="http://192.168.136.40/cloudVod/aliPayCallback"            )        except Exception as e:            print(repr(e))            return response.json(10, repr(e))        if order_string:            redirectUrl = aliPayObj.alipay_prefix + order_string            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=orderID, UID=uid, channel=channel, userID_id=userID, desc=content,                                       price=price, currency=currency, addTime=nowTime, updTime=nowTime,                                       endTime=nowTime + int(day) * 3600 * 24, rank_id=rank, payType=1,                                       store_meal_name=store_meal_name)            return JsonResponse(status=200,                                data={'result_code': 0, 'reason': 'success',                                      'result': {"redirectUrl": redirectUrl, "orderID": orderID},                                      'error_code': 0})        else:            return response.json(10, '生成订单错误')    def do_filter_playlist(self, request_dict, userID, response):        startTime = int(request_dict.get('startTime', None))        endTime = int(request_dict.get('endTime', None))        uid = request_dict.get('uid', None)        channel = request_dict.get('channel', None)        dvqs = Device_Info.objects.filter(UID=uid, userID_id=userID, isShare=False)        if not dvqs.exists():            return response.json(12)        ubqs = UID_Bucket.objects.filter(uid=uid, channel=channel).values('status')        if not ubqs.exists():            return response.json(10, '设备未购买')        split_vod_hls_obj = SplitVodHlsObject()        vodqs = split_vod_hls_obj.get_vod_hls_data(uid=uid, channel=channel).values("start_time", "sec", "bucket_id")        if not vodqs.exists():            return response.json(173)        vod_play_list = []        auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)        bucket_id = vodqs[0]['bucket_id']        vod_bucket_qs = VodBucketModel.objects.filter(id=bucket_id).values('bucket', 'endpoint')        if not vod_bucket_qs.exists():            return response.json(173)        bucket_name = vod_bucket_qs[0]["bucket"]        endpoint = vod_bucket_qs[0]["endpoint"]        for vod in vodqs:            bucket = oss2.Bucket(auth, endpoint, bucket_name)            m3u8 = '{uid}/vod{channel}/{time}/{time}.m3u8'. \                format(uid=uid, channel=channel, time=vod['start_time'])            ts = '{uid}/vod{channel}/{time}/ts0.ts'. \                format(uid=uid, channel=channel, time=vod['start_time'])            url = bucket.sign_url('GET', m3u8, 3600, params={'x-oss-process': 'hls/sign'})            urllst = url.split('?')            url_start = urllib.parse.unquote(urllst[0])            url_end = urllst[1]            vod_play_url = '{url_start}?{url_end}'. \                format(url_start=url_start, url_end=url_end)            thumb = bucket.sign_url('GET', ts, 3600,                                    params={'x-oss-process': 'video/snapshot,t_10000,m_fast,w_300'})            vod_play_list.append(                {'name': vod['start_time'], 'sign_url': vod_play_url, 'thumb': thumb, 'sec': vod['sec']})        return response.json(0, vod_play_list)    def generate_token(self, request_dict, userID):        # UserIdToken        tko = TokenObject()        userID = request_dict.get('userID', None)        username = request_dict.get('username', None)        res = tko.generate(            data={'userID': userID, 'lang': 'cn', 'user': username, 'm_code': username})        # uidToken        # utko = UidTokenObject()        # res = utko.generate(data={'uid': '4UZSEDP93MJ3X7YB111A','channel': 1})        # from Object.ETkObject import ETkObject        # etkObj = ETkObject(etk='')        # res = etkObj.encrypt("4UZSEDP93MJ3X7YB111A")        return JsonResponse(status=200, data=res, safe=False)    def test_upload_s3(self, request_dict, response):        aws_s3_guonei = boto3.client(            's3',            aws_access_key_id=AWS_ACCESS_KEY_ID[0],            aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],            config=botocore.client.Config(signature_version='s3v4'),            region_name='cn-northwest-1'        )        download_link = 'ipctest'        response_url = aws_s3_guonei.generate_presigned_url(            ClientMethod='put_object',            Params={                'Bucket': 'pc-package',                'Key': download_link            },            ExpiresIn=3600        )        return response.json(0, {'datas': response_url, 'count': 1})    def testRekognition(self, request, request_dict):        # ip = CommonService.get_ip_address(request)        # ipInfo = CommonService.getIpIpInfo(ip,"CN")        # # print(type(ipInfo))        # # exit(ipInfo)        # addr = CommonService.getAddr(ip)        # dicts = {        #     'ipInfo':ipInfo,        #     'addr':addr,        # }        # return HttpResponse(json.dumps(dicts, ensure_ascii=False),        #                     content_type="application/json,charset=utf-8")        # client = boto3.client('s3', aws_access_key_id='AKIA2E67UIMD45Y3HL53',aws_secret_access_key='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',region_name='us-east-1')        # exit(request.FILES)        files = request.FILES.get('image')        labels = int(request_dict.get('labels', 5))        minConfidence = int(request_dict.get('minConfidence', 99))        if not files:            return HttpResponse('请上传图片!!!!')        client = boto3.client('rekognition', aws_access_key_id='AKIA2E67UIMD6JD6TN3J',                              aws_secret_access_key='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', region_name='us-east-1')        # image = open('E:/photo/a615fa40b8c476bab0f6eeb332e62a5a-1000.jpg', "rb")        response = client.detect_labels(Image={'Bytes': files.read()}, MaxLabels=labels, MinConfidence=minConfidence)        # for obj in response['Labels']:        #     exit(obj)        #     if obj['Name'] == 'Person':        #         jsonstr = json.dumps(obj)        return HttpResponse(json.dumps(response, ensure_ascii=False),                            content_type="application/json,charset=utf-8")    def ip(self, response):        ip = '67.220.90.13'        country_id = Device_Region().get_device_region(ip)        print(country_id)        return response.json(0)    def configType(self, response):        print(SERVER_TYPE)        return response.json(0)    def createData(self, request_dict, response):        uid = request_dict.get('uid', None)        # filter_date = datetime.datetime.now()-datetime.timedelta(days=4)        # qs = DeviceLogModel.objects.filter(add_time__lt=filter_date)        DeviceLogModel.objects.create(uid=uid)        return response.json(0)    def count_ts(self, request_dict, response):        year = request_dict.get('year', None)        month = request_dict.get('month', None)        if not year:            year = CommonService.timestamp_to_str(int(time.time()), '%Y')        if not month:            month = CommonService.timestamp_to_str(int(time.time()), '%m')        year = int(year)        month = int(month)        startTime = CommonService.str_to_timestamp('{year}-{month}'.format(year=year, month=month), '%Y-%m')        endTime = CommonService.str_to_timestamp('{year}-{month}'.format(year=year, month=month + 1), '%Y-%m') - 1        split_vod_hls_obj = SplitVodHlsObject()        qsTs = split_vod_hls_obj.get_vod_hls_data(time__gte=startTime, time__lte=endTime).values('fg')        if not qsTs.exists():            return HttpResponse('查无数据')        sumTs = 0  # 总ts个数        sumSec = 0  # 总秒数        for val in qsTs:            fg = int(val['fg'])            sumTs += fg & 0xf            for i in range(15):                shift = (i + 1) * 4                sumSec += (fg >> shift) & 0xf        size = 0        return HttpResponse(            "{year}年{month}月 </br>上传的TS总数:{sumTs} </br> 总秒数:{sumSec} </br> 总大小:{size}GB (1秒约等150KB计算)".format(year=year,                                                                                                              month=month,                                                                                                              sumTs=sumTs,                                                                                                              sumSec=sumSec,                                                                                                              size=size))    @staticmethod    def write_redis_list(response):        redis_obj = RedisObject()        for i in range(10):            redis_obj.rpush('serial_redis_list', i)        return response.json(0)    @staticmethod    def read_redis_list(response):        redis_obj = RedisObject()        serial_redis_list_len = redis_obj.llen('serial_redis_list')        if serial_redis_list_len > 0:            for i in range(serial_redis_list_len):                serial = redis_obj.lpop('serial_redis_list')                print(serial)        return response.json(0)    @staticmethod    def play_m3u8(request_dict, response):  # 根据sts播放m3u8 视频流        uid = request_dict.get('uid', None)        channel = request_dict.get('channel', None)        storeTime = request_dict.get('time', None)        now_time = int(time.time())        try:            split_vod_hls_obj = SplitVodHlsObject()            vh_qs = split_vod_hls_obj.get_vod_hls_data(uid=uid, channel=channel, start_time=storeTime,                                                       end_time__gte=now_time).values("sec", "fg", "bucket_id")            if not vh_qs.exists():                return response.json(173)            vod_bucket_qs = VodBucketModel.objects.filter(id=vh_qs[0]['bucket_id']).values('bucket', 'region', 'mold')            if not vod_bucket_qs.exists():                return response.json(173)            fg = int(vh_qs[0]['fg'])            bucket_region = vod_bucket_qs[0]['region']            bucket_name = vod_bucket_qs[0]['bucket']            mold = vod_bucket_qs[0]['mold']            session = Session(                aws_access_key_id=AWS_ACCESS_KEY_ID[mold],                aws_secret_access_key=AWS_SECRET_ACCESS_KEY[mold],                region_name=bucket_region            )            conn = session.client('s3')            playlist_entries = []            # ts_count = fg & 0xf            # fg 64位整型,低四位代表ts文件总数,然后进行位运算,一次移四位,每四位转为十进制即为当前ts文件的秒数            for i in range(15):                shift = (i + 1) * 4                duration = (fg >> shift) & 0xf                if duration > 0:                    tsFile = '{uid}/vod{channel}/{time}/ts{i}.ts'. \                        format(uid=uid, channel=channel, time=storeTime, i=i)                    response_url = conn.generate_presigned_url(                        'get_object',                        Params={                            'Bucket': bucket_name,                            'Key': tsFile                        },                        ExpiresIn=24 * 60 * 60                    )                    playlist_entries.append({                        'name': response_url,                        'duration': duration,                    })            playlist = PlaylistGenerator(playlist_entries).generate()            response = HttpResponse(playlist)            response['Content-Type'] = 'application/octet-stream'            response['Content-Disposition'] = 'attachment;filename="play.m3u8"'            return response        except Exception as e:            print(e)            return response.json(500, repr(e))    @classmethod    def getSerialNumberInfo(cls, request_dict, response):        logger = logging.getLogger('info')        serial_number = request_dict.get('serialNumber', None)        if not serial_number:            return response.json(444)        try:            uid_user_message = {                "uid": "",                "serialNumber": "",                "userID": "",                "username": "",                "primaryUserID": "",            }            data = {                "uid": "",                "serialNumber": serial_number[:9],                "status": "",                "add_time": "",                "uid_user_message": uid_user_message            }            # 获取序列哈状态            company_serial_qs = CompanySerialModel.objects.filter(serial_number=serial_number[:6]).values('status')            if not company_serial_qs.exists():                return response.json(173)            company_serial_qs = company_serial_qs.first()            if company_serial_qs['status'] == 0:                return response.json(0, {'contents': '序列号未分配'})            uid_company_serial_qs = UIDCompanySerialModel.objects.filter(                company_serial__serial_number=serial_number[:6]).values('uid__uid', 'uid__status',                                                                        'company_serial__serial_number', 'add_time')            if not uid_company_serial_qs.exists():                data['status'] = cls.serial_number_status(company_serial_qs['status'])                return response.json(0, data)            uid_company_serial = uid_company_serial_qs.first()            data['uid'] = uid_company_serial['uid__uid']            data['status'] = uid_company_serial['uid__status']            data['add_time'] = CommonService.timestamp_to_str(uid_company_serial['add_time'])            data['status'] = cls.serial_number_status(company_serial_qs['status'])            device_info_qs = Device_Info.objects.filter(UID=data['uid']).values(                'UID',                'serial_number',                'userID_id',                'primaryUserID',                'userID__username',                'data_joined').order_by('-data_joined')            if device_info_qs.exists():                # 判断主用户是否存在                primary_qs = device_info_qs.exclude(primaryUserID='')                if primary_qs.exists():                    uid_user_message['uid'] = primary_qs[0]['UID'],                    uid_user_message['serialNumber'] = primary_qs[0]['serial_number']                    uid_user_message['userID'] = primary_qs[0]['userID_id']                    uid_user_message['username'] = primary_qs[0]['userID__username']                    uid_user_message['primaryUserID'] = primary_qs[0]['primaryUserID']                else:                    device_info = device_info_qs.first()                    uid_user_message['uid'] = device_info['UID']                    uid_user_message['serialNumber'] = device_info['serial_number']                    uid_user_message['userID'] = device_info['userID_id']                    uid_user_message['username'] = device_info['userID__username']                    uid_user_message['primaryUserID'] = device_info['primaryUserID']            return response.json(0, data)        except Exception as e:            logger.error('序列号:{}, 查询异常:{}'.format(serial_number, e))            return response.json(500)    @staticmethod    def serial_number_status(status):        # 判断序号状态        if status == 1:            status = '已分配'        elif status == 2:            status = '绑定uid'        elif status == 3:            status = '已占用'        return status    @classmethod    def get_serial_details(cls, request_dict, response, request):        """        根据序列号查询各个服绑定状态        """        try:            serial_number = request_dict.get("serialNumber", None)            if not serial_number:                return response.json(0)            results_data = []            if not CONFIG_INFO == 'cn':                return response.json(0, results_data)            local_response = cls.getSerialNumberInfo(request_dict, response)            res = json.loads(local_response.content)            res['result']['server'] = 1            res['result']['serverName'] = '中国服'            res['result']['domainName'] = 'https://www.zositechc.cn'            results_data.append(res['result'])            res1 = requests.post("http://www.dvema.com/testApi/getSerialNumberInfo",                                 data={'serialNumber': serial_number}, timeout=15)            results1 = json.loads(res1.text)            results1['result']['server'] = 2            results1['result']['serverName'] = '美国服'            results1['result']['domainName'] = 'https://www.dvema.com'            results_data.append(results1['result'])            res2 = requests.post("https://api.zositeche.com/testApi/getSerialNumberInfo",                                 data={'serialNumber': serial_number}, timeout=15)            results2 = json.loads(res2.text)            results2['result']['server'] = 3            results2['result']['serverName'] = '欧洲服'            results2['result']['domainName'] = 'https://api.zositeche.com'            results_data.append(results2['result'])            is_ok = True            operation = ''            status_log = ''            for item in results_data:                if item['status'] == '绑定uid':                    is_ok = False                    operation = '{}序列号已绑定UID'.format(serial_number)                    LOGGER.info('序列号检测状态已绑定:{}'.format(serial_number))                    break                elif item['status'] == '已占用':                    status_log = '序列号检测状态已占用:{}'.format(serial_number)            if is_ok:                LOGGER.info(status_log)                LOGGER.info('序列号检测状态正常{}'.format(serial_number))                return response.json(0, results_data)            log = {                'ip': CommonService.get_ip_address(request),                'user_id': 1,                'status': 200,                'time': int(time.time()),                'operation': operation,                'url': 'testApi/get-serial-details',            }            LogModel.objects.create(**log)            return response.json(0, results_data)        except Exception as e:            LOGGER.info('扫码检测序列号异常详情,errLine:{}, errMsg:{}'                        .format(e.__traceback__.tb_lineno, repr(e)))            return response.json(500)    @staticmethod    def checkOrderExist(request_dict, response):        trade_no = request_dict.get('trade_no', None)        pay_time = request_dict.get('pay_time', None)        try:            order_qs = Order_Model.objects.filter(trade_no=trade_no)            is_exist = 0            if order_qs.exists():                is_exist = 1                order_qs.update(payTime=pay_time, addTime=pay_time)            return response.json(0, {'is_exist': is_exist})        except Exception as e:            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
 |