Sfoglia il codice sorgente

更新APP设备类型,支持多区域添加

linhaohong 1 anno fa
parent
commit
286c71f004
1 ha cambiato i file con 249 aggiunte e 72 eliminazioni
  1. 249 72
      AdminController/DeviceManagementController.py

+ 249 - 72
AdminController/DeviceManagementController.py

@@ -3,6 +3,7 @@
 import json
 import operator
 import time
+import requests
 
 import oss2
 from django.db import transaction
@@ -24,6 +25,7 @@ from Service.CommonService import CommonService
 from Service.EquipmentInfoService import EquipmentInfoService
 from Service.ModelService import ModelService
 from Service.VodHlsService import SplitVodHlsObject
+from Ansjer.config import SERVER_DOMAIN_TEST, SERVER_DOMAIN_CN, SERVER_DOMAIN_US, SERVER_DOMAIN_EUR
 
 
 class DeviceManagement(View):
@@ -89,6 +91,10 @@ class DeviceManagement(View):
                 return self.get_app_bundle(response)
             elif operation == 'resetAll':  # 重置设备主用户/云存/AI
                 return self.reset_all(request, request_dict, response)
+            elif operation == 'getAppNameList':  # 获取app版本包
+                return self.get_app_name_list(response)
+            elif operation == 'callAddAppDeviceType':  # 可选服添加app设备类型数据并上传图标
+                return self.call_add_app_device_type(request_dict, response, request)
             else:
                 return response.json(444, 'operation')
 
@@ -481,9 +487,8 @@ class DeviceManagement(View):
             print(e)
             return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
 
-    @staticmethod
-    def get_app_device_type_list(request_dict, response):
-        app_bundle_id = request_dict.get('app_bundle_id', None)
+    def get_app_device_type_list(self, request_dict, response):
+        app_bundle_name = request_dict.get('appBundleName', None)
         lang = request_dict.get('lang', None)
         model = request_dict.get('model', None)
         type = request_dict.get('type', None)
@@ -500,8 +505,10 @@ class DeviceManagement(View):
 
         try:
             app_bundle_qs = AppBundle.objects.all()
-            if app_bundle_id:
-                app_bundle_qs = app_bundle_qs.filter(app_bundle_id=app_bundle_id)
+            if app_bundle_name:
+                app_bundle_id = self.app_name_convert_id([app_bundle_name])
+                print(app_bundle_id)
+                app_bundle_qs = app_bundle_qs.filter(id__in=app_bundle_id)
             if lang:
                 app_bundle_qs = app_bundle_qs.filter(app_device_type__devicenamelanguage__lang=lang)
             app_bundle_qs = app_bundle_qs.annotate(
@@ -512,7 +519,8 @@ class DeviceManagement(View):
                                                                             'type', 'icon', 'app_bundle_id',
                                                                             'app_device_type__devicenamelanguage__id',
                                                                             'lang', 'name', 'sort',
-                                                                            'app_device_type__app_version_number_id').order_by(
+                                                                            'app_device_type__app_version_number_id',
+                                                                            'app_device_type__config').order_by(
                 'app_device_type__devicenamelanguage__sort')
             if not app_bundle_qs.exists():
                 return response.json(0)
@@ -554,6 +562,8 @@ class DeviceManagement(View):
         device_name_language_id = request_dict.get('app_device_type__devicenamelanguage__id', None)
         sort = request_dict.get('sort', None)
         version_number = request_dict.get('version_number', None)
+        config = request_dict.get('config', None)
+
         if not all([app_device_type_id, device_name_language_id, model, type, sort, version_number]):
             return response.json(444)
 
@@ -565,8 +575,17 @@ class DeviceManagement(View):
             with transaction.atomic():
                 if icon:
                     icon_path = 'https://ansjerfilemanager.s3.amazonaws.com/app/device_type_images/{}'.format(icon)
