| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037 | #!/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)        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)
 |