-                    AppDeviceType.objects.filter(id__in=list_app_device_type_id) \
-                        .update(model=model, type=type, icon=icon_path, app_version_number_id=version_number)
+                    if config:
+                        try:
+                            config = json.loads(config)
+                        except:
+                            return response.json(444, 'config必须是一个json数据')
+                        AppDeviceType.objects.filter(id__in=list_app_device_type_id) \
+                            .update(model=model, type=type, icon=icon_path, app_version_number_id=version_number,
+                                    config=config)
+                    else:
+                        AppDeviceType.objects.filter(id__in=list_app_device_type_id) \
+                            .update(model=model, type=type, icon=icon_path, app_version_number_id=version_number)
                     bucket_name = 'ansjerfilemanager'
                     file_key = 'app/device_type_images/{}'.format(icon)
                     s3 = AmazonS3Util(AWS_ACCESS_KEY_ID[1], AWS_SECRET_ACCESS_KEY[1], AWS_SES_ACCESS_REGION)
@@ -577,8 +596,17 @@ class DeviceManagement(View):
                         icon,
                         {'ContentType': icon.content_type, 'ACL': 'public-read'})
                 else:
-                    AppDeviceType.objects.filter(id__in=list_app_device_type_id) \
-                        .update(model=model, type=type, app_version_number_id=version_number)
+                    if config:
+                        try:
+                            config = json.loads(config)
+                        except:
+                            return response.json(444, 'config必须是一个json数据')
+                        AppDeviceType.objects.filter(id__in=list_app_device_type_id) \
+                            .update(model=model, type=type, app_version_number_id=version_number,
+                                    config=config)
+                    else:
+                        AppDeviceType.objects.filter(id__in=list_app_device_type_id) \
+                            .update(model=model, type=type, app_version_number_id=version_number)
                 DeviceNameLanguage.objects.filter(id__in=list_device_name_language_id).update(sort=sort)
             return response.json(0)
         except Exception as e:
@@ -598,6 +626,7 @@ class DeviceManagement(View):
         name = request_dict.get('name', None)
         sort = request_dict.get('sort', None)
         version_number = request_dict.get('version_number', None)
+        config = request_dict.get('config', None)
 
         if not all([app_device_type_id, model, type, device_name_language_id, lang, name, sort]):
             return response.json(444)
@@ -605,8 +634,17 @@ class DeviceManagement(View):
             with transaction.atomic():
                 if icon:
                     icon_path = 'https://ansjerfilemanager.s3.amazonaws.com/app/device_type_images/{}'.format(icon)
-                    AppDeviceType.objects.filter(id=app_device_type_id) \
-                        .update(model=model, type=type, icon=icon_path, app_version_number_id=version_number)
+                    if config:
+                        try:
+                            config = json.loads(config)
+                        except:
+                            return response.json(444, 'config必须是一个json数据')
+                        AppDeviceType.objects.filter(id=app_device_type_id) \
+                            .update(model=model, type=type, icon=icon_path, app_version_number_id=version_number,
+                                    config=config)
+                    else:
+                        AppDeviceType.objects.filter(id=app_device_type_id) \
+                            .update(model=model, type=type, icon=icon_path, app_version_number_id=version_number)
                     bucket_name = 'ansjerfilemanager'
                     file_key = 'app/device_type_images/{}'.format(icon)
                     s3 = AmazonS3Util(AWS_ACCESS_KEY_ID[1], AWS_SECRET_ACCESS_KEY[1], AWS_SES_ACCESS_REGION)
@@ -617,8 +655,17 @@ class DeviceManagement(View):
                         icon,
                         {'ContentType': icon.content_type, 'ACL': 'public-read'})
                 else:
-                    AppDeviceType.objects.filter(id=app_device_type_id) \
-                        .update(model=model, type=type, app_version_number_id=version_number)
+                    if config:
+                        try:
+                            config = json.loads(config)
+                        except:
+                            return response.json(444, 'config必须是一个json数据')
+                        AppDeviceType.objects.filter(id=app_device_type_id) \
+                            .update(model=model, type=type, app_version_number_id=version_number,
+                                    config=config)
+                    else:
+                        AppDeviceType.objects.filter(id=app_device_type_id) \
+                            .update(model=model, type=type, app_version_number_id=version_number)
                 DeviceNameLanguage.objects.filter(id=device_name_language_id).update(lang=lang, name=name, sort=sort)
             return response.json(0)
         except Exception as e:
@@ -680,84 +727,103 @@ class DeviceManagement(View):
             print(e)
             return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
 
-    @staticmethod
-    def add_app_device_type(request_dict, response, request):
+    def add_app_device_type(self, request_dict, response, request):
         """
-        添加app设备类型数据并上传图标
+        添加设备类型
         @param request_dict: 请求参数
-        @request_dict lang: 语言
-        @request_dict app_bundle_id: app包id
-        @request_dict version_number: app版本号
+        @request_dict appBundleName: app包名
+        @request_dict versionNumber: app版本号
         @request_dict model: 设备类型
         @request_dict type: 设备型号
         @request_dict name: 设备名称
-        @request_dict sort: 升序排序
-        @request_dict file: 文件
+        @request_dict sort: 排序
+        @request.FILES iconFile: 上传图标
         @param response: 响应对象
-        @return:
         """
-        # 添加APP设备类型
-        app_bundle_id = request_dict.get(
-            'app_bundle_id', '')[
-                        1:-1].split(',')  # '[1,2]' -> ['1','2']
+        # app包名称
+        app_bundle_name = request_dict.get('appBundleName', None)
         # 版本号
-        version_number = request_dict.get('version_number', None)
+        version_number = request_dict.get('versionNumber', None)
         # app_device_type表数据
         model = request_dict.get('model', None)
         type = request_dict.get('type', None)
         # device_name_language表数据
         name = request_dict.get('name', None)
         sort = request_dict.get('sort', None)
+        config = request_dict.get('config', None)
         # 上传图标
         file = request.FILES.get('iconFile', None)
-        if not all([model, type, name, sort, version_number, file]):
-            return response.json(444, 'model, type, file, name, sort, version_number')
-        fileName = file.name
-        type = int(type)
-        data_name = eval(name)
+        if config:
+            config = json.loads(config)
         try:
+            type = int(type)
+            data_name = eval(name)
+            app_bundle_name_list = app_bundle_name.split(',')
+            app_bundle_id = self.app_name_convert_id(app_bundle_name_list)
+
+            existing_records = []
+            success_records = []
+            need_upload = False  # 标记是否需要上传文件
+
+            # 先检查所有数据是否存在
             with transaction.atomic():
-                for k, v in data_name.items():
-                    app_bundle_qs = AppBundle.objects.filter(id__in=app_bundle_id,
-                                                             app_device_type__devicenamelanguage__lang=k,
-                                                             app_device_type__app_version_number_id=version_number,
-                                                             app_device_type__type=type,
-                                                             app_device_type__model=model)
-                    #  数据是否重复
-                    if app_bundle_qs.exists():
-                        return response.json(174)
-                    # 是否存在相同的url
-                    response_url = 'https://ansjerfilemanager.s3.amazonaws.com/app/device_type_images/' + format(
-                        fileName)
-                    app_bundle_qs = AppDeviceType.objects.filter(appbundle__id__in=app_bundle_id, type=type,
-                                                                 model=model, icon=response_url)
-                    if not app_bundle_qs.exists():
-                        # 上传设备图标至存储桶
-                        bucket_name = 'ansjerfilemanager'
-                        file_key = 'app/device_type_images/{}'.format(fileName)
-                        s3 = AmazonS3Util(AWS_ACCESS_KEY_ID[1], AWS_SECRET_ACCESS_KEY[1], AWS_SES_ACCESS_REGION)
-                        # 地址:https://ansjerfilemanager.s3.amazonaws.com/app/device_type_images/camera_c190.png
-                        s3.upload_file_obj(
-                            bucket_name,
-                            file_key,
-                            file,
-                            {'ContentType': file.content_type, 'ACL': 'public-read'})
-                #  创建
-                for k, v in data_name.items():
+                for app_id in app_bundle_id:
+                    for k, v in data_name.items():
+                        app_bundle_qs = AppBundle.objects.filter(id=app_id,
+                                                                 app_device_type__devicenamelanguage__lang=k,
+                                                                 app_device_type__app_version_number_id=version_number,
+                                                                 app_device_type__type=type,
+                                                                 app_device_type__model=model)
+                        if app_bundle_qs.exists():
+                            app_bundle = app_bundle_qs.values("app_bundle_id").first()
+                            existing_record = {"app_bundle_id": app_bundle["app_bundle_id"], "type": type,
+                                               "version_number": version_number, "lang": k, "model": model}
+                            existing_records.append(existing_record)
+                        else:
+                            need_upload = True  # 发现至少一条记录不存在,需要上传文件
+
+            # 如果需要上传文件
+            if need_upload:
+                with transaction.atomic():
+                    fileName = file.name
+                    now_time = int(time.time())
+                    response_url = f'https://ansjerfilemanager.s3.amazonaws.com/app/device_type_images/{now_time}_{fileName}'
+                    bucket_name = 'ansjerfilemanager'
+                    file_key = f'app/device_type_images/{now_time}_{fileName}'
+                    s3 = AmazonS3Util(AWS_ACCESS_KEY_ID[1], AWS_SECRET_ACCESS_KEY[1], AWS_SES_ACCESS_REGION)
+                    s3.upload_file_obj(bucket_name, file_key, file,
+                                       {'ContentType': file.content_type, 'ACL': 'public-read'})
                     for app_id in app_bundle_id:
-                        app_bundle_qs = AppBundle.objects.filter(id=app_id).values('id')
-                        app_device_type_qs = AppDeviceType.objects.create(model=model, type=type, icon=response_url,
-                                                                          app_version_number_id=version_number)
-                        DeviceNameLanguage.objects.create(lang=k, name=v, sort=sort,
-                                                          app_device_type_id=app_device_type_qs.id)
-                        #  关联app包
-                        app_device_type_qs.appbundle_set.add(app_bundle_qs[0]['id'])
-                return response.json(0)
+                        for k, v in data_name.items():
+                            record_key = {"app_bundle_id": app_id, "type": type, "version_number": version_number,
+                                          "lang": k, "model": model}
+                            # 检查这个组合的记录是否存在
+                            if not any(rec == record_key for rec in existing_records):
+                                app_bundle = AppBundle.objects.filter(id=app_id).values('id', 'app_bundle_id').first()
+                                app_device_type_qs = AppDeviceType.objects.create(model=model, type=type,
+                                                                                  icon=response_url,
+                                                                                  app_version_number_id=version_number,
+                                                                                  config=config)
+                                DeviceNameLanguage.objects.create(lang=k, name=v, sort=sort,
+                                                                  app_device_type_id=app_device_type_qs.id)
+                                app_device_type_qs.appbundle_set.add(app_bundle["id"])
+                                success_records.append(
+                                    {"app_bundle_id": app_bundle["app_bundle_id"], "type": type,
+                                     "version_number": version_number,
+                                     "lang": k, "model": model}
+                                )
+
+            response_data = {
+                'success_records': success_records,
+                'existing_records': existing_records
+            }
+            return response.json(0, response_data)
         except Exception as e:
             print(e)
             return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
 
-    def get_device_icon(self, request_dict, response):
+    @staticmethod
+    def get_device_icon(request_dict, response):
         """
         查询设备信息图标
         @param request_dict: 请求参数
@@ -822,11 +888,12 @@ class DeviceManagement(View):
             print(e)
             return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
 
-    def get_uid_push(self, request_dict, response):
+    @staticmethod
+    def get_uid_push(request_dict, response):
         """
-        查询设备信息图标
+        查询UID对应的推送信息
         @param request_dict: 请求参数
-        @request_dict id: id
+        @request_dict UID: UID
         @param response: 响应对象
         @return:
         """
@@ -851,3 +918,113 @@ class DeviceManagement(View):
         except Exception as e:
             print(e)
             return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
+
+    @staticmethod
+    def get_app_name_list(response):
+        """
+        查询APP包名称列表
+        @param response: 响应对象
+        @return:
+        """
+        try:
+            app_bundle_qs = AppBundle.objects.all().values_list('app_bundle_id')
+            app_info = App_Info.objects.filter(appBundleId__in=app_bundle_qs).values('appName')
+            app_name_list = []
+            for app_name in app_info:
+                app_name_list.append(app_name['appName'])
+            app_name_list = list(set(app_name_list))
+            return response.json(0, app_name_list)
+        except Exception as e:
+            print(e)
+            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
+
+    @staticmethod
+    def app_name_convert_id(app_name_list):
+        """
+        app_name_list 转 app_id_list
+        @param app_name_list: app名字列表
+        @return app_id_list: app id列表
+        """
+        try:
+            app_bundle_id_list = App_Info.objects.filter(appName__in=app_name_list).values_list('appBundleId',
+                                                                                                flat=True)
+            app_id_list = AppBundle.objects.filter(app_bundle_id__in=app_bundle_id_list).values_list('id', flat=True)
+            return list(set(app_id_list))
+        except Exception as e:
+            print(e)
+            return []
+
+    @staticmethod
+    def call_add_app_device_type(request_dict, response, request):
+        """
+        添加设备类型
+        @param request_dict: 请求参数
+        @request_dict appBundleName: app包名
+        @request_dict versionNumber: app版本号
+        @request_dict model: 设备类型
+        @request_dict type: 设备型号
+        @request_dict name: 设备名字
+        @request_dict sort: 排序
+        @request_dict region: 地区
+        @request.FILES iconFile: 上传图标
+        @param response: 响应对象
+        """
+        # app包名称
+        app_bundle_name = request_dict.get('appBundleName', None)
+        # 版本号
+        version_number = request_dict.get('versionNumber', None)
+        # app_device_type表数据
+        model = request_dict.get('model', None)
+        type = request_dict.get('type', None)
+        # device_name_language表数据
+        name = request_dict.get('name', None)
+        sort = request_dict.get('sort', None)
+        config = request_dict.get('config', None)
+        # 上传图标
+        files = request.FILES.get('iconFile', None)
+        # 需要添加到哪一个服
+        region = request_dict.get("region", None)  # 获取需要同步的区域
+
+        # 检查必需参数
+        if not all([model, type, name, sort, version_number, files, app_bundle_name, region]):
+            return response.json(444, 'Missing required parameters')
+
+        regions = region.split(",")  # 将同步区域拆分为列表
+        return_value_list = []
+        for region in regions:
+            if region == 'test':
+                url = SERVER_DOMAIN_TEST
+            elif region == 'cn':
+                url = SERVER_DOMAIN_CN
+            elif region == 'us':
+                url = SERVER_DOMAIN_US
+            elif region == 'eu':
+                url = SERVER_DOMAIN_EUR
+            else:
+                return response.json(444, 'Invalid region')
+
+            try:
+                form_data = {
+                    'name': name,
+                    'type': type,
+                    'sort': sort,
+                    'model': model,
+                    'versionNumber': version_number,
+                    'appBundleName': app_bundle_name,
+                }
+                if config:
+                    try:
+                        config = json.loads(config)
+                    except:
+                        return response.json(444, 'config必须是一个json数据')
+                    form_data["config"] = json.dumps(config)
+                # 发送 POST 请求调用 add_app_device_type 方法
+                response_value = requests.post(url + "/deviceManagement/addAppDeviceType",
+                                               data=form_data,
+                                               files={'iconFile': files})
+                return_value = {region: response_value.json()["data"]}
+                return_value_list.append(return_value)
+            except Exception as e:
+                return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
+
+        return response.json(0, {"list": return_value_list})