Browse Source

Merge branch 'dev'

# Conflicts:
#	Ansjer/urls.py
#	Controller/AdminManage.py
#	Controller/CloudStorage.py
#	Controller/CloudTransfer.py
#	Controller/EquipmentManager.py
#	Controller/EquipmentManagerV2.py
#	Controller/EquipmentManagerV3.py
#	Controller/EquipmentOTA.py
#	Controller/OTAEquipment.py
#	Controller/UidSetController.py
#	Model/models.py
#	Service/ModelService.py
lang 4 years ago
parent
commit
a4a7c31bc3
76 changed files with 7401 additions and 694 deletions
  1. 1 0
      .gitignore
  2. 16 0
      Ansjer/asgi.py
  3. 185 3
      Ansjer/config.py
  4. 11 8
      Ansjer/config_local.py
  5. 17 6
      Ansjer/config_test.py
  6. 68 0
      Ansjer/file/apns_pem/ZhouShi-dev.pem
  7. 1 0
      Ansjer/formal_settings.py
  8. 27 0
      Ansjer/formal_statistics_push_month_task.py
  9. 46 0
      Ansjer/formal_zositech_help_weekly_task.py
  10. 46 0
      Ansjer/generacode.py
  11. 29 7
      Ansjer/local_settings.py
  12. 27 0
      Ansjer/push_element_into_redis.py
  13. 28 1
      Ansjer/test_settings.py
  14. 27 0
      Ansjer/test_statistics_push_month_task.py
  15. 46 0
      Ansjer/test_zositech_help_weekly_task.py
  16. 60 4
      Ansjer/urls.py
  17. 16 0
      Ansjer/wsgi.py
  18. 2 0
      Controller/AccessLog.py
  19. 12 12
      Controller/AdminManage.py
  20. 19 3
      Controller/AppSetController.py
  21. 41 10
      Controller/CloudStorage.py
  22. 16 1
      Controller/CloudTransfer.py
  23. 180 0
      Controller/Cloudsum.py
  24. 226 0
      Controller/CompanyController.py
  25. 371 372
      Controller/DateController.py
  26. 1 0
      Controller/DetectController.py
  27. 89 0
      Controller/DeviceConfirmRegion.py
  28. 13 0
      Controller/EquipmentInfo.py
  29. 94 18
      Controller/EquipmentManager.py
  30. 175 9
      Controller/EquipmentManagerV2.py
  31. 311 44
      Controller/EquipmentManagerV3.py
  32. 21 13
      Controller/EquipmentOTA.py
  33. 12 1
      Controller/EquipmentStatus.py
  34. 74 5
      Controller/FAQController.py
  35. 35 0
      Controller/FeedBack.py
  36. 541 0
      Controller/FileController.py
  37. 402 0
      Controller/HistoryUIDController.py
  38. 111 0
      Controller/IotCoreController.py
  39. 97 0
      Controller/LanguageController.py
  40. 99 0
      Controller/LogController.py
  41. 80 9
      Controller/OTAEquipment.py
  42. 77 0
      Controller/OperatingLogs.py
  43. 104 0
      Controller/OrderTaskController.py
  44. 64 0
      Controller/ProcessInfo.py
  45. 295 0
      Controller/RegionController.py
  46. 46 0
      Controller/RegionCountryController.py
  47. 107 0
      Controller/SalesController.py
  48. 390 0
      Controller/SerialNumberController.py
  49. 11 11
      Controller/StatisticsController.py
  50. 2 2
      Controller/SysManage.py
  51. 0 1
      Controller/SysMsg.py
  52. 71 5
      Controller/TestApi.py
  53. 63 0
      Controller/TestController.py
  54. 479 0
      Controller/UIDController.py
  55. 296 0
      Controller/UIDManageUserController.py
  56. 24 1
      Controller/UidSetController.py
  57. 130 54
      Controller/UserController.py
  58. 270 0
      Controller/VPGController.py
  59. 121 0
      Controller/VerifyCodeController.py
  60. 13 8
      Controller/VodBucket.py
  61. 0 0
      Model/__init__.py
  62. 31 29
      Model/models.py
  63. 3 0
      Model/tests.py
  64. 3 0
      Model/views.py
  65. 157 0
      Object/IOTCore/IotObject.py
  66. 210 0
      Object/LogsObject.py
  67. 7 0
      Object/RedisObject.py
  68. 24 4
      Object/TokenObject.py
  69. 113 0
      Object/uidManageResponseObject.py
  70. 55 0
      Service/AlgorithmService.py
  71. 141 0
      Service/LogMiddleware.py
  72. 40 6
      Service/ModelService.py
  73. 95 0
      Service/OperatingLogs.py
  74. 15 11
      Service/TemplateService.py
  75. 2 0
      Service/middleware.py
  76. 269 36
      requirements.txt

+ 1 - 0
.gitignore

@@ -11,6 +11,7 @@
 */__pycache__
 /Ansjer/test/__pycache__
 /Ansjer/test/__init__.py
+/static/log/error.log
 /sdk_install
 /DB/mydata4vipday2.ipdb
 /venv

+ 16 - 0
Ansjer/asgi.py

@@ -0,0 +1,16 @@
+"""
+ASGI config for AnsjerUIDManage project.
+
+It exposes the ASGI callable as a module-level variable named ``application``.
+
+For more information on this file, see
+https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
+"""
+
+import os
+
+from django.core.asgi import get_asgi_application
+
+os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AnsjerUIDManage.settings')
+
+application = get_asgi_application()

+ 185 - 3
Ansjer/config.py

@@ -1,5 +1,5 @@
-#!/usr/bin/env python3  
-# -*- coding: utf-8 -*-  
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
 """
 @Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
 @AUTHOR: ASJRD018
@@ -33,6 +33,7 @@ AWS_SES_ACCESS_ID = 'AKIAJKPU23EU5QWHFPKQ'
 AWS_SES_ACCESS_SECRET = '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'
 AWS_SES_ACCESS_REGION = 'us-east-1'
 AWS_SES_ACCESS_REGION_WEST = 'us-west-1'
+
 AWS_BUCKET = 'ansjertest'
 # 设定离线时间为5分钟
 OFF_LINE_TIME_DELTA = 5
@@ -68,6 +69,11 @@ OSS_STS_ACCESS_KEY = 'LTAIyMkGfEdogyL9'
 OSS_STS_ACCESS_SECRET = '71uIjpsqVOmF7DAITRyRuc259jHOjO'
 OSS_ROLE_ARN = 'acs:ram::1901342792446414:role/stsoss'
 
+# aws api key
+AWS_ACCESS_KEY_ID = ['AKIA2MMWBR4DSFG67DTG','AKIA2E67UIMD45Y3HL53']  #0国内, 1国外
+AWS_SECRET_ACCESS_KEY = ['aI9gxcAKPmiGgPy9axrtFKzjYGbvpuytEX4xWweL','ckYLg4Lo9ZXJIcJEAKkzf2rWvs8Xth1FCjqiAqUw']
+AWS_ARN = ['arn:aws-cn:s3','arn:aws:s3']
+
 # 不同环境配置
 if SERVER_TYPE == 'Ansjer.local_settings':
     from Ansjer.config_local import *
@@ -159,4 +165,180 @@ APP_FREQUENT = {
     5: '一个月',
     6: '一个月以上',
 
-}
+}
+
+# Iot Core国外
+AWS_IOT_SES_ACCESS_FOREIGN_ID = 'AKIA2E67UIMD62VUBV5I'
+AWS_IOT_SES_ACCESS_FOREIGN_SECRET = '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'
+AWS_IOT_SES_ACCESS_FOREIGN_REGION_AMERICA = 'us-east-1'
+AWS_IOT_SES_ACCESS_FOREIGN_REGION_ASIA = 'ap-southeast-1'
+AWS_IOT_SES_ACCESS_FOREIGN_REGION_EUROPE = 'eu-west-1'
+
+# Iot Core国内
+AWS_IOT_SES_ACCESS_CHINA_ID = 'AKIA2MMWBR4DUUYPCFNJ'
+AWS_IOT_SES_ACCESS_CHINA_SECRET = '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'
+AWS_IOT_SES_ACCESS_CHINA_REGION = 'cn-northwest-1'
+
+IOT_HOST = {
+    1: 'a250bbr0p9u7as-ats.iot.cn-northwest-1.amazonaws.com.cn',
+    2: 'a2rqy12o004ad8-ats.iot.ap-southeast-1.amazonaws.com',
+    3: 'a2rqy12o004ad8-ats.iot.eu-west-1.amazonaws.com',
+    4: 'a2rqy12o004ad8-ats.iot.us-east-1.amazonaws.com'
+}
+ONLINE_DEVICE = 1000000
+
+SALES = {
+    2020: [
+        {
+            'name': 'United States',
+            'value': [3768901, 23.337, '美国']
+        },
+        {
+            'name': 'Japan',
+            'value': [1886988, 9.027, '日本']
+        },
+        {
+            'name': 'Russia',
+            'value': [1940038, 7.923, '俄国']
+        },
+        {
+            'name': 'Germany',
+            'value': [1319651, 6.253, '德国']
+        },
+        {
+            'name': 'France',
+            'value': [1291157, 5.825, '法国']
+        },
+        {
+            'name': 'United Kingdom',
+            'value': [1041917, 4.567, '英国']
+        },
+        {
+            'name': 'Italy',
+            'value': [859811, 3.875, '意大利']
+        }
+    ],
+    2019: [
+        {
+            'name': 'United States',
+            'value': [2768900, 37.374, '美国']
+        },
+        {
+            'name': 'Japan',
+            'value': [1086988, 14.672, '日本']
+        },
+        {
+            'name': 'Russia',
+            'value': [940038, 12.689, '俄国']
+        },
+        {
+            'name': 'Germany',
+            'value': [919651, 12.413, '德国']
+        },
+        {
+            'name': 'France',
+            'value': [691157, 9.329, '法国']
+        },
+        {
+            'name': 'United Kingdom',
+            'value': [541917, 7.315, '英国']
+        },
+        {
+            'name': 'Italy',
+            'value': [459811, 6.206, '意大利']
+        }
+    ],
+    2018: [
+        {
+            'name': 'United States',
+            'value': [2068912, 32.329, '美国']
+        },
+        {
+            'name': 'Japan',
+            'value': [1007988, 15.751, '日本']
+        },
+        {
+            'name': 'Germany',
+            'value': [909653, 14.214, '德国']
+        },
+        {
+            'name': 'Russia',
+            'value': [900038, 14.064, '俄国']
+        },
+
+        {
+            'name': 'France',
+            'value': [601158, 9.394, '法国']
+        },
+        {
+            'name': 'United Kingdom',
+            'value': [501920, 7.843, '英国']
+        },
+        {
+            'name': 'Italy',
+            'value': [409813, 6.404, '意大利']
+        }
+    ],
+    2017: [
+        {
+            'name': 'United States',
+            'value': [1668900, 30.914, '美国']
+        },
+        {
+            'name': 'Japan',
+            'value': [906988, 16.800, '日本']
+        },
+        {
+            'name': 'Germany',
+            'value': [809651, 14.998, '德国']
+        },
+        {
+            'name': 'Russia',
+            'value': [800038, 14.820, '俄国']
+        },
+        {
+            'name': 'France',
+            'value': [501157, 9.283, '法国']
+        },
+        {
+            'name': 'United Kingdom',
+            'value': [401920, 7.445, '英国']
+        },
+        {
+            'name': 'Italy',
+            'value': [309822, 5.739, '意大利']
+        }
+    ],
+    2016: [
+        {
+            'name': 'United States',
+            'value': [1468900, 31.943, '美国']
+        },
+        {
+            'name': 'Japan',
+            'value': [806988, 17.549, '日本']
+        },
+        {
+            'name': 'Germany',
+            'value': [709651, 15.432, '德国']
+        },
+        {
+            'name': 'Russia',
+            'value': [700038, 15.223, '俄国']
+        },
+
+        {
+            'name': 'France',
+            'value': [401157, 8.724, '法国']
+        },
+        {
+            'name': 'United Kingdom',
+            'value': [301917, 6.566, '英国']
+        },
+        {
+            'name': 'Italy',
+            'value': [209811, 4.562, '意大利']
+        }
+    ]
+
+}

+ 11 - 8
Ansjer/config_local.py

@@ -15,14 +15,14 @@
 OAUTH_ACCESS_TOKEN_SECRET = 'local_a+jbgnw%@1%zy^=@dn62%'
 OAUTH_REFRESH_TOKEN_SECRET = 'local_r+jbgnw%@1%zy^=@dn62%'
 
-NGINX_RTMP_STAT = 'http://192.168.136.99:8077/stat'
-SERVER_DOMAIN = 'http://192.168.136.99:8077/'
-SERVER_DOMAIN_SSL = 'http://192.168.136.99:8077/'
-SERVER_HOST = '192.168.136.99'
-DOMAIN_HOST = '192.168.136.99'
+NGINX_RTMP_STAT = 'http://127.0.0.1:8077/stat'
+SERVER_DOMAIN = 'http://127.0.0.1:8077/'
+SERVER_DOMAIN_SSL = 'http://127.0.0.1:8077/'
+SERVER_HOST = '127.0.0.1'
+DOMAIN_HOST = '127.0.0.1'
 # SERVER_HOST = '127.0.0.1'
-# DOMAIN_HOST = '192.168.136.99'
-RTMP_PUSH_URL = 'rtmp://192.168.136.99:1935/hls'
+# DOMAIN_HOST = '127.0.0.1'
+RTMP_PUSH_URL = 'rtmp://127.0.0.1:1935/hls'
 PAYPAL_CRD = {
     "mode": "sandbox",  # sandbox or live
     "client_id": "AeuhR7FHisO-lOd2OwtzyDu7PSLMmDZoDLgmzuEQ12WCtTu_8Z1AzcD4gG5SnymnuvJs-n5KBB8H9Z_G",
@@ -52,7 +52,10 @@ APNS_CONFIG = {
     },
     'com.ansjer.accloud': {
         'pem_path': 'Ansjer/file/apns_pem/accloud-dev.pem',
-    }
+    },
+    'com.ansjer.customizede': {
+        'pem_path': 'Ansjer/file/apns_pem/ZhouShi-dev.pem',
+    },
 }
 APNS_MODE = 'dev'
 TUTK_PUSH_DOMAIN = 'http://push.iotcplatform.com/tpns'

+ 17 - 6
Ansjer/config_test.py

@@ -23,16 +23,21 @@ OAUTH_REFRESH_TOKEN_SECRET = 'test_r+jbgnw%@1%zy^=@dn62%'
 DOMAIN_HOST = 'test.dvema.com'
 SERVER_HOST = 'localhost'
 PAYPAL_CRD = {
-    # "mode": "live",  # sandbox or live
-    # "client_id": "AdSRd6WBn-qLl9OiQHQuNYTDFSx0ZX0RUttqa58au8bPzoGYQUrt8bc6591RmH8_pEAIPijdvVYSVXyI",
-    # "client_secret": "ENT-J08N3Fw0B0uAokg4RukljAwO9hFHPf8whE6-Dwd8oBWJO8AWMgpdTKpfB1pOy89t4bsFEzMWDowm"
+    "mode": "live",  # sandbox or live
+    "client_id": "AdSRd6WBn-qLl9OiQHQuNYTDFSx0ZX0RUttqa58au8bPzoGYQUrt8bc6591RmH8_pEAIPijdvVYSVXyI",
+    "client_secret": "ENT-J08N3Fw0B0uAokg4RukljAwO9hFHPf8whE6-Dwd8oBWJO8AWMgpdTKpfB1pOy89t4bsFEzMWDowm"
     # "mode": "sandbox",  # sandbox or live
     # "client_id": "AeuhR7FHisO-lOd2OwtzyDu7PSLMmDZoDLgmzuEQ12WCtTu_8Z1AzcD4gG5SnymnuvJs-n5KBB8H9Z_G",
     # "client_secret": "EGkMCB3RWTcUGJGDYahJ9mCO0AQzEn2AvFfx1GAFjfyyn7-8a0NObcZks89QorlFpvNWTsDXVa2INRNM"
-    "mode": "sandbox",  # sandbox or live
-    "client_id": "AVLoQVq3xHZ6FrF4mxHwlCPgVBAw4Fw5RtMkuxmYd23SkUTIY643n2g3KdK-Al8wV05I28lza5uoQbAA",
-    "client_secret": "EO8kRc8yioDk0i2Qq-QMcVFfwkmyMJorTvBSLDTnxDJJ_wb9VoM_0jkUY9iEng2Flp1ze8wQOGpH5nB2"
+    # "mode": "sandbox",  # sandbox or live
+    # "client_id": "AVLoQVq3xHZ6FrF4mxHwlCPgVBAw4Fw5RtMkuxmYd23SkUTIY643n2g3KdK-Al8wV05I28lza5uoQbAA",
+    # "client_secret": "EO8kRc8yioDk0i2Qq-QMcVFfwkmyMJorTvBSLDTnxDJJ_wb9VoM_0jkUY9iEng2Flp1ze8wQOGpH5nB2"
 }
+# PAYPAL_CRD = {
+#     "mode": "sandbox",  # sandbox or live
+#     "client_id": "ATXTpWs8sajNYeU46jNs1yzpy4H_o3RRrGVIJ8Tscc312BjMx12cpRgCucfWX07a4G6GbK8hzElB04Pd",
+#     "client_secret": "EHcnfrpL1o1ev9WnlQ-C1uymeRKDoJ6li6Y0d6iHoRGj4u8Sx5lSEEH774XphP4LQZ0DrDUdvxbux0T2"
+# }
 DETECT_PUSH_DOMAIN = 'http://test.push.dvema.com/'
 # 数据库dyanamo品牌日志数据库
 USER_BRAND = 'test_user_brand'
@@ -56,6 +61,12 @@ APNS_CONFIG = {
     },
     'com.ansjer.accloud': {
         'pem_path': 'Ansjer/file/apns_pem/accloud-dev.pem',
+    },
+    'com.ansjer.customizede': {
+        'pem_path': 'Ansjer/file/apns_pem/ZhouShi-dev.pem',
+    },
+    'com.ansjer.customizedc': {
+        'pem_path': 'Ansjer/file/apns_pem/customizedc.pem',
     }
 }
 APNS_MODE = 'dev'

+ 68 - 0
Ansjer/file/apns_pem/ZhouShi-dev.pem

@@ -0,0 +1,68 @@
+Bag Attributes
+    friendlyName: Apple Push Services: com.ansjer.customizede
+    localKeyID: F9 76 DF A5 B7 2C 38 04 6E CD FA BF F5 74 9F AD 83 1A E9 8E 
+subject=/UID=com.ansjer.customizede/CN=Apple Push Services: com.ansjer.customizede/OU=772N5HXAR2/O=ZOSI Technology Co. , Ltd/C=CN
+issuer=/C=US/O=Apple Inc./OU=Apple Worldwide Developer Relations/CN=Apple Worldwide Developer Relations Certification Authority
+-----BEGIN CERTIFICATE-----
+MIIGOTCCBSGgAwIBAgIIPI2iB4mqqDEwDQYJKoZIhvcNAQELBQAwgZYxCzAJBgNV
+BAYTAlVTMRMwEQYDVQQKDApBcHBsZSBJbmMuMSwwKgYDVQQLDCNBcHBsZSBXb3Js
+ZHdpZGUgRGV2ZWxvcGVyIFJlbGF0aW9uczFEMEIGA1UEAww7QXBwbGUgV29ybGR3
+aWRlIERldmVsb3BlciBSZWxhdGlvbnMgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkw
+HhcNMjAxMjE5MDY1NDE0WhcNMjIwMTE4MDY1NDE0WjCBpDEmMCQGCgmSJomT8ixk
+AQEMFmNvbS5hbnNqZXIuY3VzdG9taXplZGUxNDAyBgNVBAMMK0FwcGxlIFB1c2gg
+U2VydmljZXM6IGNvbS5hbnNqZXIuY3VzdG9taXplZGUxEzARBgNVBAsMCjc3Mk41
+SFhBUjIxIjAgBgNVBAoMGVpPU0kgVGVjaG5vbG9neSBDby4gLCBMdGQxCzAJBgNV
+BAYTAkNOMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuIhNiP1jkZsf
+HD8nyx6G5DjF4RONEZGMUYph5GFpQSlnY4c1IeHFcNa7qKnvrx3t2ZnIIKaAaMWc
+w+9XiK3KNDpo/A4CEt/Es0Dh5gDze8bG8DK1qORI5XMDUC3r2wRdZ1jSSDcXJ0Fu
+byIkxrOaCe4J0hlJkPbzB/2z9AXMhSh4UhzcHUNMqfWbpzrUCG1nv0woA2MaWrw9
+OiwLy4HckGHXDJEV1eIPsN3v+W5RoP2VJp69gx7M2LH5KcFTvpzhlcXl4elSETgU
+07dqHnoHkSaVVNB8dmPmpHn11Sk8S+fm1qMtNy9PB5gmMaCQt31+YThFp1rl8Zs4
+ERVmbPWtVQIDAQABo4ICeTCCAnUwDAYDVR0TAQH/BAIwADAfBgNVHSMEGDAWgBSI
+JxcJqbYYYIvs67r2R1nFUlSjtzCCARwGA1UdIASCARMwggEPMIIBCwYJKoZIhvdj
+ZAUBMIH9MIHDBggrBgEFBQcCAjCBtgyBs1JlbGlhbmNlIG9uIHRoaXMgY2VydGlm
+aWNhdGUgYnkgYW55IHBhcnR5IGFzc3VtZXMgYWNjZXB0YW5jZSBvZiB0aGUgdGhl
+biBhcHBsaWNhYmxlIHN0YW5kYXJkIHRlcm1zIGFuZCBjb25kaXRpb25zIG9mIHVz
+ZSwgY2VydGlmaWNhdGUgcG9saWN5IGFuZCBjZXJ0aWZpY2F0aW9uIHByYWN0aWNl
+IHN0YXRlbWVudHMuMDUGCCsGAQUFBwIBFilodHRwOi8vd3d3LmFwcGxlLmNvbS9j
+ZXJ0aWZpY2F0ZWF1dGhvcml0eTATBgNVHSUEDDAKBggrBgEFBQcDAjAwBgNVHR8E
+KTAnMCWgI6Ahhh9odHRwOi8vY3JsLmFwcGxlLmNvbS93d2RyY2EuY3JsMB0GA1Ud
+DgQWBBT5dt+ltyw4BG7N+r/1dJ+tgxrpjjAOBgNVHQ8BAf8EBAMCB4AwEAYKKoZI
+hvdjZAYDAQQCBQAwEAYKKoZIhvdjZAYDAgQCBQAwgYkGCiqGSIb3Y2QGAwYEezB5
+DBZjb20uYW5zamVyLmN1c3RvbWl6ZWRlMAUMA2FwcAwbY29tLmFuc2plci5jdXN0
+b21pemVkZS52b2lwMAYMBHZvaXAMI2NvbS5hbnNqZXIuY3VzdG9taXplZGUuY29t
+cGxpY2F0aW9uMA4MDGNvbXBsaWNhdGlvbjANBgkqhkiG9w0BAQsFAAOCAQEAOS3j
+rVNOYYSoEYf7OgUl26ubcAMyYwVHhggxtQw0hR63+pdSXWi2/E5IynEf7qmBmbk/
+wTuIkWXnvR5a+sjJy+f94TM9Qe5bXvSuqQn+3HA0XruuBq1A7OGfbORBBZwwNSWZ
+mEjBd9vNdT3ZDksY2XSLvoKOE8gW7i60u4dE5GYqxe3CnICXLlgKjWZx5xbbMl/m
+W6j6ikKOVCqIG6nA8uUwrbznZQAUfQHblB2Yj58zOpCg/0KLqmtQMQJG4kCnZres
+4FElErUr0aEJXPTLqTHLX3PlvFA7Iwb7alTA8a7AFJYxyB184XoKS7rV8MZLuhdd
+wIggtF2b+92ah39F4w==
+-----END CERTIFICATE-----
+-----BEGIN RSA PRIVATE KEY-----
+MIIEpAIBAAKCAQEAuIhNiP1jkZsfHD8nyx6G5DjF4RONEZGMUYph5GFpQSlnY4c1
+IeHFcNa7qKnvrx3t2ZnIIKaAaMWcw+9XiK3KNDpo/A4CEt/Es0Dh5gDze8bG8DK1
+qORI5XMDUC3r2wRdZ1jSSDcXJ0FubyIkxrOaCe4J0hlJkPbzB/2z9AXMhSh4Uhzc
+HUNMqfWbpzrUCG1nv0woA2MaWrw9OiwLy4HckGHXDJEV1eIPsN3v+W5RoP2VJp69
+gx7M2LH5KcFTvpzhlcXl4elSETgU07dqHnoHkSaVVNB8dmPmpHn11Sk8S+fm1qMt
+Ny9PB5gmMaCQt31+YThFp1rl8Zs4ERVmbPWtVQIDAQABAoIBAF9NjfW9IApYOgYF
+nBCsUHBX3eKzjTzQlc6bEJm5sXmE36+oacl459ayIDMoqPAhHfEvGgu60kDKJn+P
+Af9F+lNlA0mCFpIW3WjSjpiSTy3S6HWvSuDSHc/ayZBEVzZDF9ZDKj8/rIaKpXVi
+BepVYa3VMV8/zh2/XJ746VKTGCCAd0fLHHL4A0GRHnNBktLB9Ik3KzMqg+3yh2K3
+gDdl1zP1vVgUHZUw6wSwYVUVycsSxD1uwa4iKs1G6taWK0hm2cZ/UkFHfLylWymx
+ZMU/zXeloIHz2/PwWrczx7lBEgaYNQ3rptgc+BbafHBEIpH36XlU1N2wdQUAkQqC
+VeCxbQECgYEA83imEE5pwCdBxcbg7WXL5GrvQqdzCxkqL8xSsftDklvyHGktc8OU
+XBkVkip+D9FBSNbKYWzCGXBaHg6mdtskmkxsq9rALzIzvVDNJ0r4WzyuRi//AEbV
+Mg+gZ3NeXYx61pwE0tYEC1RocboYGEpYGbJ6+SXG/BySiks7FBukJ8ECgYEAwgc6
+Pcfu7dUmFrj31xjylVgpdhsZNDr200eKgJ1dE3wbrJYz31sVMYULhaoJGKrYKNKY
+ECTDmhywKnM/0Z9MqpG64VWeR10hEbsL+bKrVbPQZkLKGpichNRF7QIOT64cjZt2
+kjMYCWEp+ip8yy9PrVufVqrhG6/a6XxXQGwdCpUCgYEAv4n86vslStwXbGaHcXwS
+KYLO89sUMHj9rVjK/eY0RKI9GIjODzKgNswtIi53ui3fdFQ2JusO0ECJRPg1kW/Z
+neHd5F1VsEuIVLmKjAz40Z4tZF5B+I/BDX8pq/khFet8f/WB/fQMfnVLLZ0/c2yZ
+Xq4A/JzxrEk2J8IDmlAcloECgYEAmawjwr7RS+kfq6uAEAqgRwx2eiZoRefVie0F
+k2wPRdlsCbtFBkgbdwcK4yiS38igP2TcLx0PFsZV+KkjCKGElSuqucGYBKmMAYEF
+sRSDgvNRwUxwybPJc6K0Z0zTjOQ3lShmNtDk3rjoCE0SXdLw5jrE7l2UwNr9JSPn
+7wwxzCkCgYBCRf/n0ID2NcsbVJBhxqel19Pa3vxxvY7Lw1j0kzgXx4a5LrOw6qnZ
+KRQUOK9EMrby63tjrIE9p2xuwXj7r0jMi9GFrk0fd1yLBveqAt/Hq9+DmWU4YDSN
+ZnxCyQ+VQ+wGtVqmuwV0iUWnnhhSLYuaqVgvsnY1QoNmxHIXgSV04g==
+-----END RSA PRIVATE KEY-----

+ 1 - 0
Ansjer/formal_settings.py

@@ -111,6 +111,7 @@ DATABASE_APPS_MAPPING = {
     'db2': 'mysql02',
 }
 
+
 AUTH_PASSWORD_VALIDATORS = [
     {
         'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',

+ 27 - 0
Ansjer/formal_statistics_push_month_task.py

@@ -0,0 +1,27 @@
+import json
+
+import requests
+
+
+# url = 'http://test.dvema.com'
+base_url = 'http://dvema.com/'
+username='13800138001'
+password='ansjer123456'
+login_url = base_url + 'account/login'
+
+data = {
+    'userName': username,
+    'userPwd': password
+}
+res = requests.post(url=login_url, data=data)
+res = res.json()
+print(res)
+
+if res['result_code'] == 0:
+    statistics_url = base_url + 'statistcs/pushMonth'
+    data = {
+        'token': res['result']['access_token']
+    }
+    res = requests.post(url=statistics_url, data=data)
+    print(res.json())
+

+ 46 - 0
Ansjer/formal_zositech_help_weekly_task.py

@@ -0,0 +1,46 @@
+import json
+
+import requests
+import time
+
+
+# url = 'http://test.dvema.com'
+# base_url = 'http://127.0.0.1:8000/'
+base_url = 'http://dvema.com/'
+username='13800138001'
+password='ansjer.x123789'
+login_url = base_url + 'account/login'
+
+data = {
+    'userName': username,
+    'userPwd': password
+}
+res = requests.post(url=login_url, data=data)
+res = res.json()
+
+if res['result_code'] == 0:
+    isbool = True
+    while isbool:
+        try:
+            statistics_url = base_url + 'faq/synZositechHelp'
+            zhcnDatares = requests.get(
+                url='https://mobileapphelp.zendesk.com/api/v2/help_center/articles/embeddable_search.json?locale=zh-cn&section=null&origin=web_widget', timeout=1).text
+
+            enusDatares = requests.get(
+                url='https://mobileapphelp.zendesk.com/api/v2/help_center/articles/embeddable_search.json?locale=en-us&section=null&origin=web_widget', timeout=1).text
+
+            data = {
+                'token': res['result']['access_token'],
+                'zhresults': zhcnDatares,
+                'enresults': enusDatares
+            }
+            isbool = False
+            res = requests.post(url=statistics_url, data=data)
+
+        except Exception as e:
+            isbool=True
+            time.sleep(3)
+
+
+
+

+ 46 - 0
Ansjer/generacode.py

@@ -0,0 +1,46 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import json
+
+import xlwt
+
+from Object.TokenObject import TokenObject
+import base64
+import requests
+
+token = TokenObject()
+token = token.generate({'userID': str(2)})
+
+file = open('./file/UID-2020-09-09-06-14-44.txt', mode='r', encoding='utf-8')
+content = file.read()
+content = content.replace(' ', '\t')
+
+file1 = open('./file/UID_2020_09_09_06_14_44.txt', mode='w', encoding='utf-8')
+file1.write(content)
+file1.close()
+
+tmps = content.split('\n')
+workbook = xlwt.Workbook(encoding='utf-8')
+sheet1 = workbook.add_sheet('UID')
+num = 0
+for tmp in tmps:
+    lines = tmp.split('\t')
+    for i in range(len(lines)):
+        sheet1.write(num, i, lines[i].strip())
+    num += 1
+
+workbook.save('./file/UID_2020_09_09_06_14_44.xls')
+
+
+file.close()
+
+# url = 'http://192.168.136.35:8000/upload'
+# postData = {
+#     'area': 0,
+#     'token': token['access_token'],
+#     'fileName': content
+# }
+# # postData = json.dumps(postData)
+# print(postData)
+# res = requests.post(url=url, data=postData)
+# print(res)

+ 29 - 7
Ansjer/local_settings.py

@@ -31,7 +31,7 @@ MIDDLEWARE = [
     'django.contrib.messages.middleware.MessageMiddleware',
     'django.middleware.clickjacking.XFrameOptionsMiddleware',
     'django.middleware.security.SecurityMiddleware',
-    'django_global_request.middleware.GlobalRequestMiddleware',
+    # 'django_global_request.middleware.GlobalRequestMiddleware',
 ]
 
 AUTHENTICATION_BACKENDS = (
@@ -72,18 +72,19 @@ TEMPLATES = [
 
 WSGI_APPLICATION = 'Ansjer.local_wsgi.application'
 
-
 # 服务器类型
-DATABASE_DATA = 'ansjerlocal'
+DATABASE_DATA = 'ansjertest'
 SERVER_HOST = '127.0.0.1'
 DATABASES_USER = 'root'
-DATABASES_PASS = '123456'
+DATABASES_PASS = 'mysqlfyzs9wl'
 
-DATABASE_DATA2 = 'asjl'
+DATABASE_DATA2 = 'ansjerpush'
 SERVER_HOST2 = '127.0.0.1'
 DATABASES_USER2 = 'root'
 DATABASES_PASS2 = '123456'
 
+
+
 DATABASES = {
     'default': {
         'ENGINE': 'django.db.backends.mysql',
@@ -108,11 +109,10 @@ DATABASES = {
 }
 DATABASE_ROUTERS = ['Ansjer.database_router.DatabaseAppsRouter']
 DATABASE_APPS_MAPPING = {
-    'db1': 'default',
+    'Model': 'default',
     'db2': 'mysql02',
 }
 
-
 AUTH_PASSWORD_VALIDATORS = [
     {
         'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
@@ -197,6 +197,12 @@ LOGGING = {
             # 'format': '{"asctime":"%(asctime)s","thread":"%(threadName)s:%(thread)d","errorline":"%(lineno)d","errorlevel":"%(levelname)s","errorcontent":"%(message)s"}'
             'format': '%(asctime)s %(threadName)s %(thread)d %(lineno)d %(levelname)s %(message)s'
         },
+        'standard': {
+            'format': '[%(asctime)s] [%(filename)s:%(lineno)d] [%(module)s:%(funcName)s] '
+                      '[%(levelname)s]- %(message)s'},
+        'simple': {  # 简单格式
+            'format': '%(levelname)s %(message)s'
+        },
     },
     'filters': {
     },
@@ -220,6 +226,16 @@ LOGGING = {
             'class': 'logging.StreamHandler',
             'formatter': 'error_format'
         },
+        # 输出info日志
+        'info': {
+            'level': 'INFO',
+            'class': 'logging.handlers.RotatingFileHandler',
+            'filename': BASE_DIR + '/static/log/info.log',
+            'maxBytes': 1024 * 1024 * 5,
+            'backupCount': 5,
+            'formatter': 'standard',
+            'encoding': 'utf-8',  # 设置默认编码
+        },
     },
     'loggers': {
         'django': {
@@ -229,6 +245,12 @@ LOGGING = {
             'level': 'DEBUG',
             'propagate': True
         },
+        # log 调用时需要当作参数传入
+        'log': {
+            'handlers': ['info', 'console', 'default'],
+            'level': 'INFO',
+            'propagate': True
+        },
         # 'django.db.backends': {
         #     'handlers': ['console'],
         #     'propagate': True,

+ 27 - 0
Ansjer/push_element_into_redis.py

@@ -0,0 +1,27 @@
+import _thread
+
+from Object.RedisObject import RedisObject
+
+key = 'serial_lock'
+key1 = 'create_serial_lock'
+key2 = 'company_serial_lock'
+redisObject = RedisObject()
+
+value = redisObject.lrange(key, 0, 1)
+if len(value) == 0:
+    redisObject.rpush(key, 1)
+
+value = redisObject.lrange(key1, 0, 1)
+if len(value) == 0:
+    redisObject.rpush(key1, 1)
+
+value = redisObject.lrange(key2, 0, 1)
+if len(value) == 0:
+    redisObject.rpush(key2, 1)
+
+
+
+
+
+
+

+ 28 - 1
Ansjer/test_settings.py

@@ -108,7 +108,7 @@ DATABASES = {
 }
 DATABASE_ROUTERS = ['Ansjer.database_router.DatabaseAppsRouter']
 DATABASE_APPS_MAPPING = {
-    'db1': 'default',
+    'Model': 'default',
     'db2': 'mysql02',
 }
 
@@ -196,6 +196,12 @@ LOGGING = {
             # 'format': '{"asctime":"%(asctime)s","thread":"%(threadName)s:%(thread)d","errorline":"%(lineno)d","errorlevel":"%(levelname)s","errorcontent":"%(message)s"}'
             'format': '%(asctime)s %(threadName)s %(thread)d %(lineno)d %(levelname)s %(message)s'
         },
+        'standard': {
+            'format': '[%(asctime)s] [%(filename)s:%(lineno)d] [%(module)s:%(funcName)s] '
+                      '[%(levelname)s]- %(message)s'},
+        'simple': {  # 简单格式
+            'format': '%(levelname)s %(message)s'
+        },
     },
     'filters': {
     },
@@ -217,14 +223,35 @@ LOGGING = {
             'level': 'ERROR',
             'class': 'logging.StreamHandler',
             'formatter': 'error_format'
+        },# 输出info日志
+        'info': {
+            'level': 'INFO',
+            'class': 'logging.handlers.RotatingFileHandler',
+            'filename': BASE_DIR + '/static/log/info.log',
+            'maxBytes': 1024 * 1024 * 5,
+            'backupCount': 5,
+            'formatter': 'standard',
+            'encoding': 'utf-8',  # 设置默认编码
         },
     },
     'loggers': {
         'django': {
             'handlers': ['default', 'console'],
             # 'handlers': ['mail_admins','default','console'],
+            # 'level': 'ERROR',
             'level': 'ERROR',
             'propagate': False
         },
+        # log 调用时需要当作参数传入
+        'log': {
+            'handlers': ['info', 'console', 'default'],
+            'level': 'INFO',
+            'propagate': True
+        },
+        # 'django.db.backends': {
+        #     'handlers': ['console'],
+        #     'propagate': True,
+        #     'level': 'DEBUG',
+        # },
     }
 }

+ 27 - 0
Ansjer/test_statistics_push_month_task.py

@@ -0,0 +1,27 @@
+import json
+
+import requests
+
+
+# url = 'http://test.dvema.com'
+base_url = 'http://test.dvema.com/'
+username='13800138001'
+password='ansjer999999'
+login_url = base_url + 'account/login'
+
+data = {
+    'userName': username,
+    'userPwd': password
+}
+res = requests.post(url=login_url, data=data)
+res = res.json()
+print(res)
+
+if res['result_code'] == 0:
+    statistics_url = base_url + 'statistcs/pushMonth'
+    data = {
+        'token': res['result']['access_token']
+    }
+    res = requests.post(url=statistics_url, data=data)
+    print(res.json())
+

+ 46 - 0
Ansjer/test_zositech_help_weekly_task.py

@@ -0,0 +1,46 @@
+import json
+
+import requests
+import time
+
+
+# url = 'http://test.dvema.com'
+# base_url = 'http://127.0.0.1:8000/'
+base_url = 'http://test.dvema.com/'
+username='13800138001'
+password='ansjer999999'
+login_url = base_url + 'account/login'
+
+data = {
+    'userName': username,
+    'userPwd': password
+}
+res = requests.post(url=login_url, data=data)
+res = res.json()
+
+if res['result_code'] == 0:
+    isbool = True
+    while isbool:
+        try:
+            statistics_url = base_url + 'faq/synZositechHelp'
+            zhcnDatares = requests.get(
+                url='https://mobileapphelp.zendesk.com/api/v2/help_center/articles/embeddable_search.json?locale=zh-cn&section=null&origin=web_widget', timeout=1).text
+
+            enusDatares = requests.get(
+                url='https://mobileapphelp.zendesk.com/api/v2/help_center/articles/embeddable_search.json?locale=en-us&section=null&origin=web_widget', timeout=1).text
+
+            data = {
+                'token': res['result']['access_token'],
+                'zhresults': zhcnDatares,
+                'enresults': enusDatares
+            }
+            isbool = False
+            res = requests.post(url=statistics_url, data=data)
+
+        except Exception as e:
+            isbool=True
+            time.sleep(3)
+
+
+
+

+ 60 - 4
Ansjer/urls.py

@@ -1,3 +1,4 @@
+from django.contrib import admin
 from django.conf.urls import url
 from django.urls import path, re_path
 
@@ -10,12 +11,15 @@ from Controller import FeedBack, EquipmentOTA, EquipmentInfo, AdminManage, AppIn
     StsOssController, UIDPreview, OssCrd, SysMsg, UidUser, EquipmentManagerV2, EquipmentManagerV3, PushDeploy, \
     AppSetController, \
     ApplicationController, UserExController, CloudStorage, TestApi, UserBrandControllerV2, \
-    StatisticsController, Alexa, FAQController, AppLogController, EquipmentVersionLimit, DeviceTypeController, \
-    VoicePromptController
+    StatisticsController, Alexa, FAQController, AppLogController, EquipmentVersionLimit, VoicePromptController, \
+    CDKController, \
+    DeviceTypeController, CloudTransfer, Cloudsum, IotCoreController, OperatingLogs, ProcessInfo, RegionCountryController, \
+    VerifyCodeController, FileController, UIDController, LogController, SalesController, \
+    OrderTaskController, HistoryUIDController, UIDManageUserController, SerialNumberController, CompanyController, \
+    RegionController, VPGController, LanguageController, TestController, DeviceConfirmRegion
 
 urlpatterns = [
     url(r'^testApi/(?P<operation>.*)$', TestApi.testView.as_view()),
-
     url(r'^account/authcode$', UserController.authCodeView.as_view()),
     url(r'^v3/account/generatepictureCodeView/$', UserController.generatePictureCodeView.as_view()),
     url(r'^v3/account/imageCodeRegister/$', UserController.Image_Code_RegisterView.as_view()),
@@ -106,11 +110,14 @@ urlpatterns = [
     path('access/staticPath/', AccessLog.statisticsPath),
     path('access/deleteSn/', AccessLog.deleteSn),
     path('eq/del', EquipmentInfo.deleteExpireEquipmentInfo),
+    path('eq/delById', EquipmentInfo.deleteExpireEquipmentInfoById),
     # 新需求ota接口
     url(r'^OTA/getNewVer', OTAEquipment.getNewVerInterface),
     url(r'^OTA/uploadsPack$', OTAEquipment.uploadOTAInterfaceView.as_view()),
     url(r'^OTA/downloadsPack/(?P<fullPath>[0-9\w/.\-]+)', OTAEquipment.downloadOTAInterface),
     url(r'^dlotapack/(?P<fullPath>[0-9\w/.\-]+)', OTAEquipment.downloadOTAInterfaceV2),
+    url(r'^OTA/getDownLoadOTApackUrl$', OTAEquipment.getDownLoadOTApackUrl),
+    url(r'^OTA/checkMaxVersion$', OTAEquipment.checkMaxVersion),
 
     # h获取验证码    # v2接口
     url(r'^v2/account/authcode$', UserController.v2authCodeView.as_view()),
@@ -150,6 +157,7 @@ urlpatterns = [
 
     # 屏蔽
     url(r'^user/initInfo$', UserController.InitInfoView.as_view()),
+    url(r'^user/information/(?P<operation>.*)$', UserController.InitUserInformationView.as_view()),
     # 获取时区相关信息
     url(r'^getTZ$', EquipmentStatus.getTZ),
 
@@ -178,6 +186,7 @@ urlpatterns = [
     url(r'^oauth/unbunding', UserController.UnbundingWXView.as_view()),
 
     # 删除云存视频
+    # path('cv/del', CloudVod.deleteVodHls),
     path('cv/del', CloudStorage.deleteVodHls),
     path('cv/updateExpiredUidBucket', CloudStorage.updateExpiredUidBucket),
     path('cv/updateUnusedUidBucket', CloudStorage.updateUnusedUidBucket),
@@ -238,21 +247,68 @@ urlpatterns = [
 
     # 本地登录接口
     url(r'^local/(?P<operation>.*)$', UserController.LocalUserView.as_view()),
+
     url(r'^account/updateUserCountry', UserController.updateUserCountry),
     url(r'^equipmentVersionLimit/(?P<operation>.*)$', EquipmentVersionLimit.EquipmentVersionLimitView.as_view()),
 
     # 订阅邮件
     url(r'^account/subscribe$', UserController.SubscribeEmailView.as_view()),
+    url(r'^account/subscribe/download$', UserController.SubscribeEmailView.as_view()),
+
     # 语音提示
     url(r'^voicePrompt/(?P<operation>.*)$', VoicePromptController.VoicePromptView.as_view()),
-
     # 设备类型
     url(r'^deviceType/(?P<operation>.*)$', DeviceTypeController.DeviceTypeView.as_view()),
 
+    # cdk(激活码)
+    url(r'^cdk/(?P<operation>.*)$', CDKController.CDKView.as_view()),
+    # 云存转移功能
+    url(r'^cloudTransfer/(?P<operation>.*)$', CloudTransfer.cloudTestView.as_view()),
+
     # app 设备消息模板
     # 路由加参数参考
     # url(r'^(?P<path>.*)/(?P<UID>.*)/lls$', Test.Test.as_view(), name=u'gg'),
     #testing....................
+
+    #云存服务统计
+    url(r'^Cloudsum/(?P<operation>.*)$', Cloudsum.Cloudsum.as_view()),
+
+    #Iot Core
+    url(r'iot/(?P<operation>.*)$', IotCoreController.IotCoreView.as_view()),
+
+    # 云分配UID
+    path('admin/', admin.site.urls),
+    re_path('user/(?P<operation>.*)', UIDManageUserController.UserView.as_view()),
+    re_path('uid/(?P<operation>.*)', UIDController.UIDView.as_view()),
+    re_path('history/(?P<operation>.*)', HistoryUIDController.HistoryUIDView.as_view()),
+    re_path('log/(?P<operation>.*)', LogController.LogView.as_view()),
+    re_path('orderTask/(?P<operation>.*)', OrderTaskController.OrderTaskView.as_view()),
+    path('upload', FileController.UploadUIDFileView.as_view()),
+    path('download', FileController.DownloadUIDFileView.as_view()),
+    path('sales', SalesController.SalesView.as_view()),
+    path('device/online', SalesController.DeviceOnlineView.as_view()),
+    re_path('serialNumber/(?P<operation>.*)', SerialNumberController.SerialNumberView.as_view()),
+    re_path('company/(?P<operation>.*)', CompanyController.CompanyView.as_view()),
+    re_path('region/(?P<operation>.*)', RegionController.RegionView.as_view()),
+    re_path('vpg/(?P<operation>.*)', VPGController.VPGView.as_view()),
+    path('vpgUid/uid', VPGController.do_upload_uid),
+    re_path('language/(?P<operation>.*)', LanguageController.LanguageView.as_view()),
+
+
+    re_path('test/(?P<operation>.*)', TestController.TestView.as_view()),
+    # 日志管理系统
+    url(r'^OperatingLogs/(?P<operation>.*)$', OperatingLogs.OperatingLogsView.as_view()),
+    url(r'^ProcessInfo/(?P<operation>.*)$', ProcessInfo.ProcessInfoView.as_view()),
+    url(r'^Cloudsum/(?P<operation>.*)$', Cloudsum.Cloudsum.as_view()),
+
+    url(r'regionCountry/(?P<operation>.*$)', RegionCountryController.RegionCountryView.as_view()),
+
+    # 验证验证码
+    url(r'verifyCode/(?P<operation>.*$)', VerifyCodeController.VerifyCodeView.as_view()),
+
+    #设备确定分配地区
+    url(r'^device/confirmRegion$', DeviceConfirmRegion.ConfirmRegion.as_view()),
+
     re_path('(?P<path>.*)', LogManager.errorPath),
 
 

+ 16 - 0
Ansjer/wsgi.py

@@ -0,0 +1,16 @@
+"""
+WSGI config for AnsjerUIDManage project.
+
+It exposes the WSGI callable as a module-level variable named ``application``.
+
+For more information on this file, see
+https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
+"""
+
+import os
+
+from django.core.wsgi import get_wsgi_application
+
+os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AnsjerUIDManage.settings')
+
+application = get_wsgi_application()

+ 2 - 0
Controller/AccessLog.py

@@ -19,6 +19,8 @@ http://192.168.136.40:8077/accesslog?operation=queryByAdmin&token=test&page=1&li
 http://192.168.136.40:8077/accesslog?operation=truncateByAdmin&token=test
 http://192.168.136.40:8077/accesslog?operation=searchByAdmin&token=test&page=1&line=10&content={"status":20}&order=-id
 
+
+
 http://192.168.136.40:8077/accesslog/staticPath/?token=stest
 '''
 

+ 12 - 12
Controller/AdminManage.py

@@ -10,6 +10,8 @@ from django.views.decorators.csrf import csrf_exempt
 from django.views.generic import TemplateView
 from django.utils.decorators import method_decorator
 from django.contrib.auth.hashers import make_password  # 对密码加密模块
+from openpyxl import workbook
+
 from Model.models import Device_Info, Role, UserExModel, User_Brand, UidSetModel, AppFrequencyYearStatisticsModel, \
     AppFrequencyStatisticsModel, EquipmentInfoExStatisticsModel, Equipment_Info
 from Service.ModelService import ModelService
@@ -83,14 +85,14 @@ class AdminManage(TemplateView):
             return self.getAppFrequency(userID, request_dict, response)
         if operation == 'getHistoryAppFrequency':
             return self.getAllAppFrequency(userID, response)
-        if operation == 'downloadSubscribeEmail':
-            return self.download_subscribe_email(userID, request_dict, response)
         if operation == 'getPushStatistics':
             return self.query_push_by_level(userID, request_dict, response)
         if operation == 'getPushFailures':
             return self.query_failures_push(userID, request_dict, response)
         if operation == 'getPushServerCPUUsage':
             return self.query_push_server_cpu_usage(userID, request_dict, response)
+        if operation == 'downloadSubscribeEmail':
+            return self.download_subscribe_email(userID, request_dict, response)
 
     def resetUserPwd(self, request_dict, userID, response):
         own_permission = ModelService.check_perm(userID=userID, permID=50)
@@ -467,15 +469,12 @@ class AdminManage(TemplateView):
 
     def query_push_day_statistics(self, level, response):
         start_time = 0
-        end_time = 0
-        # localtime = time.localtime()
-        # current_day = localtime.tm_mday
-        #
-        # time_struct = [localtime.tm_year, localtime.tm_mon, current_day, 0, 0, 0, 0, 0, 0]
-        # current_time = int(time.mktime(tuple(time_struct)))
-        current_time = int(time.time())
-        count = int(current_time / (24 * 3600))
-        current_time = count * 24 * 3600 - 8 * 3600
+
+        gmtime = time.gmtime(int(time.time()) + 28800)
+        current_day = gmtime.tm_mday
+        time_struct = [gmtime.tm_year, gmtime.tm_mon, current_day, 0, 0, 0, 0, 0, 0]
+        current_time = int(time.mktime(tuple(time_struct))) - 28800
+
         count = 0
         if level == 0: # 七天
             start_time = current_time - 6 * 24 * 3600
@@ -639,6 +638,7 @@ class AdminManage(TemplateView):
         except Exception as e:
             print(repr(e))
             return response.json(10, 'AWS Server Error')
+
     def download_subscribe_email(self, userID, request_dict, response):
         own_permission = ModelService.check_perm(userID=userID, permID=30)
         if own_permission is not True:
@@ -662,6 +662,7 @@ class AdminManage(TemplateView):
         workbook.save(response)
         return response
 
+
 def getCompareKey(item):
     return item['Timestamp']
 
@@ -750,4 +751,3 @@ def search_user_by_content(request):
         sqlDict['count'] = count
         return response.json(0, sqlDict)
     return response.json(0, {'datas': [], 'count': 0})
-

+ 19 - 3
Controller/AppSetController.py

@@ -55,6 +55,7 @@ class AppSetView(View):
 
     # 查询
     def do_query(self, request_dict, response):
+        lang = request_dict.get('lang', None)
         appBundleId = request_dict.get('appBundleId', None)
         if not appBundleId:
             return response.json(444,'appBundleId')
@@ -64,19 +65,34 @@ class AppSetView(View):
             key_id= "www"+appBundleId
         else:
             key_id = "test" + appBundleId
-        redis_value = redis.get_data(key=key_id)
+        #redis_value = redis.get_data(key=key_id)  去除到缓存中找
+        redis_value = False
         if redis_value == False:
             print('添加到缓存')
             # 查数据库
             sm_qs = AppSetModel.objects.filter(appBundleId=appBundleId)
             count = sm_qs.count()
             if count > 0:
+
                 sm_qs = sm_qs.values("content")
                 # 添加到缓存,缓存时间为3600秒------指的是一个钟后再次访问,就会刷新缓存一次
-                content_json_str = list(sm_qs)[0]['content'].replace("'", '"')
+                dict_json = json.loads(sm_qs[0]['content'])
+                if 'editionUpgrading' in dict_json :
+                    if  dict_json['editionUpgrading'] == 1:
+                        if lang !='cn':
+                            dict_json['editionUpgrading'] = 'Upgrading, please sign in later'
+                        else:
+                            dict_json['editionUpgrading'] = '正在升级,请稍后登录'
+                    else:
+                        dict_json['editionUpgrading'] = ''
+
+
+
+                content_json_str = dict_json
+
                 redis.set_data(key=key_id, val=content_json_str, expire=3600)
                 # 返回固定值
-                return response.json(0, json.loads(list(sm_qs)[0]['content']))
+                return response.json(0, content_json_str)
             else:
                 return response.json(173)
         else:

+ 41 - 10
Controller/CloudStorage.py

@@ -40,7 +40,7 @@ from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, OSS_ROLE_AR
     JPUSH_CONFIG, FCM_CONFIG, OAUTH_ACCESS_TOKEN_SECRET
 from Model.models import Device_Info, Order_Model, Store_Meal, VodHlsModel, OssCrdModel, UID_Bucket, StsCrdModel, \
     ExperienceContextModel, Pay_Type, CDKcontextModel, Device_User, SysMassModel, SysMsgModel, UidPushModel, \
-    Unused_Uid_Meal, RegionCountryModel
+    Unused_Uid_Meal, UIDMainUser
 from Object.AliPayObject import AliPayObject
 from Object.ResponseObject import ResponseObject
 from Object.TokenObject import TokenObject
@@ -185,9 +185,6 @@ class CloudStorageView(View):
         qs = Store_Meal.objects
         eq = ExperienceContextModel.objects.filter(uid=uid, experience_type=0).values('id')
 
-        #userObj = Device_User.objects.get(userID=userID)
-        #regionObj = RegionCountryModel.objects.get(number=userObj.region_country)
-
         if mold:
             qs = qs.filter(bucket__mold=mold,lang__lang=lang)
         else:
@@ -778,6 +775,14 @@ class CloudStorageView(View):
                         }
                         dvq.update(**dvq_set_update_dict)
 
+                    uid_main_exist = UIDMainUser.objects.filter(UID=UID)
+                    if not uid_main_exist.exists():
+                        uid_main_dict = {
+                            'UID': UID,
+                            'user_id': userid
+                        }
+                        UIDMainUser.objects.create(**uid_main_dict)
+
                     order_qs.update(status=1, updTime=nowTime, uid_bucket_id=uid_bucket_id)
                     sys_msg_text_list = ['成功购买云存', 'Successful purchase of cloud storage']
                     self.do_vod_msg_Notice(UID, channel, userid, lang, sys_msg_text_list)
@@ -874,6 +879,15 @@ class CloudStorageView(View):
                         'vodPrimaryMaster': username
                     }
                     dvq.update(**dvq_set_update_dict)
+
+                uid_main_exist = UIDMainUser.objects.filter(UID=UID)
+                if not uid_main_exist.exists():
+                    uid_main_dict = {
+                        'UID': UID,
+                        'user_id': userid
+                    }
+                    UIDMainUser.objects.create(**uid_main_dict)
+
                 order_qs.update(status=1, updTime=nowTime, uid_bucket_id=uid_bucket_id)
                 sys_msg_text_list = ['成功购买云存','Successful purchase of cloud storage']
                 self.do_vod_msg_Notice(UID, channel, userid, lang, sys_msg_text_list)
@@ -965,6 +979,15 @@ class CloudStorageView(View):
                             'vodPrimaryMaster': username
                         }
                         dvq.update(**dvq_set_update_dict)
+
+                    uid_main_exist = UIDMainUser.objects.filter(UID=UID)
+                    if not uid_main_exist.exists():
+                        uid_main_dict = {
+                            'UID': UID,
+                            'user_id': userid
+                        }
+                        UIDMainUser.objects.create(**uid_main_dict)
+
                     order_qs.update(status=1, updTime=nowTime, uid_bucket_id=uid_bucket_id)
                     sys_msg_text_list = ['成功购买云存', 'Successful purchase of cloud storage']
                     self.do_vod_msg_Notice(UID, channel, userid, lang, sys_msg_text_list)
@@ -1237,6 +1260,14 @@ class CloudStorageView(View):
                     }
                     dvq.update(**dvq_set_update_dict)
 
+                uid_main_exist = UIDMainUser.objects.filter(UID=uid)
+                if not uid_main_exist.exists():
+                    uid_main_dict = {
+                        'UID': uid,
+                        'user_id': userID
+                    }
+                    UIDMainUser.objects.create(**uid_main_dict)
+
                 sys_msg_text_list = ['成功购买云存', 'Successful purchase of cloud storage']
                 # return response.json(0)
                 returnurl = "{SERVER_DOMAIN_SSL}cloudstorage/payOK?lang={lang}".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL,lang=lang)
@@ -1318,7 +1349,7 @@ class CloudStorageView(View):
         bucket_id_list = []
         store_list = []
         uid_bucket = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time).values("id", "uid","bucket__content",
-                                                                                      "use_status","endTime","has_unused","bucket__id")
+                                                                    "use_status","endTime","has_unused","bucket__id")
         if not uid_bucket:
             return response.json(10030)
         uid_bucket[0]['storage'] = 0
@@ -1362,9 +1393,9 @@ class CloudStorageView(View):
         if unused_id:
             # 切换设备套餐关联
             using_uid_bucket = UID_Bucket.objects.filter(uid=uid,has_unused=1).values("id", "uid", "endTime",
-                                                                                      "bucket__content","addTime")
+                                                                 "bucket__content","addTime")
             unuseds = Unused_Uid_Meal.objects.filter(id=unused_id).values("id","uid","channel","addTime","expire",
-                                                                          "num","bucket_id")
+                                                                         "num","bucket_id")
             if not unuseds.exists() or not using_uid_bucket.exists():
                 return response.json(10030)
             unused = unuseds[0]
@@ -1608,7 +1639,7 @@ def updateUnusedUidBucket(request):
     expired_uid_buckets = UID_Bucket.objects.filter(endTime__lte=now_time,has_unused=1).values("id","uid")[0:1000]
     for expired_uid_bucket in expired_uid_buckets:
         unuseds = Unused_Uid_Meal.objects.filter(uid=expired_uid_bucket['uid']).values("id","uid","channel","addTime","expire",
-                                                                                       "num","bucket_id","userID_id").order_by('addTime')[0:1]
+                                                                  "num","bucket_id").order_by('addTime')[0:1]
         if not unuseds.exists():
             continue
         unused = unuseds[0]
@@ -1618,8 +1649,8 @@ def updateUnusedUidBucket(request):
                 has_unused = 1 if count_unused>1 else 0
                 endTime = CommonService.calcMonthLater(unused['expire'] * unused['num'])
                 UID_Bucket.objects.filter(uid=expired_uid_bucket['uid']).update(channel=unused['channel'],endTime=endTime,bucket_id=unused['bucket_id']
-                                                                                ,updateTime=now_time,use_status=1,userID_id=unused['userID_id'],
-                                                                                has_unused=has_unused)
+                                                          ,updateTime=now_time,use_status=1,
+                                                          has_unused=has_unused)
                 Unused_Uid_Meal.objects.filter(id=unused['id']).delete()
                 StsCrdModel.objects.filter(uid=expired_uid_bucket['uid']).delete()  # 删除sts记录
                 VodHlsModel.objects.filter(uid=expired_uid_bucket['uid']).delete()  # 删除播放列表,后期数据量多时应该考虑延后删除

+ 16 - 1
Controller/CloudTransfer.py

@@ -14,7 +14,7 @@ from Service.CommonService import CommonService
 from Service.ModelService import ModelService
 from Object.ResponseObject import ResponseObject
 from Model.models import Device_User, Device_Info, Order_Model, UID_Bucket, StsCrdModel, VodHlsModel, Unused_Uid_Meal, \
-    VodBucketModel
+    VodBucketModel, UIDMainUser
 
 
 class cloudTestView(View):
@@ -75,6 +75,13 @@ class cloudTestView(View):
             vodPrimaryUserID = old_deviceInfo_qs[0]['vodPrimaryUserID']
             if vodPrimaryUserID != '' and vodPrimaryUserID != oldUserID:
                 return response.json(10037)
+
+            uid_mian = UIDMainUser.objects.filter(UID=uid).values('UID', 'user_id')
+            if uid_mian.exists():
+                vodPrimaryUserID = uid_mian[0]['user_id']
+                if vodPrimaryUserID != '' and vodPrimaryUserID != oldUserID:
+                    return response.json(10037)
+
             # 判断新用户是否已有此设备
             new_deviceInfo_qs = Device_Info.objects.filter(userID_id=newUserID, UID=uid, isExist=1)
             if new_deviceInfo_qs:
@@ -91,6 +98,14 @@ class cloudTestView(View):
                 # 更新设备的主用户信息
                 Device_Info.objects.filter(UID=uid).update(vodPrimaryUserID=vodPrimaryUserID, vodPrimaryMaster=vodPrimaryMaster)
                 VodHlsModel.objects.filter(uid=uid).delete()
+
+                UIDMainUser.objects.filter(UID=uid).delete()
+                uid_main_dict = {
+                    'UID': uid,
+                    'user_id': newUserID
+                }
+                UIDMainUser.objects.create(**uid_main_dict)
+
         except Exception as e:
             # print(e)
             return response.json(500, repr(e))

+ 180 - 0
Controller/Cloudsum.py

@@ -0,0 +1,180 @@
+# -*- coding: utf-8 -*-
+"""
+@Time : 2021/1/8 12:00
+@Auth : liehaoquan
+@File :Cloudsum.py
+@IDE :PyCharm
+"""
+import json
+
+from Ansjer.config import SERVER_TYPE
+from Model.models import Order_Model, UID_Bucket, UserExModel, EquipmentLogModel
+from Object.RedisObject import RedisObject
+from Object.ResponseObject import ResponseObject
+from Object.TokenObject import TokenObject
+from django.views import View
+
+from Service.CommonService import CommonService
+from Service.ModelService import Device_User, ModelService
+from django.db.models import Count, Sum
+
+
+class Cloudsum(View):
+    def dispatch(self, requset, *args, **kwargs):
+        return super(Cloudsum, self).dispatch(requset, *args, **kwargs)
+
+    def get(self, request, *args, **kwargs):
+        operation = kwargs.get('operation')
+        request.encoding = 'utf-8'
+        return self.validation(request.GET, request, operation)
+
+    def post(self, request, *args, **kwargs):
+        operation = kwargs.get('operation')
+        request.encoding = 'utf-8'
+        return self.validation(request.POST, request, operation)
+
+    def validation(self, request_dict, request, operation):
+        response = ResponseObject()
+        token = request_dict.get('token', None)
+        tko = TokenObject(token)
+        response.lang = tko.lang
+        userID = tko.userID
+        print('userID:', userID)
+        if tko.code != 0:
+            return response.json(tko.code)
+        if userID is None or operation is None:
+            return response.json(444, 'operation')
+        if operation == 'cloudservicesum':
+            return self.cloudservicesum(userID, response)
+        if operation == 'userappversion':
+            return self.userappversion(userID, response)
+        if operation == 'usercount':
+            return self.usercount(userID, request_dict, response)
+        if operation == 'usercloud':
+            return self.usercloud(userID, response)
+        if operation == 'equipment_logs':
+            return self.equipment_logs(userID, request_dict, response)
+
+    # 类型:用户手机
+    # 统计用户手机型号  已有
+    # 统计某段时间内新用户的增长数√
+    # 统计一天用户打开zosi app的频率   已有
+    # 统计用户下载zosi app数,卸载人数
+    # 统计用户使用zosi app的版本√
+
+    # 统计用户使用zosi app的版本以及使用zosi app不同版本的用户数量
+    def userappversion(self, userID, response):
+        own_permission = ModelService.check_perm(userID=userID, permID=30)
+        if own_permission is not True:
+            return response.json(404)
+        res = UserExModel.objects.extra(tables=['app_info'],
+                                        select={'appname': 'app_info.appName',
+                                                'appversion': 'app_info.newAppversion'},
+                                        where=["user_ex.appBundleId=app_info.appBundleId"]). \
+            values('appBundleId', 'appname', 'appversion').annotate(dates=Count('appBundleId')).order_by()
+        print(res.query)
+        print(res)
+        return response.json(0, list(res))
+
+    # 统计某段时间内新用户的增长数
+    def usercount(self, userID, request_dict, response):
+        own_permission = ModelService.check_perm(userID=userID, permID=30)
+        if own_permission is not True:
+            return response.json(404)
+
+        # 优化代码
+        # usercountyear = request_dict.get('usercountyear', None)
+        # if usercountyear == None:
+        #     return response.json(444)
+        # usercountyear = int(usercountyear)
+        # count = Device_User.objects.extra(select={'dates': "DATE_FORMAT(data_joined,'%%Y-%%m')"},
+        #                                   where=["data_joined between '%s-01-01' and '%s-01-01' "],
+        #                                   params=[usercountyear, usercountyear+1]).values(
+        #     'dates').annotate(用户合计=Count('data_joined')).order_by('dates')
+        count = Device_User.objects.extra(select={'dates': "DATE_FORMAT(data_joined,'%%Y-%%m')"}, ).values(
+            'dates').annotate(用户合计=Count('data_joined')).order_by('dates')
+        print(count.query)
+        return response.json(0, list(count))
+
+    # 类型:云存服务统计
+    # 统计开通云存的设备有多少台√
+    # 统计未支付,支付成功的订单√
+    # 统计开通云存的增长率    (每个月开通云存套餐的总数)√
+    # 统计已开通云存的各套餐总数√
+    # 统计已支付的订单总金额√
+    def cloudservicesum(self, userID, response):
+        own_permission = ModelService.check_perm(userID=userID, permID=30)
+        if own_permission is not True:
+            return response.json(404)
+        uid_cloud = UID_Bucket.objects.values('uid').distinct().count()
+        cloud_sum = UID_Bucket.objects.all().count()
+        pay_0 = Order_Model.objects.filter(status='0').count()
+        pay_1 = Order_Model.objects.filter(status='1').count()
+        money = Order_Model.objects.filter(status='1').aggregate(Sum('price'))
+        data_dict = {
+            "开通云存的设备数": uid_cloud,
+            "已开通云存的各套餐总数": cloud_sum,
+            "未支付的订单数": pay_0,
+            "已支付的订单数": pay_1,
+            "已支付的订单总金额": money['price__sum'],
+        }
+        return response.json(0, data_dict)
+
+    # 每个月开通云存套餐的总数
+    def usercloud(self, userID, response):
+        own_permission = ModelService.check_perm(userID=userID, permID=30)
+        if own_permission is not True:
+            return response.json(404)
+        a = Order_Model.objects.extra(select={'dates': "FROM_UNIXTIME(addTime,'%%Y-%%m')"}).values(
+            'dates').filter(status=1).annotate(开通云存合计=Count('addTime')).order_by('dates')
+        return response.json(0, list(a))
+
+    def equipment_logs(self, userID, request_dict, response):
+        page = int(request_dict.get('page', None))
+        line = int(request_dict.get('line', None))
+        order = request_dict.get('order', '-id')
+        if order == '':
+            order = '-id'
+        if not page or not line:
+            return response.json(444, 'page,line')
+
+        own_perm = ModelService.check_perm(userID=userID, permID=30)
+        if own_perm is not True:
+            return response.json(404)
+
+        if SERVER_TYPE == 'Ansjer.formal_settings':
+            logKey = 'logger'
+        else:
+            logKey = 'test_logger'
+        # 判断redis列表长度
+        redisObj = RedisObject()
+        data_list = redisObj.lrange(logKey, 0, -1)
+        redisObj.del_data(key=logKey)
+        add_batch_log(data_list)
+
+        qs = EquipmentLogModel.objects.all().order_by(order)
+        if qs.exists():
+            count = qs.count()
+            res = qs[(page - 1) * line:page * line]
+            send_json = CommonService.qs_to_dict(res)
+            send_json['count'] = count
+            return response.json(0, send_json)
+        return response.json(0, {'datas': [], 'count': 0})
+
+# 访问日志批量添加
+def add_batch_log(data_list):
+    try:
+        if data_list:
+            querysetlist = []
+            for i in data_list:
+                data = json.loads(i.decode('utf-8'))
+                querysetlist.append(EquipmentLogModel(**data))
+            EquipmentLogModel.objects.bulk_create(querysetlist)
+        else:
+            return
+    except Exception as e:
+        print('ggga')
+        print(repr(e))
+        return False
+    else:
+        return True

+ 226 - 0
Controller/CompanyController.py

@@ -0,0 +1,226 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import logging
+import time
+
+from django.db import transaction
+from django.views import View
+
+from Model.models import CompanyModel, UserModel, SerialNumberModel, CompanySerialModel
+from Object.uidManageResponseObject import uidManageResponseObject
+from Object.TokenObject import TokenObject
+from Service.CommonService import CommonService
+from Service.ModelService import ModelService
+
+
+class CompanyView(View):
+
+    def get(self, request, *arg, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.GET
+        operation = kwargs.get('operation', None)
+        return self.validate(request_dict, operation)
+
+    def post(self, request, *arg, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.POST
+        operation = kwargs.get('operation', None)
+        return self.validate(request_dict, operation)
+
+    def validate(self, request_dict, operation):
+
+        token = TokenObject(request_dict.get('token', None))
+
+        response = uidManageResponseObject()
+
+        if token.code != 0:
+            return response.json(token.code)
+
+        if operation == 'create':
+            return self.do_create(token.userID, request_dict, response)
+        elif operation == 'update':
+            return self.do_update(token.userID, request_dict, response)
+        elif operation == 'delete':
+            return self.do_delete(token.userID, request_dict, response)
+        elif operation == 'list':
+            return self.do_list(token.userID, request_dict, response)
+        elif operation == 'createSerial':
+            return self.do_create_serial(token.userID, request_dict, response)
+        else:
+            return response.json(404)
+
+    def do_create(self, userID, request_dict, response):
+
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        name = request_dict.get('name', None)
+        mark = request_dict.get('mark', None)
+
+        if name and mark:
+            now_time = int(time.time())
+            company_qs = CompanyModel.objects.filter(mark=mark)
+            if company_qs.exists():
+                return response.json(174)
+
+            secret = self.create_secret(mark)
+            print(secret)
+
+            company = CompanyModel(
+                name=name,
+                mark=mark,
+                secret=secret,
+                quantity=0,
+                add_time=now_time,
+                update_time=now_time
+            )
+            company.save()
+            return response.json(0)
+        else:
+            return response.json(444)
+
+    def do_update(self, userID, request_dict, response):
+
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        id = request_dict.get('id', None)
+
+        if id:
+            name = request_dict.get('name', None)
+            quantity = request_dict.get('quantity', None)
+
+            update = {}
+
+            if name:
+                update['name'] = name
+
+            if quantity:
+                update['quantity'] = quantity
+
+            company_qs = CompanyModel.objects.filter(id=id)
+            if company_qs.exists():
+                company_qs.update(**update)
+                return response.json(0)
+            else:
+                return response.json(173)
+
+        else:
+            return response.json(444)
+
+    def do_delete(self, userID, request_dict, response):
+
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        id = request_dict.get('id', None)
+
+        if id:
+            CompanyModel.objects.filter(id=id).delete()
+            return response.json(0)
+        else:
+            return response.json(444)
+
+    @transaction.atomic
+    def do_create_serial(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        id = request_dict.get('id', None)
+        quantity = request_dict.get('quantity', None)
+        p2p = request_dict.get('p2p', None)
+        if id and quantity:
+            company_qs = CompanyModel.objects.filter(id=id)
+
+            if not company_qs.exists():
+                return response.json(444)
+
+            savePoint = transaction.savepoint()
+            try:
+                try:
+
+                    company = company_qs[0]
+                    start = company.quantity
+                    end = start + int(quantity)
+                    serial_qs = SerialNumberModel.objects.filter(p2p=p2p)[start:end]
+                    if serial_qs.exists():
+                        data = []
+                        now_time = int(time.time())
+                        for item in serial_qs:
+                            data.append(CompanySerialModel(
+                                company_id=company.id,
+                                serial_number_id=item.id,
+                                add_time=now_time,
+                                update_time=now_time
+                            ))
+
+                            if len(data) == 5000:
+                                CompanySerialModel.objects.bulk_create(data)
+                                data.clear()
+                        if len(data) > 0:
+                            CompanySerialModel.objects.bulk_create(data)
+                            data.clear()
+
+                        company.quantity = company.quantity + end - start
+                        company.save()
+                        return response.json(0)
+                    else:
+                        return response.json(173)
+                except Exception as e:
+                    # print('--------------------------error 5000')
+                    # print(repr(e))
+                    if savePoint:
+                        transaction.rollback(savePoint)
+                    djangoLogger = logging.getLogger('django')
+                    djangoLogger.exception(repr(e))
+                    return response.json(176, str(e))
+            except Exception as e:
+                # print('--------------------------error 5001')
+                # print(repr(e))
+                djangoLogger = logging.getLogger('django')
+                djangoLogger.exception(repr(e))
+                return response.json(176, str(e))
+        else:
+            return response.json(444)
+
+    def do_list(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        page = request_dict.get('page', None)
+        line = request_dict.get('limit', None)
+        if page and line:
+            page = int(page)
+            line = int(line)
+
+            start = (page - 1) * line
+            end = start + line
+
+            company_qs = CompanyModel.objects.filter()
+            count = company_qs.count()
+
+            company_qs = company_qs[start: end].values()
+            print(company_qs)
+
+            res = {
+                'count': count,
+                'data': list(company_qs)
+            }
+            return response.json(0, res)
+        else:
+            return response.json(444)
+
+    def create_secret(self, mark):
+        len1 = len(mark)
+        secret = ''
+        for i in range(len1):
+            secret += CommonService.RandomStr(randomlength=1)
+            secret += mark[i]
+
+        print(mark)
+        return CommonService.encode_data_without_salt(secret)

+ 371 - 372
Controller/DateController.py

@@ -26,7 +26,6 @@ from Service.CommonService import CommonService
 from Service.ModelService import ModelService
 
 
-
 class DateConView(View):
     @method_decorator(csrf_exempt)
     def dispatch(self, *args, **kwargs):
@@ -51,382 +50,382 @@ class DateConView(View):
         else:
             return response.json(414)
 
-    def do_date(self, request_dict,response):
+    def do_date(self, request_dict, response):
         h = request_dict.get('h', None)
         day = [
-        {"dayStr": "20200101", "type": "2"},
-        {"dayStr": "20200102", "type": "0"},
-        {"dayStr": "20200103", "type": "0"},
-        {"dayStr": "20200104", "type": "1"},
-        {"dayStr": "20200105", "type": "1"},
-        {"dayStr": "20200106", "type": "0"},
-        {"dayStr": "20200107", "type": "0"},
-        {"dayStr": "20200108", "type": "0"},
-        {"dayStr": "20200109", "type": "0"},
-        {"dayStr": "20200110", "type": "0"},
-        {"dayStr": "20200111", "type": "1"},
-        {"dayStr": "20200112", "type": "1"},
-        {"dayStr": "20200113", "type": "0"},
-        {"dayStr": "20200114", "type": "0"},
-        {"dayStr": "20200115", "type": "0"},
-        {"dayStr": "20200116", "type": "0"},
-        {"dayStr": "20200117", "type": "0"},
-        {"dayStr": "20200118", "type": "1"},
-        {"dayStr": "20200119", "type": "0"},
-        {"dayStr": "20200120", "type": "0"},
-        {"dayStr": "20200121", "type": "0"},
-        {"dayStr": "20200122", "type": "0"},
-        {"dayStr": "20200123", "type": "0"},
-        {"dayStr": "20200124", "type": "2"},
-        {"dayStr": "20200125", "type": "2"},
-        {"dayStr": "20200126", "type": "2"},
-        {"dayStr": "20200127", "type": "2"},
-        {"dayStr": "20200128", "type": "2"},
-        {"dayStr": "20200129", "type": "2"},
-        {"dayStr": "20200130", "type": "2"},
-        {"dayStr": "20200131", "type": "0"},
-        {"dayStr": "20200201", "type": "0"},
-        {"dayStr": "20200202", "type": "1"},
-        {"dayStr": "20200203", "type": "0"},
-        {"dayStr": "20200204", "type": "0"},
-        {"dayStr": "20200205", "type": "0"},
-        {"dayStr": "20200206", "type": "0"},
-        {"dayStr": "20200207", "type": "0"},
-        {"dayStr": "20200208", "type": "1"},
-        {"dayStr": "20200209", "type": "1"},
-        {"dayStr": "20200210", "type": "0"},
-        {"dayStr": "20200211", "type": "0"},
-        {"dayStr": "20200212", "type": "0"},
-        {"dayStr": "20200213", "type": "0"},
-        {"dayStr": "20200214", "type": "0"},
-        {"dayStr": "20200215", "type": "1"},
-        {"dayStr": "20200216", "type": "1"},
-        {"dayStr": "20200217", "type": "0"},
-        {"dayStr": "20200218", "type": "0"},
-        {"dayStr": "20200219", "type": "0"},
-        {"dayStr": "20200220", "type": "0"},
-        {"dayStr": "20200221", "type": "0"},
-        {"dayStr": "20200222", "type": "1"},
-        {"dayStr": "20200223", "type": "1"},
-        {"dayStr": "20200224", "type": "0"},
-        {"dayStr": "20200225", "type": "0"},
-        {"dayStr": "20200226", "type": "0"},
-        {"dayStr": "20200227", "type": "0"},
-        {"dayStr": "20200228", "type": "0"},
-        {"dayStr": "20200229", "type": "1"},
-        {"dayStr": "20200301", "type": "1"},
-        {"dayStr": "20200302", "type": "0"},
-        {"dayStr": "20200303", "type": "0"},
-        {"dayStr": "20200304", "type": "0"},
-        {"dayStr": "20200305", "type": "0"},
-        {"dayStr": "20200306", "type": "0"},
-        {"dayStr": "20200307", "type": "1"},
-        {"dayStr": "20200308", "type": "1"},
-        {"dayStr": "20200309", "type": "0"},
-        {"dayStr": "20200310", "type": "0"},
-        {"dayStr": "20200311", "type": "0"},
-        {"dayStr": "20200312", "type": "0"},
-        {"dayStr": "20200313", "type": "0"},
-        {"dayStr": "20200314", "type": "1"},
-        {"dayStr": "20200315", "type": "1"},
-        {"dayStr": "20200316", "type": "0"},
-        {"dayStr": "20200317", "type": "0"},
-        {"dayStr": "20200318", "type": "0"},
-        {"dayStr": "20200319", "type": "0"},
-        {"dayStr": "20200320", "type": "0"},
-        {"dayStr": "20200321", "type": "1"},
-        {"dayStr": "20200322", "type": "1"},
-        {"dayStr": "20200323", "type": "0"},
-        {"dayStr": "20200324", "type": "0"},
-        {"dayStr": "20200325", "type": "0"},
-        {"dayStr": "20200326", "type": "0"},
-        {"dayStr": "20200327", "type": "0"},
-        {"dayStr": "20200328", "type": "1"},
-        {"dayStr": "20200329", "type": "1"},
-        {"dayStr": "20200330", "type": "0"},
-        {"dayStr": "20200331", "type": "0"},
-        {"dayStr": "20200401", "type": "0"},
-        {"dayStr": "20200402", "type": "0"},
-        {"dayStr": "20200403", "type": "0"},
-        {"dayStr": "20200404", "type": "2"},
-        {"dayStr": "20200405", "type": "2"},
-        {"dayStr": "20200406", "type": "2"},
-        {"dayStr": "20200407", "type": "0"},
-        {"dayStr": "20200408", "type": "0"},
-        {"dayStr": "20200409", "type": "0"},
-        {"dayStr": "20200410", "type": "0"},
-        {"dayStr": "20200411", "type": "1"},
-        {"dayStr": "20200412", "type": "1"},
-        {"dayStr": "20200413", "type": "0"},
-        {"dayStr": "20200414", "type": "0"},
-        {"dayStr": "20200415", "type": "0"},
-        {"dayStr": "20200416", "type": "0"},
-        {"dayStr": "20200417", "type": "0"},
-        {"dayStr": "20200418", "type": "1"},
-        {"dayStr": "20200419", "type": "1"},
-        {"dayStr": "20200420", "type": "0"},
-        {"dayStr": "20200421", "type": "0"},
-        {"dayStr": "20200422", "type": "0"},
-        {"dayStr": "20200423", "type": "0"},
-        {"dayStr": "20200424", "type": "0"},
-        {"dayStr": "20200425", "type": "1"},
-        {"dayStr": "20200426", "type": "0"},
-        {"dayStr": "20200427", "type": "0"},
-        {"dayStr": "20200428", "type": "0"},
-        {"dayStr": "20200429", "type": "0"},
-        {"dayStr": "20200430", "type": "0"},
-        {"dayStr": "20200501", "type": "2"},
-        {"dayStr": "20200502", "type": "2"},
-        {"dayStr": "20200503", "type": "2"},
-        {"dayStr": "20200504", "type": "2"},
-        {"dayStr": "20200505", "type": "2"},
-        {"dayStr": "20200506", "type": "0"},
-        {"dayStr": "20200507", "type": "0"},
-        {"dayStr": "20200508", "type": "0"},
-        {"dayStr": "20200509", "type": "0"},
-        {"dayStr": "20200510", "type": "1"},
-        {"dayStr": "20200511", "type": "0"},
-        {"dayStr": "20200512", "type": "0"},
-        {"dayStr": "20200513", "type": "0"},
-        {"dayStr": "20200514", "type": "0"},
-        {"dayStr": "20200515", "type": "0"},
-        {"dayStr": "20200516", "type": "1"},
-        {"dayStr": "20200517", "type": "1"},
-        {"dayStr": "20200518", "type": "0"},
-        {"dayStr": "20200519", "type": "0"},
-        {"dayStr": "20200520", "type": "0"},
-        {"dayStr": "20200521", "type": "0"},
-        {"dayStr": "20200522", "type": "0"},
-        {"dayStr": "20200523", "type": "1"},
-        {"dayStr": "20200524", "type": "1"},
-        {"dayStr": "20200525", "type": "0"},
-        {"dayStr": "20200526", "type": "0"},
-        {"dayStr": "20200527", "type": "0"},
-        {"dayStr": "20200528", "type": "0"},
-        {"dayStr": "20200529", "type": "0"},
-        {"dayStr": "20200530", "type": "1"},
-        {"dayStr": "20200531", "type": "1"},
-        {"dayStr": "20200601", "type": "0"},
-        {"dayStr": "20200602", "type": "0"},
-        {"dayStr": "20200603", "type": "0"},
-        {"dayStr": "20200604", "type": "0"},
-        {"dayStr": "20200605", "type": "0"},
-        {"dayStr": "20200606", "type": "1"},
-        {"dayStr": "20200607", "type": "1"},
-        {"dayStr": "20200608", "type": "0"},
-        {"dayStr": "20200609", "type": "0"},
-        {"dayStr": "20200610", "type": "0"},
-        {"dayStr": "20200611", "type": "0"},
-        {"dayStr": "20200612", "type": "0"},
-        {"dayStr": "20200613", "type": "1"},
-        {"dayStr": "20200614", "type": "1"},
-        {"dayStr": "20200615", "type": "0"},
-        {"dayStr": "20200616", "type": "0"},
-        {"dayStr": "20200617", "type": "0"},
-        {"dayStr": "20200618", "type": "0"},
-        {"dayStr": "20200619", "type": "0"},
-        {"dayStr": "20200620", "type": "1"},
-        {"dayStr": "20200621", "type": "1"},
-        {"dayStr": "20200622", "type": "0"},
-        {"dayStr": "20200623", "type": "0"},
-        {"dayStr": "20200624", "type": "0"},
-        {"dayStr": "20200625", "type": "2"},
-        {"dayStr": "20200626", "type": "2"},
-        {"dayStr": "20200627", "type": "2"},
-        {"dayStr": "20200628", "type": "0"},
-        {"dayStr": "20200629", "type": "0"},
-        {"dayStr": "20200630", "type": "0"},
-        {"dayStr": "20200701", "type": "0"},
-        {"dayStr": "20200702", "type": "0"},
-        {"dayStr": "20200703", "type": "0"},
-        {"dayStr": "20200704", "type": "1"},
-        {"dayStr": "20200705", "type": "1"},
-        {"dayStr": "20200706", "type": "0"},
-        {"dayStr": "20200707", "type": "0"},
-        {"dayStr": "20200708", "type": "0"},
-        {"dayStr": "20200709", "type": "0"},
-        {"dayStr": "20200710", "type": "0"},
-        {"dayStr": "20200711", "type": "1"},
-        {"dayStr": "20200712", "type": "1"},
-        {"dayStr": "20200713", "type": "0"},
-        {"dayStr": "20200714", "type": "0"},
-        {"dayStr": "20200715", "type": "0"},
-        {"dayStr": "20200716", "type": "0"},
-        {"dayStr": "20200717", "type": "0"},
-        {"dayStr": "20200718", "type": "1"},
-        {"dayStr": "20200719", "type": "1"},
-        {"dayStr": "20200720", "type": "0"},
-        {"dayStr": "20200721", "type": "0"},
-        {"dayStr": "20200722", "type": "0"},
-        {"dayStr": "20200723", "type": "0"},
-        {"dayStr": "20200724", "type": "0"},
-        {"dayStr": "20200725", "type": "1"},
-        {"dayStr": "20200726", "type": "1"},
-        {"dayStr": "20200727", "type": "0"},
-        {"dayStr": "20200728", "type": "0"},
-        {"dayStr": "20200729", "type": "0"},
-        {"dayStr": "20200730", "type": "0"},
-        {"dayStr": "20200731", "type": "0"},
-        {"dayStr": "20200801", "type": "1"},
-        {"dayStr": "20200802", "type": "1"},
-        {"dayStr": "20200803", "type": "0"},
-        {"dayStr": "20200804", "type": "0"},
-        {"dayStr": "20200805", "type": "0"},
-        {"dayStr": "20200806", "type": "0"},
-        {"dayStr": "20200807", "type": "0"},
-        {"dayStr": "20200808", "type": "1"},
-        {"dayStr": "20200809", "type": "1"},
-        {"dayStr": "20200810", "type": "0"},
-        {"dayStr": "20200811", "type": "0"},
-        {"dayStr": "20200812", "type": "0"},
-        {"dayStr": "20200813", "type": "0"},
-        {"dayStr": "20200814", "type": "0"},
-        {"dayStr": "20200815", "type": "1"},
-        {"dayStr": "20200816", "type": "1"},
-        {"dayStr": "20200817", "type": "0"},
-        {"dayStr": "20200818", "type": "0"},
-        {"dayStr": "20200819", "type": "0"},
-        {"dayStr": "20200820", "type": "0"},
-        {"dayStr": "20200821", "type": "0"},
-        {"dayStr": "20200822", "type": "1"},
-        {"dayStr": "20200823", "type": "1"},
-        {"dayStr": "20200824", "type": "0"},
-        {"dayStr": "20200825", "type": "0"},
-        {"dayStr": "20200826", "type": "0"},
-        {"dayStr": "20200827", "type": "0"},
-        {"dayStr": "20200828", "type": "0"},
-        {"dayStr": "20200829", "type": "1"},
-        {"dayStr": "20200830", "type": "1"},
-        {"dayStr": "20200831", "type": "0"},
-        {"dayStr": "20200901", "type": "0"},
-        {"dayStr": "20200902", "type": "0"},
-        {"dayStr": "20200903", "type": "0"},
-        {"dayStr": "20200904", "type": "0"},
-        {"dayStr": "20200905", "type": "1"},
-        {"dayStr": "20200906", "type": "1"},
-        {"dayStr": "20200907", "type": "0"},
-        {"dayStr": "20200908", "type": "0"},
-        {"dayStr": "20200909", "type": "0"},
-        {"dayStr": "20200910", "type": "0"},
-        {"dayStr": "20200911", "type": "0"},
-        {"dayStr": "20200912", "type": "1"},
-        {"dayStr": "20200913", "type": "1"},
-        {"dayStr": "20200914", "type": "0"},
-        {"dayStr": "20200915", "type": "0"},
-        {"dayStr": "20200916", "type": "0"},
-        {"dayStr": "20200917", "type": "0"},
-        {"dayStr": "20200918", "type": "0"},
-        {"dayStr": "20200919", "type": "1"},
-        {"dayStr": "20200920", "type": "1"},
-        {"dayStr": "20200921", "type": "0"},
-        {"dayStr": "20200922", "type": "0"},
-        {"dayStr": "20200923", "type": "0"},
-        {"dayStr": "20200924", "type": "0"},
-        {"dayStr": "20200925", "type": "0"},
-        {"dayStr": "20200926", "type": "1"},
-        {"dayStr": "20200927", "type": "0"},
-        {"dayStr": "20200928", "type": "0"},
-        {"dayStr": "20200929", "type": "0"},
-        {"dayStr": "20200930", "type": "0"},
-        {"dayStr": "20201001", "type": "2"},
-        {"dayStr": "20201002", "type": "2"},
-        {"dayStr": "20201003", "type": "2"},
-        {"dayStr": "20201004", "type": "2"},
-        {"dayStr": "20201005", "type": "2"},
-        {"dayStr": "20201006", "type": "2"},
-        {"dayStr": "20201007", "type": "2"},
-        {"dayStr": "20201008", "type": "2"},
-        {"dayStr": "20201009", "type": "0"},
-        {"dayStr": "20201010", "type": "0"},
-        {"dayStr": "20201011", "type": "1"},
-        {"dayStr": "20201012", "type": "0"},
-        {"dayStr": "20201013", "type": "0"},
-        {"dayStr": "20201014", "type": "0"},
-        {"dayStr": "20201015", "type": "0"},
-        {"dayStr": "20201016", "type": "0"},
-        {"dayStr": "20201017", "type": "1"},
-        {"dayStr": "20201018", "type": "1"},
-        {"dayStr": "20201019", "type": "0"},
-        {"dayStr": "20201020", "type": "0"},
-        {"dayStr": "20201021", "type": "0"},
-        {"dayStr": "20201022", "type": "0"},
-        {"dayStr": "20201023", "type": "0"},
-        {"dayStr": "20201024", "type": "1"},
-        {"dayStr": "20201025", "type": "1"},
-        {"dayStr": "20201026", "type": "0"},
-        {"dayStr": "20201027", "type": "0"},
-        {"dayStr": "20201028", "type": "0"},
-        {"dayStr": "20201029", "type": "0"},
-        {"dayStr": "20201030", "type": "0"},
-        {"dayStr": "20201031", "type": "1"},
-        {"dayStr": "20201101", "type": "1"},
-        {"dayStr": "20201102", "type": "0"},
-        {"dayStr": "20201103", "type": "0"},
-        {"dayStr": "20201104", "type": "0"},
-        {"dayStr": "20201105", "type": "0"},
-        {"dayStr": "20201106", "type": "0"},
-        {"dayStr": "20201107", "type": "1"},
-        {"dayStr": "20201108", "type": "1"},
-        {"dayStr": "20201109", "type": "0"},
-        {"dayStr": "20201110", "type": "0"},
-        {"dayStr": "20201111", "type": "0"},
-        {"dayStr": "20201112", "type": "0"},
-        {"dayStr": "20201113", "type": "0"},
-        {"dayStr": "20201114", "type": "1"},
-        {"dayStr": "20201115", "type": "1"},
-        {"dayStr": "20201116", "type": "0"},
-        {"dayStr": "20201117", "type": "0"},
-        {"dayStr": "20201118", "type": "0"},
-        {"dayStr": "20201119", "type": "0"},
-        {"dayStr": "20201120", "type": "0"},
-        {"dayStr": "20201121", "type": "1"},
-        {"dayStr": "20201122", "type": "1"},
-        {"dayStr": "20201123", "type": "0"},
-        {"dayStr": "20201124", "type": "0"},
-        {"dayStr": "20201125", "type": "0"},
-        {"dayStr": "20201126", "type": "0"},
-        {"dayStr": "20201127", "type": "0"},
-        {"dayStr": "20201128", "type": "1"},
-        {"dayStr": "20201129", "type": "1"},
-        {"dayStr": "20201130", "type": "0"},
-        {"dayStr": "20201201", "type": "0"},
-        {"dayStr": "20201202", "type": "0"},
-        {"dayStr": "20201203", "type": "0"},
-        {"dayStr": "20201204", "type": "0"},
-        {"dayStr": "20201205", "type": "1"},
-        {"dayStr": "20201206", "type": "1"},
-        {"dayStr": "20201207", "type": "0"},
-        {"dayStr": "20201208", "type": "0"},
-        {"dayStr": "20201209", "type": "0"},
-        {"dayStr": "20201210", "type": "0"},
-        {"dayStr": "20201211", "type": "0"},
-        {"dayStr": "20201212", "type": "1"},
-        {"dayStr": "20201213", "type": "1"},
-        {"dayStr": "20201214", "type": "0"},
-        {"dayStr": "20201215", "type": "0"},
-        {"dayStr": "20201216", "type": "0"},
-        {"dayStr": "20201217", "type": "0"},
-        {"dayStr": "20201218", "type": "0"},
-        {"dayStr": "20201219", "type": "1"},
-        {"dayStr": "20201220", "type": "1"},
-        {"dayStr": "20201221", "type": "0"},
-        {"dayStr": "20201222", "type": "0"},
-        {"dayStr": "20201223", "type": "0"},
-        {"dayStr": "20201224", "type": "0"},
-        {"dayStr": "20201225", "type": "0"},
-        {"dayStr": "20201226", "type": "1"},
-        {"dayStr": "20201227", "type": "1"},
-        {"dayStr": "20201228", "type": "0"},
-        {"dayStr": "20201229", "type": "0"},
-        {"dayStr": "20201230", "type": "0"},
-        {"dayStr": "20201231", "type": "0"}
+            {"dayStr": "20210101", "type": "2"},
+            {"dayStr": "20210102", "type": "2"},
+            {"dayStr": "20210103", "type": "2"},
+            {"dayStr": "20210104", "type": "0"},
+            {"dayStr": "20210105", "type": "0"},
+            {"dayStr": "20210106", "type": "0"},
+            {"dayStr": "20210107", "type": "0"},
+            {"dayStr": "20210108", "type": "0"},
+            {"dayStr": "20210109", "type": "1"},
+            {"dayStr": "20210110", "type": "1"},
+            {"dayStr": "20210111", "type": "0"},
+            {"dayStr": "20210112", "type": "0"},
+            {"dayStr": "20210113", "type": "0"},
+            {"dayStr": "20210114", "type": "0"},
+            {"dayStr": "20210115", "type": "0"},
+            {"dayStr": "20210116", "type": "1"},
+            {"dayStr": "20210117", "type": "1"},
+            {"dayStr": "20210118", "type": "0"},
+            {"dayStr": "20210119", "type": "0"},
+            {"dayStr": "20210120", "type": "0"},
+            {"dayStr": "20210121", "type": "0"},
+            {"dayStr": "20210122", "type": "0"},
+            {"dayStr": "20210123", "type": "1"},
+            {"dayStr": "20210124", "type": "1"},
+            {"dayStr": "20210125", "type": "0"},
+            {"dayStr": "20210126", "type": "0"},
+            {"dayStr": "20210127", "type": "0"},
+            {"dayStr": "20210128", "type": "0"},
+            {"dayStr": "20210129", "type": "0"},
+            {"dayStr": "20210130", "type": "1"},
+            {"dayStr": "20210131", "type": "1"},
+            {"dayStr": "20210201", "type": "0"},
+            {"dayStr": "20210202", "type": "0"},
+            {"dayStr": "20210203", "type": "0"},
+            {"dayStr": "20210204", "type": "0"},
+            {"dayStr": "20210205", "type": "0"},
+            {"dayStr": "20210206", "type": "1"},
+            {"dayStr": "20210207", "type": "0"},
+            {"dayStr": "20210208", "type": "0"},
+            {"dayStr": "20210209", "type": "0"},
+            {"dayStr": "20210210", "type": "0"},
+            {"dayStr": "20210211", "type": "2"},
+            {"dayStr": "20210212", "type": "2"},
+            {"dayStr": "20210213", "type": "2"},
+            {"dayStr": "20210214", "type": "2"},
+            {"dayStr": "20210215", "type": "2"},
+            {"dayStr": "20210216", "type": "2"},
+            {"dayStr": "20210217", "type": "2"},
+            {"dayStr": "20210218", "type": "0"},
+            {"dayStr": "20210219", "type": "0"},
+            {"dayStr": "20210220", "type": "0"},
+            {"dayStr": "20210221", "type": "1"},
+            {"dayStr": "20210222", "type": "0"},
+            {"dayStr": "20210223", "type": "0"},
+            {"dayStr": "20210224", "type": "0"},
+            {"dayStr": "20210225", "type": "0"},
+            {"dayStr": "20210226", "type": "0"},
+            {"dayStr": "20210227", "type": "1"},
+            {"dayStr": "20210228", "type": "1"},
+            {"dayStr": "20210229", "type": "0"},
+            {"dayStr": "20210301", "type": "0"},
+            {"dayStr": "20210302", "type": "0"},
+            {"dayStr": "20210303", "type": "0"},
+            {"dayStr": "20210304", "type": "0"},
+            {"dayStr": "20210305", "type": "0"},
+            {"dayStr": "20210306", "type": "1"},
+            {"dayStr": "20210307", "type": "1"},
+            {"dayStr": "20210308", "type": "0"},
+            {"dayStr": "20210309", "type": "0"},
+            {"dayStr": "20210310", "type": "0"},
+            {"dayStr": "20210311", "type": "0"},
+            {"dayStr": "20210312", "type": "0"},
+            {"dayStr": "20210313", "type": "1"},
+            {"dayStr": "20210314", "type": "1"},
+            {"dayStr": "20210315", "type": "0"},
+            {"dayStr": "20210316", "type": "0"},
+            {"dayStr": "20210317", "type": "0"},
+            {"dayStr": "20210318", "type": "0"},
+            {"dayStr": "20210319", "type": "0"},
+            {"dayStr": "20210320", "type": "1"},
+            {"dayStr": "20210321", "type": "1"},
+            {"dayStr": "20210322", "type": "0"},
+            {"dayStr": "20210323", "type": "0"},
+            {"dayStr": "20210324", "type": "0"},
+            {"dayStr": "20210325", "type": "0"},
+            {"dayStr": "20210326", "type": "0"},
+            {"dayStr": "20210327", "type": "1"},
+            {"dayStr": "20210328", "type": "1"},
+            {"dayStr": "20210329", "type": "0"},
+            {"dayStr": "20210330", "type": "0"},
+            {"dayStr": "20210331", "type": "0"},
+            {"dayStr": "20210401", "type": "0"},
+            {"dayStr": "20210402", "type": "0"},
+            {"dayStr": "20210403", "type": "2"},
+            {"dayStr": "20210404", "type": "2"},
+            {"dayStr": "20210405", "type": "2"},
+            {"dayStr": "20210406", "type": "0"},
+            {"dayStr": "20210407", "type": "0"},
+            {"dayStr": "20210408", "type": "0"},
+            {"dayStr": "20210409", "type": "0"},
+            {"dayStr": "20210410", "type": "1"},
+            {"dayStr": "20210411", "type": "1"},
+            {"dayStr": "20210412", "type": "0"},
+            {"dayStr": "20210413", "type": "0"},
+            {"dayStr": "20210414", "type": "0"},
+            {"dayStr": "20210415", "type": "0"},
+            {"dayStr": "20210416", "type": "0"},
+            {"dayStr": "20210417", "type": "1"},
+            {"dayStr": "20210418", "type": "1"},
+            {"dayStr": "20210419", "type": "0"},
+            {"dayStr": "20210420", "type": "0"},
+            {"dayStr": "20210421", "type": "0"},
+            {"dayStr": "20210422", "type": "0"},
+            {"dayStr": "20210423", "type": "0"},
+            {"dayStr": "20210424", "type": "1"},
+            {"dayStr": "20210425", "type": "0"},
+            {"dayStr": "20210426", "type": "0"},
+            {"dayStr": "20210427", "type": "0"},
+            {"dayStr": "20210428", "type": "0"},
+            {"dayStr": "20210429", "type": "0"},
+            {"dayStr": "20210430", "type": "0"},
+            {"dayStr": "20210501", "type": "2"},
+            {"dayStr": "20210502", "type": "2"},
+            {"dayStr": "20210503", "type": "2"},
+            {"dayStr": "20210504", "type": "2"},
+            {"dayStr": "20210505", "type": "2"},
+            {"dayStr": "20210506", "type": "0"},
+            {"dayStr": "20210507", "type": "0"},
+            {"dayStr": "20210508", "type": "0"},
+            {"dayStr": "20210509", "type": "1"},
+            {"dayStr": "20210510", "type": "0"},
+            {"dayStr": "20210511", "type": "0"},
+            {"dayStr": "20210512", "type": "0"},
+            {"dayStr": "20210513", "type": "0"},
+            {"dayStr": "20210514", "type": "0"},
+            {"dayStr": "20210515", "type": "1"},
+            {"dayStr": "20210516", "type": "1"},
+            {"dayStr": "20210517", "type": "0"},
+            {"dayStr": "20210518", "type": "0"},
+            {"dayStr": "20210519", "type": "0"},
+            {"dayStr": "20210520", "type": "0"},
+            {"dayStr": "20210521", "type": "0"},
+            {"dayStr": "20210522", "type": "1"},
+            {"dayStr": "20210523", "type": "1"},
+            {"dayStr": "20210524", "type": "0"},
+            {"dayStr": "20210525", "type": "0"},
+            {"dayStr": "20210526", "type": "0"},
+            {"dayStr": "20210527", "type": "0"},
+            {"dayStr": "20210528", "type": "0"},
+            {"dayStr": "20210529", "type": "1"},
+            {"dayStr": "20210530", "type": "1"},
+            {"dayStr": "20210531", "type": "0"},
+            {"dayStr": "20210601", "type": "0"},
+            {"dayStr": "20210602", "type": "0"},
+            {"dayStr": "20210603", "type": "0"},
+            {"dayStr": "20210604", "type": "0"},
+            {"dayStr": "20210605", "type": "1"},
+            {"dayStr": "20210606", "type": "1"},
+            {"dayStr": "20210607", "type": "0"},
+            {"dayStr": "20210608", "type": "0"},
+            {"dayStr": "20210609", "type": "0"},
+            {"dayStr": "20210610", "type": "0"},
+            {"dayStr": "20210611", "type": "0"},
+            {"dayStr": "20210612", "type": "2"},
+            {"dayStr": "20210613", "type": "2"},
+            {"dayStr": "20210614", "type": "2"},
+            {"dayStr": "20210615", "type": "0"},
+            {"dayStr": "20210616", "type": "0"},
+            {"dayStr": "20210617", "type": "0"},
+            {"dayStr": "20210618", "type": "0"},
+            {"dayStr": "20210619", "type": "1"},
+            {"dayStr": "20210620", "type": "1"},
+            {"dayStr": "20210621", "type": "0"},
+            {"dayStr": "20210622", "type": "0"},
+            {"dayStr": "20210623", "type": "0"},
+            {"dayStr": "20210624", "type": "0"},
+            {"dayStr": "20210625", "type": "0"},
+            {"dayStr": "20210626", "type": "1"},
+            {"dayStr": "20210627", "type": "1"},
+            {"dayStr": "20210628", "type": "0"},
+            {"dayStr": "20210629", "type": "0"},
+            {"dayStr": "20210630", "type": "0"},
+            {"dayStr": "20210701", "type": "0"},
+            {"dayStr": "20210702", "type": "0"},
+            {"dayStr": "20210703", "type": "1"},
+            {"dayStr": "20210704", "type": "1"},
+            {"dayStr": "20210705", "type": "0"},
+            {"dayStr": "20210706", "type": "0"},
+            {"dayStr": "20210707", "type": "0"},
+            {"dayStr": "20210708", "type": "0"},
+            {"dayStr": "20210709", "type": "0"},
+            {"dayStr": "20210710", "type": "1"},
+            {"dayStr": "20210711", "type": "1"},
+            {"dayStr": "20210712", "type": "0"},
+            {"dayStr": "20210713", "type": "0"},
+            {"dayStr": "20210714", "type": "0"},
+            {"dayStr": "20210715", "type": "0"},
+            {"dayStr": "20210716", "type": "0"},
+            {"dayStr": "20210717", "type": "1"},
+            {"dayStr": "20210718", "type": "1"},
+            {"dayStr": "20210719", "type": "0"},
+            {"dayStr": "20210720", "type": "0"},
+            {"dayStr": "20210721", "type": "0"},
+            {"dayStr": "20210722", "type": "0"},
+            {"dayStr": "20210723", "type": "0"},
+            {"dayStr": "20210724", "type": "1"},
+            {"dayStr": "20210725", "type": "1"},
+            {"dayStr": "20210726", "type": "0"},
+            {"dayStr": "20210727", "type": "0"},
+            {"dayStr": "20210728", "type": "0"},
+            {"dayStr": "20210729", "type": "0"},
+            {"dayStr": "20210730", "type": "0"},
+            {"dayStr": "20210731", "type": "1"},
+            {"dayStr": "20210801", "type": "1"},
+            {"dayStr": "20210802", "type": "0"},
+            {"dayStr": "20210803", "type": "0"},
+            {"dayStr": "20210804", "type": "0"},
+            {"dayStr": "20210805", "type": "0"},
+            {"dayStr": "20210806", "type": "0"},
+            {"dayStr": "20210807", "type": "1"},
+            {"dayStr": "20210808", "type": "1"},
+            {"dayStr": "20210809", "type": "0"},
+            {"dayStr": "20210810", "type": "0"},
+            {"dayStr": "20210811", "type": "0"},
+            {"dayStr": "20210812", "type": "0"},
+            {"dayStr": "20210813", "type": "0"},
+            {"dayStr": "20210814", "type": "1"},
+            {"dayStr": "20210815", "type": "1"},
+            {"dayStr": "20210816", "type": "0"},
+            {"dayStr": "20210817", "type": "0"},
+            {"dayStr": "20210818", "type": "0"},
+            {"dayStr": "20210819", "type": "0"},
+            {"dayStr": "20210820", "type": "0"},
+            {"dayStr": "20210821", "type": "1"},
+            {"dayStr": "20210822", "type": "1"},
+            {"dayStr": "20210823", "type": "0"},
+            {"dayStr": "20210824", "type": "0"},
+            {"dayStr": "20210825", "type": "0"},
+            {"dayStr": "20210826", "type": "0"},
+            {"dayStr": "20210827", "type": "0"},
+            {"dayStr": "20210828", "type": "1"},
+            {"dayStr": "20210829", "type": "1"},
+            {"dayStr": "20210830", "type": "0"},
+            {"dayStr": "20210831", "type": "0"},
+            {"dayStr": "20210901", "type": "0"},
+            {"dayStr": "20210902", "type": "0"},
+            {"dayStr": "20210903", "type": "0"},
+            {"dayStr": "20210904", "type": "1"},
+            {"dayStr": "20210905", "type": "1"},
+            {"dayStr": "20210906", "type": "0"},
+            {"dayStr": "20210907", "type": "0"},
+            {"dayStr": "20210908", "type": "0"},
+            {"dayStr": "20210909", "type": "0"},
+            {"dayStr": "20210910", "type": "0"},
+            {"dayStr": "20210911", "type": "1"},
+            {"dayStr": "20210912", "type": "1"},
+            {"dayStr": "20210913", "type": "0"},
+            {"dayStr": "20210914", "type": "0"},
+            {"dayStr": "20210915", "type": "0"},
+            {"dayStr": "20210916", "type": "0"},
+            {"dayStr": "20210917", "type": "0"},
+            {"dayStr": "20210918", "type": "0"},
+            {"dayStr": "20210919", "type": "2"},
+            {"dayStr": "20210920", "type": "2"},
+            {"dayStr": "20210921", "type": "2"},
+            {"dayStr": "20210922", "type": "0"},
+            {"dayStr": "20210923", "type": "0"},
+            {"dayStr": "20210924", "type": "0"},
+            {"dayStr": "20210925", "type": "1"},
+            {"dayStr": "20210926", "type": "0"},
+            {"dayStr": "20210927", "type": "0"},
+            {"dayStr": "20210928", "type": "0"},
+            {"dayStr": "20210929", "type": "0"},
+            {"dayStr": "20210930", "type": "0"},
+            {"dayStr": "20211001", "type": "2"},
+            {"dayStr": "20211002", "type": "2"},
+            {"dayStr": "20211003", "type": "2"},
+            {"dayStr": "20211004", "type": "2"},
+            {"dayStr": "20211005", "type": "2"},
+            {"dayStr": "20211006", "type": "2"},
+            {"dayStr": "20211007", "type": "2"},
+            {"dayStr": "20211008", "type": "0"},
+            {"dayStr": "20211009", "type": "0"},
+            {"dayStr": "20211010", "type": "1"},
+            {"dayStr": "20211011", "type": "0"},
+            {"dayStr": "20211012", "type": "0"},
+            {"dayStr": "20211013", "type": "0"},
+            {"dayStr": "20211014", "type": "0"},
+            {"dayStr": "20211015", "type": "0"},
+            {"dayStr": "20211016", "type": "1"},
+            {"dayStr": "20211017", "type": "1"},
+            {"dayStr": "20211018", "type": "0"},
+            {"dayStr": "20211019", "type": "0"},
+            {"dayStr": "20211020", "type": "0"},
+            {"dayStr": "20211021", "type": "0"},
+            {"dayStr": "20211022", "type": "0"},
+            {"dayStr": "20211023", "type": "1"},
+            {"dayStr": "20211024", "type": "1"},
+            {"dayStr": "20211025", "type": "0"},
+            {"dayStr": "20211026", "type": "0"},
+            {"dayStr": "20211027", "type": "0"},
+            {"dayStr": "20211028", "type": "0"},
+            {"dayStr": "20211029", "type": "0"},
+            {"dayStr": "20211030", "type": "1"},
+            {"dayStr": "20211031", "type": "1"},
+            {"dayStr": "20211101", "type": "0"},
+            {"dayStr": "20211102", "type": "0"},
+            {"dayStr": "20211103", "type": "0"},
+            {"dayStr": "20211104", "type": "0"},
+            {"dayStr": "20211105", "type": "0"},
+            {"dayStr": "20211106", "type": "1"},
+            {"dayStr": "20211107", "type": "1"},
+            {"dayStr": "20211108", "type": "0"},
+            {"dayStr": "20211109", "type": "0"},
+            {"dayStr": "20211110", "type": "0"},
+            {"dayStr": "20211111", "type": "0"},
+            {"dayStr": "20211112", "type": "0"},
+            {"dayStr": "20211113", "type": "1"},
+            {"dayStr": "20211114", "type": "1"},
+            {"dayStr": "20211115", "type": "0"},
+            {"dayStr": "20211116", "type": "0"},
+            {"dayStr": "20211117", "type": "0"},
+            {"dayStr": "20211118", "type": "0"},
+            {"dayStr": "20211119", "type": "0"},
+            {"dayStr": "20211120", "type": "1"},
+            {"dayStr": "20211121", "type": "1"},
+            {"dayStr": "20211122", "type": "0"},
+            {"dayStr": "20211123", "type": "0"},
+            {"dayStr": "20211124", "type": "0"},
+            {"dayStr": "20211125", "type": "0"},
+            {"dayStr": "20211126", "type": "0"},
+            {"dayStr": "20211127", "type": "1"},
+            {"dayStr": "20211128", "type": "1"},
+            {"dayStr": "20211129", "type": "0"},
+            {"dayStr": "20211130", "type": "0"},
+            {"dayStr": "20211201", "type": "0"},
+            {"dayStr": "20211202", "type": "0"},
+            {"dayStr": "20211203", "type": "0"},
+            {"dayStr": "20211204", "type": "1"},
+            {"dayStr": "20211205", "type": "1"},
+            {"dayStr": "20211206", "type": "0"},
+            {"dayStr": "20211207", "type": "0"},
+            {"dayStr": "20211208", "type": "0"},
+            {"dayStr": "20211209", "type": "0"},
+            {"dayStr": "20211210", "type": "0"},
+            {"dayStr": "20211211", "type": "1"},
+            {"dayStr": "20211212", "type": "1"},
+            {"dayStr": "20211213", "type": "0"},
+            {"dayStr": "20211214", "type": "0"},
+            {"dayStr": "20211215", "type": "0"},
+            {"dayStr": "20211216", "type": "0"},
+            {"dayStr": "20211217", "type": "0"},
+            {"dayStr": "20211218", "type": "1"},
+            {"dayStr": "20211219", "type": "1"},
+            {"dayStr": "20211220", "type": "0"},
+            {"dayStr": "20211221", "type": "0"},
+            {"dayStr": "20211222", "type": "0"},
+            {"dayStr": "20211223", "type": "0"},
+            {"dayStr": "20211224", "type": "0"},
+            {"dayStr": "20211225", "type": "1"},
+            {"dayStr": "20211226", "type": "1"},
+            {"dayStr": "20211227", "type": "0"},
+            {"dayStr": "20211228", "type": "0"},
+            {"dayStr": "20211229", "type": "0"},
+            {"dayStr": "20211230", "type": "0"},
+            {"dayStr": "20211231", "type": "0"}
         ]
 
-        srt=[{"dayStr": h, "type": "该日期不支持,只支持2020年"}]
+        srt = [{"dayStr": h, "type": "该日期不支持,只支持2021年"}]
         for i in day:
-            if i['dayStr']==h:
+            if i['dayStr'] == h:
                 print(i)
-                srt=i
+                srt = i
         print(h)
 
-        return response.json(0,srt)
+        return response.json(0, srt)

+ 1 - 0
Controller/DetectController.py

@@ -30,6 +30,7 @@ from Object.ResponseObject import ResponseObject
 from Object.TokenObject import TokenObject
 from Object.UidTokenObject import UidTokenObject
 from Service.CommonService import CommonService
+from Service.ModelService import ModelService
 
 '''
 http://test.push.dvema.com/notify/push?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJUNEFaM0NVS0NFUkg5RlpBMTExQSJ9.GtrXeq5gb2Z9M3mKECxi9eNQbPxqC-6PtgJkOOg6PwI&n_time=1598456451&channel=1&event_type=1&is_st=1

+ 89 - 0
Controller/DeviceConfirmRegion.py

@@ -0,0 +1,89 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
+@software: PyCharm
+@Version: python3.6
+"""
+import datetime
+import traceback
+import time
+import logging
+import jwt
+import simplejson
+import simplejson as json
+import requests
+from django.contrib.auth.hashers import make_password, check_password  # 对密码加密模块
+from django.db.models import Q
+from django.http import HttpResponseRedirect
+from django.utils.decorators import method_decorator
+from django.utils.timezone import utc
+from django.views.decorators.csrf import csrf_exempt
+from django.views.generic import TemplateView
+from jwt.algorithms import RSAAlgorithm
+from ratelimit.decorators import ratelimit
+
+from Ansjer.config import AuthCode_Expire, SERVER_DOMAIN, APNS_CONFIG, JPUSH_CONFIG, FCM_CONFIG, TUTK_PUSH_DOMAIN
+from Controller.CheckUserData import DataValid, date_handler, RandomStr
+from Model.models import Device_User, Role, UidPushModel, UserOauth2Model, UserExModel, Device_Info, UidSetModel, \
+    UserAppFrequencyModel, CountryIPModel, CountryModel, RegionModel
+from Object.AWS.SesClassObject import SesClassObject
+from Object.AliSmsObject import AliSmsObject
+from Object.RedisObject import RedisObject
+from Object.ResponseObject import ResponseObject
+from Object.TokenObject import TokenObject
+from Service.CommonService import CommonService
+from Service.ModelService import ModelService
+from Service.TemplateService import TemplateService
+from django.views.generic import View
+import base64
+import random
+from io import BytesIO
+from PIL import Image, ImageDraw, ImageFont
+from django.shortcuts import HttpResponse
+from Ansjer.config import BASE_DIR
+
+#确认设备所在地区
+class ConfirmRegion(TemplateView):
+    @method_decorator(csrf_exempt)
+    def dispatch(self, *args, **kwargs):
+        return super(ConfirmRegion, self).dispatch(*args, **kwargs)
+
+    def get(self, request, *args, **kwargs):
+        response = ResponseObject()
+        request.encoding = 'utf-8'
+        # number = request.POST.get('number', None)
+        # selectRegion = CountryModel.objects.filter(number=number).values('region__api_url')
+        # if not selectRegion.exists():
+        #     return response.json(0,{"api_url":"https://test.dvema.com"})
+        # else:
+        #     return response.json(0,{"api_url":selectRegion[0]['region__api_url']})
+
+        # serial_number = request.POST.get('serial_number', None)
+        ip = CommonService.get_ip_address(request)
+        # ip = '14.102.176.0'
+        ipInfo = CommonService.getIpIpInfo(ip,"CN")
+        if ipInfo['country_code']:
+            device_request_url = CountryModel.objects.filter(country_code=ipInfo['country_code']).values("region__api")
+            if device_request_url.exists():
+                return response.json(0,{"request_api_url":device_request_url[0]['region__api']})
+
+        # 不存在默认返回美洲地区api。
+        api = RegionModel.objects.filter(continent_code='NA').values("api")
+        return response.json(0,{"request_api_url":api[0]['api']})
+
+#确认设备所在地区
+class Device_Region(object):
+
+    def get_device_region(self, ip):
+
+        ipInfo = CommonService.getIpIpInfo(ip, "CN")
+        if ipInfo['country_code']:
+            device_request_url = CountryModel.objects.filter(country_code=ipInfo['country_code']).values("region__api","region__id")
+            if device_request_url.exists():
+                return device_request_url[0]['region__id']
+        # 不存在默认返回美洲地区api
+        api = RegionModel.objects.filter(continent_code='NA').values("id")
+        return api[0]['id']
+
+

+ 13 - 0
Controller/EquipmentInfo.py

@@ -84,6 +84,7 @@ class EquipmentInfo(View):
         if not device_info.exists():
             return response.json(14)
         try:
+
             nowTime = int(time.time())
             equipment_info = Equipment_Info(
                 userID_id=userID,
@@ -303,3 +304,15 @@ def deleteExpireEquipmentInfo(request):
     return response.json(0)
 
 
+# 按季度删除访问日志
+def deleteExpireEquipmentInfoById(request):
+    response = ResponseObject()
+    id = int(request.GET.get('id', None))
+
+    if id is None:
+        return response.json(0)
+
+    Equipment_Info.objects.filter(id__lte=id).delete()
+    return response.json(0)
+
+

+ 94 - 18
Controller/EquipmentManager.py

@@ -3,9 +3,12 @@ import time
 import traceback
 import threading
 import logging
+
+import requests
 import simplejson as json
 from django.utils import timezone
-from Model.models import Device_User, Device_Info, UID_Bucket, UID_Preview, UidSetModel, UidPushModel
+from Model.models import Device_User, Device_Info, UID_Bucket, UID_Preview, UidSetModel, UidPushModel, \
+    UIDCompanySerialModel, iotdeviceInfoModel, UIDMainUser
 from django.db.models import Q
 from Object.ResponseObject import ResponseObject
 from Object.TokenObject import TokenObject
@@ -16,6 +19,7 @@ from Object.ETkObject import ETkObject
 import oss2
 from django.http import JsonResponse
 from Object.RedisObject import RedisObject
+from Controller.DetectController import DetectControllerView
 
 
 #     查询用户设备
@@ -160,14 +164,15 @@ def delUserEquipmentInterface(request):
         # redisObj.del_data(key='uid_qs_' + userID)
         if dv_qs.exists():
             uid = dv_qs[0].UID
-            asy = threading.Thread(target=ModelService.delete_log,
-                                   args=(CommonService.get_ip_address(request), userID, 'deleteV1', uid))
+            asy = threading.Thread(target=ModelService.add_log, args=(CommonService.get_ip_address(request), userID, 'deleteV1'))
             asy.start()
+
             print('删除')
             UID_Preview.objects.filter(uid=uid).delete()
             dv_qs.delete()
             asy = threading.Thread(target=ModelService.del_eq_info, args=(userID, uid))
             asy.start()
+
     except Exception as e:
         errorInfo = traceback.format_exc()
         print('删除数据库记录错误: %s' % errorInfo)
@@ -383,10 +388,7 @@ def addInterface(request):
                     asy.start()
                     return response.json(10, 'illegal uid: {uid}'.format(uid=UID))
                 pass
-                # is_bind = Device_Info.objects.filter(UID=UID, isShare=False)
-                # # 判断是否有已绑定用户
-                # if is_bind:
-                #     return response.json(15)
+
                 pk = CommonService.getUserID(getUser=False)
 
 
@@ -403,13 +405,32 @@ def addInterface(request):
                 is_bind = Device_Info.objects.filter(UID=UID, isShare=False).values('userID__userID', 'vodPrimaryUserID')
                 # 判断是否有已绑定用户
                 isvodPrimaryUserID = ''
-
                 for forbind in is_bind:
                     if forbind['vodPrimaryUserID'] != '':
                         isvodPrimaryUserID = forbind['vodPrimaryUserID']
 
+                if isCheckMainUser != '1':
+                    if main_exist.exists():
+                        vodPrimaryUserID = main_exist[0]['vodPrimaryUserID']
+                        vodPrimaryMaster = main_exist[0]['vodPrimaryMaster']
+                    else:
+                        vodPrimaryUserID = ''
+                        vodPrimaryMaster = ''
+
+                isusermain = False
+                if is_bind and isvodPrimaryUserID != userID and isvodPrimaryUserID != '':
+                    isusermain = True
+
+                uid_main_exist = UIDMainUser.objects.filter(UID=UID).values('UID', 'user_id')
+                if uid_main_exist.exists():
+                    vodPrimaryUserID = uid_main_exist[0]['user_id']
+                    vodPrimaryMaster = Device_User.objects.get(userID=vodPrimaryUserID).username
+
+                    if vodPrimaryUserID != userID:
+                        isusermain = True
+
                 # 判断是否有已绑定用户
-                if is_bind and isCheckMainUser == '1' and isvodPrimaryUserID != userID and isvodPrimaryUserID != '':
+                if isCheckMainUser == '1' and isusermain:
                     res = {
                         'id': pk,
                         'userID': userID,
@@ -465,9 +486,23 @@ def addInterface(request):
                                              View_Password=View_Password, Type=Type, ChannelIndex=ChannelIndex,
                                              version=version, vodPrimaryUserID=vodPrimaryUserID, vodPrimaryMaster=vodPrimaryMaster)
                     userDevice.save()
-                    Device_Info.objects.filter(UID=UID).update(vodPrimaryUserID=vodPrimaryUserID,
-                                                               vodPrimaryMaster=vodPrimaryMaster)
-                    # redisObj = RedisObject(db=8)
+                    uid_serial_qs = UIDCompanySerialModel.objects.filter(
+                        uid__uid=UID)
+                    if uid_serial_qs.exists():
+                        uid_serial = uid_serial_qs[0]
+                        Device_Info.objects.filter(UID=UID).update(vodPrimaryUserID=vodPrimaryUserID,
+                                                                   vodPrimaryMaster=vodPrimaryMaster,
+                                                                   serial_number=uid_serial.company_serial.serial_number.serial_number + uid_serial.company_serial.company.mark)
+                    else:
+                        Device_Info.objects.filter(UID=UID).update(vodPrimaryUserID=vodPrimaryUserID,
+                                                                   vodPrimaryMaster=vodPrimaryMaster)
+                    if isCheckMainUser == '1':
+                        uid_main_dict = {
+                            'UID': UID,
+                            'user_id': vodPrimaryUserID
+                        }
+                        UIDMainUser.objects.create(**uid_main_dict)
+                # redisObj = RedisObject(db=8)
                     # redisObj.del_data(key='uid_qs_' + userID)
                 except Exception as e:
                     return response.json(10, repr(e))
@@ -478,12 +513,25 @@ def addInterface(request):
                                                                     'isShare',
                                                                     'primaryUserID', 'primaryMaster', 'vodPrimaryUserID', 'vodPrimaryMaster', 'userID__userEmail',
                                                                     'data_joined', 'version',
-                                                                    'isVod', 'isExist', 'isCameraOpenCloud', 'endpoint', 'token_iot_number')
+                                                                    'isVod', 'isExist', 'isCameraOpenCloud', 'serial_number')
                     dvql = CommonService.qs_to_list(dvqs)
                     ubqs = UID_Bucket.objects.filter(uid=UID). \
                         values('bucket__content', 'status', 'channel', 'endTime', 'uid')
                     res = dvql[0]
                     res['vod'] = list(ubqs)
+
+
+                    # 新增获取IOT证书内容
+                    iotqs = iotdeviceInfoModel.objects.filter(serial_number__serial_number=dvql[0]['serial_number'])
+                    if iotqs.exists():
+                        res['iot'].append(
+                            {
+                                'endpoint': iotqs[0].endpoint,
+                                'token_iot_number': iotqs[0].endpoint
+
+                            }
+                        )
+
                     if isMainUserExists:
                         res['isMainUserExists'] = 1
                     return response.json(0, res)
@@ -753,6 +801,7 @@ def deleteInterface(request):
                 dv_qs.delete()
                 # 删除设备影子信息uid_set   外键关联删除设备推送配置信息 uid_push
                 up_qs = UidPushModel.objects.filter(uid_set__uid=uid)
+                DetectControllerView().do_delete_redis(uid)
                 if up_qs.count() > 1:
                     UidPushModel.objects.filter(uid_set__uid=uid, userID_id=userID).delete()
                     redisObj = RedisObject(db=6, SERVER_HOST='push.dvema.com')
@@ -814,13 +863,22 @@ def queryInterface(request):
         dvql = dvqs[(page - 1) * line:page * line].values('id', 'userID', 'NickName', 'UID', 'View_Account',
                                                           'View_Password', 'ChannelIndex', 'Type', 'isShare',
                                                           'primaryUserID', 'primaryMaster', 'data_joined', 'version', 'vodPrimaryUserID', 'vodPrimaryMaster', 'userID__userEmail',
-                                                          'isVod', 'isExist', 'NotificationMode', 'isCameraOpenCloud', 'endpoint', 'token_iot_number')
+                                                          'isVod', 'isExist', 'NotificationMode', 'isCameraOpenCloud', 'serial_number')
         dvls = CommonService.qs_to_list(dvql)
         uid_list = []
+        serial_number_list = []
         for dvl in dvls:
+            if dvl['primaryUserID'] and dvl['id'] == dvl['primaryUserID']:
+                dvl['isPrimaryUser'] = 1
+            else:
+                dvl['isPrimaryUser'] = 0
             uid_list.append(dvl['UID'])
-            # if dvl['isShare'] is False:
-            #     uid_list.append(dvl['UID'])
+            serial_number_list.append(dvl['serial_number'][0:6])
+
+
+        #新增获取IOT证书内容
+        iotqs = iotdeviceInfoModel.objects.filter(serial_number__serial_number__in=serial_number_list)
+
         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')
@@ -836,7 +894,20 @@ def queryInterface(request):
             uv_dict[us['uid']] = {'version': us['version'],
                                   'nickname': us['nickname'],
                                   'detect_interval': us['detect_interval']}
+
         for p in dvls:
+            #新增IOT
+            p['iot'] = []
+            for iot in iotqs:
+                if p['serial_number'][0:6] == iot.serial_number.serial_number:
+                        p['iot'].append(
+                            {
+                                'endpoint':iot.endpoint,
+                                'token_iot_number':iot.token_iot_number
+
+                            }
+                        )
+
             p['vod'] = []
             for dm in ubqs:
                 if p['UID'] == dm['uid']:
@@ -1074,10 +1145,15 @@ def update_device_shadow(request):
         is_reset = request_dict.get('is_reset', None)
         # 传1则重置设备信息
         if is_reset == '1':
+
             UidSetModel.objects.filter(uid=uid).delete()
             # 重置设备,判断设备为已删除
-            di_qs = Device_Info.objects.filter(UID=uid)
-            di_qs.update(isExist=2)
+            nowTime = int(time.time())
+            uid_bucket = UID_Bucket.objects.filter(uid=uid, endTime__gte=nowTime).values('id', 'has_unused').order_by('addTime')
+            if not uid_bucket.exists():
+                di_qs = Device_Info.objects.filter(UID=uid)
+                di_qs.update(isExist=2)
+
             # 清除redis缓存
             # data = di_qs.values()
             # redisObj = RedisObject(db=8)

+ 175 - 9
Controller/EquipmentManagerV2.py

@@ -8,7 +8,8 @@ from django.db.models import Q
 from django.views.generic.base import View
 
 from Ansjer.config import OSS_STS_ACCESS_SECRET, OSS_STS_ACCESS_KEY
-from Model.models import Device_Info, UID_Bucket, UID_Preview, UidSetModel, UidPushModel
+from Model.models import Device_Info, UID_Bucket, UID_Preview, UidSetModel, UidPushModel, UidChannelSetModel, \
+    iotdeviceInfoModel
 from Object.ResponseObject import ResponseObject
 from Object.TokenObject import TokenObject
 from Service.CommonService import CommonService
@@ -148,17 +149,22 @@ class EquipmentManagerV2(View):
                        'View_Password', 'ChannelIndex', 'Type', 'isShare',
                        'primaryUserID', 'primaryMaster', 'data_joined', 'vodPrimaryUserID', 'vodPrimaryMaster', 'userID__userEmail',
                        'version',
-                       'isVod', 'isExist', 'NotificationMode', 'isOpenCloud', 'endpoint')
+                       'isVod', 'isExist', 'NotificationMode', 'isOpenCloud', 'serial_number')
             dvls = CommonService.qs_to_list(dvql)
+
             uid_list = []
+            serial_number_list = []
             for dvl in dvls:
                 if dvl['primaryUserID'] and dvl['id'] == dvl['primaryUserID']:
                     dvl['isPrimaryUser'] = 1
                 else:
                     dvl['isPrimaryUser'] = 0
                 uid_list.append(dvl['UID'])
-                # if dvl['isShare'] is False:
-                #     uid_list.append(dvl['UID'])
+                serial_number_list.append(dvl['serial_number'][0:6])
+
+            # 新增获取IOT证书内容
+            iotqs = iotdeviceInfoModel.objects.filter(serial_number__serial_number__in=serial_number_list)
+
             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')
@@ -167,11 +173,30 @@ class EquipmentManagerV2(View):
             nowTime = int(time.time())
             data = []
             # 设备拓展信息表
-            us_qs = UidSetModel.objects.filter(uid__in=uid_list).values('uid', 'version', 'nickname', 'ucode','detect_interval')
+            us_qs = UidSetModel.objects.filter(uid__in=uid_list).values('uid', 'version', 'nickname', 'ucode','detect_interval', 'is_human', 'is_custom_voice')
             uv_dict = {}
             for us in us_qs:
-                uv_dict[us['uid']] = {'version': us['version'], 'nickname': us['nickname'], 'ucode': us['ucode'],'detect_interval':us['detect_interval']}
+                uv_dict[us['uid']] = {
+                    'version': us['version'],
+                    'nickname': us['nickname'],
+                    'ucode': us['ucode'],
+                    'detect_interval': us['detect_interval'],
+                    'is_human': us['is_human'],
+                    'is_custom_voice': us['is_custom_voice'],
+                }
             for p in dvls:
+                # 新增云分配UID
+                p['iot'] = []
+                for iot in iotqs:
+                    if p['serial_number'][0:6] == iot.serial_number.serial_number:
+                        p['iot'].append(
+                            {
+                                'endpoint': iot.endpoint,
+                                'token_iot_number': iot.token_iot_number
+
+                            }
+                        )
+
                 p['vod'] = []
                 for dm in ubqs:
                     if p['UID'] == dm['uid']:
@@ -189,6 +214,8 @@ class EquipmentManagerV2(View):
                     p['uid_version'] = uv_dict[p_uid]['version']
                     p['ucode'] = uv_dict[p_uid]['ucode']
                     p['detect_interval'] = uv_dict[p_uid]['detect_interval']
+                    p['is_human'] = uv_dict[p_uid]['is_human']
+                    p['is_custom_voice'] = uv_dict[p_uid]['is_custom_voice']
                     # 设备昵称 调用影子信息昵称,先阶段不可
                     if uv_dict[p_uid]['nickname']:
                         p['NickName'] = uv_dict[p_uid]['nickname']
@@ -210,6 +237,145 @@ class EquipmentManagerV2(View):
                            'View_Password', 'ChannelIndex', 'Type', 'isShare',
                            'primaryUserID', 'primaryMaster', 'data_joined', 'vodPrimaryUserID', 'vodPrimaryMaster',
                            'userID__userEmail',
-                           'version', 'isVod', 'isExist', 'NotificationMode', 'isCameraOpenCloud', 'endpoint', 'token_iot_number')
-        res = CommonService.qs_to_list(dvql)
-        return response.json(0, res)
+                           'version', 'isVod', 'isExist', 'NotificationMode', 'isCameraOpenCloud', 'serial_number')
+        dvls = CommonService.qs_to_list(dvql)
+        uid_list = []
+        serial_number_list = []
+        for dvl in dvls:
+            if dvl['primaryUserID'] and dvl['id'] == dvl['primaryUserID']:
+                dvl['isPrimaryUser'] = 1
+            else:
+                dvl['isPrimaryUser'] = 0
+            uid_list.append(dvl['UID'])
+            serial_number_list.append(dvl['serial_number'])
+
+        # 新增获取IOT证书内容
+        iotqs = iotdeviceInfoModel.objects.filter(serial_number__serial_number__in=serial_number_list)
+
+        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('id', 'uid', 'version', 'nickname', 'ucode',
+                                                                    'detect_status', 'detect_group',
+                                                                    'detect_interval',
+                                                                    'region_alexa', 'is_alexa', 'deviceModel',
+                                                                    'TimeZone', 'TimeStatus', 'SpaceUsable',
+                                                                    'SpaceSum', 'MirrorType', 'RecordType',
+                                                                    'OutdoorModel', 'WIFIName', 'isDetector',
+                                                                    'DetectorRank')
+        uv_dict = {}
+        for us in us_qs:
+            uv_dict[us['uid']] = {
+                'version': us['version'],
+                'nickname': us['nickname'],
+                'ucode': us['ucode'],
+                'detect_interval': us['detect_interval'],
+                'detect_group': us['detect_group'],
+                'detect_status': us['detect_status'],
+                'region_alexa': us['region_alexa'],
+                'is_alexa': us['is_alexa'],
+                'deviceModel': us['deviceModel'],
+                'TimeZone': us['TimeZone'],
+                'TimeStatus': us['TimeStatus'],
+                'SpaceUsable': us['SpaceUsable'],
+                'SpaceSum': us['SpaceSum'],
+                'MirrorType': us['MirrorType'],
+                'RecordType': us['RecordType'],
+                'OutdoorModel': us['OutdoorModel'],
+                'WIFIName': us['WIFIName'],
+                'isDetector': us['isDetector'],
+                'DetectorRank': us['DetectorRank']
+            }
+            # 从uid_channel里面取出通道配置信息
+            ucs_qs = UidChannelSetModel.objects.filter(uid__id=us['id']).values('channel', 'pir_audio', 'mic_audio',
+                                                                                'battery_status', 'battery_level',
+                                                                                'sleep_status', 'sleep_time',
+                                                                                'light_night_model',
+                                                                                'light_alarm_type',
+                                                                                'light_alarm_level',
+                                                                                'light_alarm_man_en',
+                                                                                'light_alarm_vol',
+                                                                                'light_long_light'
+                                                                                )
+            channels = []
+            for ucs in ucs_qs:
+                channels_dict = {
+                    'channel': ucs['channel'],
+                    'pir_audio': ucs['pir_audio'],
+                    'mic_audio': ucs['mic_audio'],
+                    'battery_status': ucs['battery_status'],
+                    'battery_level': ucs['battery_level'],
+                    'sleep_status': ucs['sleep_status'],
+                    'sleep_time': ucs['sleep_time'],
+                    'light_night_model': ucs['light_night_model'],
+                    'light_alarm_type': ucs['light_alarm_type'],
+                    'light_alarm_level': ucs['light_alarm_level'],
+                    'light_alarm_man_en': ucs['light_alarm_man_en'],
+                    'light_alarm_vol': ucs['light_alarm_vol'],
+                    'light_long_light': ucs['light_long_light']
+                }
+                channels.append(channels_dict)
+            uv_dict[us['uid']]['channels'] = channels
+
+        for p in dvls:
+            # 新增IOT
+            p['iot'] = []
+            for iot in iotqs:
+                if p['serial_number'][0:6] == iot.serial_number:
+                    p['iot'].append(
+                        {
+                            'endpoint': iot.endpoint,
+                            'token_iot_number': iot.token_iot_number
+
+                        }
+                    )
+
+            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['ucode'] = uv_dict[p_uid]['ucode']
+                p['detect_interval'] = uv_dict[p_uid]['detect_interval']
+                p['detect_status'] = uv_dict[p_uid]['detect_status']
+                p['detect_group'] = uv_dict[p_uid]['detect_group']
+                p['region_alexa'] = uv_dict[p_uid]['region_alexa']
+                p['is_alexa'] = uv_dict[p_uid]['is_alexa']
+                p['deviceModel'] = uv_dict[p_uid]['deviceModel']
+                p['TimeZone'] = uv_dict[p_uid]['TimeZone']
+                p['TimeStatus'] = uv_dict[p_uid]['TimeStatus']
+                p['SpaceUsable'] = uv_dict[p_uid]['SpaceUsable']
+                p['SpaceSum'] = uv_dict[p_uid]['SpaceSum']
+                p['MirrorType'] = uv_dict[p_uid]['MirrorType']
+                p['RecordType'] = uv_dict[p_uid]['RecordType']
+                p['OutdoorModel'] = uv_dict[p_uid]['OutdoorModel']
+                p['WIFIName'] = uv_dict[p_uid]['WIFIName']
+                p['isDetector'] = uv_dict[p_uid]['isDetector']
+                p['DetectorRank'] = uv_dict[p_uid]['DetectorRank']
+                p['channels'] = uv_dict[p_uid]['channels']
+                # 设备昵称 调用影子信息昵称,先阶段不可
+                if uv_dict[p_uid]['nickname']:
+                    p['NickName'] = uv_dict[p_uid]['nickname']
+            else:
+                # 设备版本号
+                p['uid_version'] = ''
+                p['ucode'] = ''
+            data.append(p)
+        result = data
+
+        return response.json(0, result)

+ 311 - 44
Controller/EquipmentManagerV3.py

@@ -2,18 +2,23 @@ import re
 import threading
 import time
 import traceback
+
+import requests
+
 from Controller.CheckUserData import RandomStr
 import oss2, base64
 from django.db.models import Q
 from django.views.generic.base import View
 from Object.RedisObject import RedisObject
 from Ansjer.config import OSS_STS_ACCESS_SECRET, OSS_STS_ACCESS_KEY, BASE_DIR
-from Model.models import Device_Info, UID_Bucket, UID_Preview, UidSetModel, UidPushModel, UidChannelSetModel
+from Model.models import Device_Info, UID_Bucket, UID_Preview, UidSetModel, UidPushModel, UidChannelSetModel, \
+    Device_User, iotdeviceInfoModel, UIDCompanySerialModel, UIDMainUser
 from Object.ResponseObject import ResponseObject
 from Object.TokenObject import TokenObject
 from Service.CommonService import CommonService
 from Service.ModelService import ModelService
-import time,json
+import time, json
+
 
 class EquipmentManagerV3(View):
 
@@ -24,6 +29,7 @@ class EquipmentManagerV3(View):
 
     def post(self, request, *args, **kwargs):
         request.encoding = 'utf-8'
+
         operation = kwargs.get('operation')
         return self.validation(request.POST, request, operation)
 
@@ -42,8 +48,12 @@ class EquipmentManagerV3(View):
                 return self.do_query(userID, request_dict, response)
             elif operation == 'modify':
                 return self.do_modify(userID, request_dict, response, request)
+            elif operation == 'fuzzyQuery':
+                return self.do_fuzzy_query(userID, request_dict, response)
             elif operation == 'mainUserDevice':
                 return self.do_mainUserDevice( request_dict, response)
+            elif operation == 'getDeviceFeatures':
+                return self.do_get_device_features(request_dict, response)
             else:
                 return response.json(414)
         else:
@@ -54,9 +64,10 @@ class EquipmentManagerV3(View):
         UID = request_dict.get('UID', None)
         NickName = request_dict.get('NickName', None)
         View_Account = request_dict.get('View_Account', None)
-        View_Password_Encypt = request_dict.get('View_Password', '')
+        View_Password = request_dict.get('View_Password', '')
+        encrypt_pass = View_Password
         print("准备解密")
-        View_Password = self.decode_pwd(View_Password_Encypt)
+        View_Password = self.decode_pwd(View_Password)
         Type = request_dict.get('Type', None)
         ChannelIndex = request_dict.get('ChannelIndex', None)
         version = request_dict.get('version', '')
@@ -64,11 +75,10 @@ class EquipmentManagerV3(View):
         isMainUserExists = False
         if all([UID, NickName, View_Account, Type, ChannelIndex]):
             tko = TokenObject(token)
-
             response.lang = tko.lang
             if tko.code == 0:
                 userID = tko.userID
-                re_uid = re.compile(r'^[A-Za-z0-9]{20}$')
+                re_uid = re.compile(r'^[A-Za-z0-9]{14,20}$')
                 if re_uid.match(UID):
                     is_exist = Device_Info.objects.filter(UID=UID, userID_id=userID)
                     if is_exist:
@@ -77,15 +87,11 @@ class EquipmentManagerV3(View):
                             return response.json(174)
                         else:
                             is_exist.delete()
-                    # if UID == '98UXAA8BRPA35VAL111A':
-                    #     asy = threading.Thread(target=ModelService.add_log,
-                    #                            args=(CommonService.get_ip_address(request), userID, 'addV3'))
-                    #     asy.start()
-                    #     return response.json(10, 'illegal uid: {uid}'.format(uid=UID))
-                    # is_bind = Device_Info.objects.filter(UID=UID, isShare=False)
-                    # # 判断是否有已绑定用户
-                    # if is_bind:
-                    #     return response.json(15)
+                    if UID == '98UXAA8BRPA35VAL111A':
+                        asy = threading.Thread(target=ModelService.add_log,
+                                               args=(CommonService.get_ip_address(request), userID, 'addV3'))
+                        asy.start()
+                        return response.json(10, 'illegal uid: {uid}'.format(uid=UID))
 
                     pk = CommonService.getUserID(getUser=False)
 
@@ -108,8 +114,30 @@ class EquipmentManagerV3(View):
                         if forbind['vodPrimaryUserID'] != '':
                             isvodPrimaryUserID = forbind['vodPrimaryUserID']
 
+                    if isCheckMainUser != '1' :
+                        if main_exist.exists():
+                            vodPrimaryUserID = main_exist[0]['vodPrimaryUserID']
+                            vodPrimaryMaster = main_exist[0]['vodPrimaryMaster']
+                        else:
+                            vodPrimaryUserID = ''
+                            vodPrimaryMaster = ''
+
+                    isusermain = False
+                    if is_bind and isvodPrimaryUserID != userID and isvodPrimaryUserID != '':
+                        isusermain = True
+
+                    uid_main_exist = UIDMainUser.objects.filter(UID=UID).values('UID', 'user_id')
+                    if uid_main_exist.exists():
+                        vodPrimaryUserID = uid_main_exist[0]['user_id']
+                        vodPrimaryMaster = Device_User.objects.get(userID=vodPrimaryUserID).username
+
+                        if vodPrimaryUserID != userID:
+                            isusermain = True
+
+
+
                     # 判断是否有已绑定用户
-                    if is_bind and isCheckMainUser == '1' and isvodPrimaryUserID != userID and isvodPrimaryUserID != '':
+                    if isCheckMainUser == '1' and isusermain:
                         res = {
                             'id': pk,
                             'userID': userID,
@@ -159,20 +187,37 @@ class EquipmentManagerV3(View):
                             UidSetModel.objects.create(**uid_set_create_dict)
                         else:
                             us_qs.update(nickname=NickName)
+
                         userDevice = Device_Info(id=pk, userID_id=userID, UID=UID,
                                                  NickName=NickName, View_Account=View_Account,
                                                  View_Password=View_Password, Type=Type, ChannelIndex=ChannelIndex,
                                                  version=version,
                                                  vodPrimaryUserID=vodPrimaryUserID, vodPrimaryMaster=vodPrimaryMaster)
                         userDevice.save()
-                        Device_Info.objects.filter(UID=UID).update(vodPrimaryUserID=vodPrimaryUserID,
-                                                                   vodPrimaryMaster=vodPrimaryMaster)
+                        uid_serial_qs = UIDCompanySerialModel.objects.filter(
+                            uid__uid=UID)
+                        if uid_serial_qs.exists():
+                            uid_serial = uid_serial_qs[0]
+                            Device_Info.objects.filter(UID=UID).update(vodPrimaryUserID=vodPrimaryUserID,
+                                                                       vodPrimaryMaster=vodPrimaryMaster,
+                                                                       serial_number=uid_serial.company_serial.serial_number.serial_number + uid_serial.company_serial.company.mark)
+                        else:
+                            Device_Info.objects.filter(UID=UID).update(vodPrimaryUserID=vodPrimaryUserID,
+                                                                       vodPrimaryMaster=vodPrimaryMaster)
+
+                        if isCheckMainUser == '1':
+                            uid_main_dict = {
+                                'UID': UID,
+                                'user_id': vodPrimaryUserID
+                            }
+                            UIDMainUser.objects.create(**uid_main_dict)
 
                         if not us_qs.exists():
                             us_qs = UidSetModel.objects.filter(uid=UID)
 
                         if us_qs.exists() and us_qs[0].is_alexa == 1:
-                            asy = threading.Thread(target=ModelService.notify_alexa_add, args=(UID, userID, NickName, View_Password_Encypt))
+                            asy = threading.Thread(target=ModelService.notify_alexa_add,
+                                                   args=(UID, userID, NickName, encrypt_pass))
                             asy.start()
 
                         # redisObj = RedisObject(db=8)
@@ -188,21 +233,31 @@ class EquipmentManagerV3(View):
                                                                         'vodPrimaryUserID', 'vodPrimaryMaster',
                                                                         'userID__userEmail',
                                                                         'data_joined', 'version',
-                                                                        'isVod', 'isExist', 'isCameraOpenCloud', 'endpoint', 'token_iot_number')
-                    dvql = CommonService.qs_to_list(dvqs)
-                    ubqs = UID_Bucket.objects.filter(uid=UID). \
-                        values('bucket__content', 'status', 'channel', 'endTime', 'uid')
-                    res = dvql[0]
-                    res['vod'] = list(ubqs)
+                                                                        'isVod', 'isExist', 'isCameraOpenCloud', 'serial_number')
+                        dvql = CommonService.qs_to_list(dvqs)
+                        ubqs = UID_Bucket.objects.filter(uid=UID). \
+                            values('bucket__content', 'status', 'channel', 'endTime', 'uid')
+                        res = dvql[0]
+                        res['vod'] = list(ubqs)
+
+                        iotqs = iotdeviceInfoModel.objects.filter(serial_number__serial_number=dvql[0]['serial_number'])
+                        if iotqs.exists():
+                            res['iot'].append(
+                                {
+                                    'endpoint': iotqs[0].endpoint,
+                                    'token_iot_number': iotqs[0].endpoint
+
+                                }
+                            )
 
-                    return response.json(0, res)
+                        return response.json(0, res)
 
                 else:
                     return response.json(444, {'param': 'UID'})
             else:
                 return response.json(tko.code)
         else:
-            return response.json(444, {'param': 'UID,NickName,View_Account,View_Password,Type,ChannelIndex'})
+            return response.json(444, {'param': 'UID,NickName,View_Account,View_Password,Type,ChannelIndex,version'})
 
     def do_modify(self, userID, request_dict, response, request):
         token = request_dict.get('token', None)
@@ -217,10 +272,11 @@ class EquipmentManagerV3(View):
         userID = tko.userID
         if userID is None:
             return response.json(309)
+        deviceData = None
+        dev_info_qs = None
         try:
             # deviceData = json.loads(deviceContent)
             deviceData = eval(deviceContent)
-
             if deviceData.__contains__('userID_id'):
                 asy = threading.Thread(target=ModelService.update_log,
                                        args=(CommonService.get_ip_address(request), userID, 'modifyV3', deviceData, id))
@@ -232,6 +288,7 @@ class EquipmentManagerV3(View):
 
             # print(deviceData['View_Password'])
             if deviceData.__contains__('View_Password'):
+                encrypt_pwd = deviceData['View_Password']
                 deviceData['View_Password'] = self.decode_pwd(deviceData['View_Password'])
             dev_info_qs = Device_Info.objects.filter(userID_id=userID, id=id)
             dev_info_qs.update(**deviceData)
@@ -243,15 +300,12 @@ class EquipmentManagerV3(View):
             res = CommonService.qs_to_dict(qs)
             if qs.exists():
                 uid = qs[0].UID
-                # if uid == '98UXAA8BRPA35VAL111A':
-                #     asy = threading.Thread(target=ModelService.update_log,
-                #                            args=(CommonService.get_ip_address(request), userID, 'modifyV3', deviceData, id))
-                #     asy.start()
                 nickname = qs[0].NickName
                 # 增加设备影子信息修改昵称 start
                 us_qs = UidSetModel.objects.filter(uid=uid)
                 if us_qs.exists():
-                    us_qs.update(nickname=nickname)
+                    if deviceData.__contains__('NickName'):
+                        us_qs.update(nickname=nickname)
                 else:
                     ChannelIndex = qs[0].ChannelIndex
                     nowTime = int(time.time())
@@ -267,8 +321,8 @@ class EquipmentManagerV3(View):
                 di_qs = Device_Info.objects.filter(UID=uid)
                 di_qs.update(NickName=nickname)
                 if deviceData is not None and deviceData.__contains__('NickName') and us_qs[0].is_alexa == 1:
-
-                    asy = threading.Thread(target=ModelService.notify_alexa_add, args=(uid, userID, nickname, self.encrypt_pwd(di_qs[0].View_Password)))
+                    password = encrypt_pwd if deviceData.__contains__('View_Password') else ''
+                    asy = threading.Thread(target=ModelService.notify_alexa_add, args=(uid, userID, nickname, password))
                     asy.start()
             # redisObj = RedisObject(db=8)
             # redisObj.del_data(key='uid_qs_' + userID)
@@ -300,15 +354,21 @@ class EquipmentManagerV3(View):
                                'primaryUserID', 'primaryMaster', 'data_joined', 'vodPrimaryUserID', 'vodPrimaryMaster',
                                'userID__userEmail',
                                'version', 'isVod', 'isExist', 'NotificationMode', 'isCameraOpenCloud',
-                               'endpoint', 'token_iot_number')
+                               'serial_number')
             dvls = CommonService.qs_to_list(dvql)
             uid_list = []
+            serial_number_list = []
             for dvl in dvls:
                 if dvl['primaryUserID'] and dvl['id'] == dvl['primaryUserID']:
                     dvl['isPrimaryUser'] = 1
                 else:
                     dvl['isPrimaryUser'] = 0
                 uid_list.append(dvl['UID'])
+                serial_number_list.append(dvl['serial_number'][0:6])
+
+            # 新增获取IOT证书内容
+            iotqs = iotdeviceInfoModel.objects.filter(serial_number__serial_number__in=serial_number_list)
+
             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')
@@ -351,10 +411,19 @@ class EquipmentManagerV3(View):
                     'is_custom_voice': us['is_custom_voice']
                 }
                 # 从uid_channel里面取出通道配置信息
-                ucs_qs = UidChannelSetModel.objects.filter(uid__id=us['id']).values()
+                ucs_qs = UidChannelSetModel.objects.filter(uid__id=us['id']).values('channel', 'pir_audio', 'mic_audio',
+                                                                                    'battery_status', 'battery_level',
+                                                                                    'sleep_status', 'sleep_time',
+                                                                                    'light_night_model',
+                                                                                    'light_alarm_type',
+                                                                                    'light_alarm_level',
+                                                                                    'light_alarm_man_en',
+                                                                                    'light_alarm_vol',
+                                                                                    'light_long_light'
+                                                                                    )
                 channels = []
                 for ucs in ucs_qs:
-                    channel = {
+                    channels_dict = {
                         'channel': ucs['channel'],
                         'pir_audio': ucs['pir_audio'],
                         'mic_audio': ucs['mic_audio'],
@@ -369,10 +438,22 @@ class EquipmentManagerV3(View):
                         'light_alarm_vol': ucs['light_alarm_vol'],
                         'light_long_light': ucs['light_long_light']
                     }
-                    channels.append(channel)
+                    channels.append(channels_dict)
                 uv_dict[us['uid']]['channels'] = channels
 
             for p in dvls:
+                # 新增IOT
+                p['iot'] = []
+                for iot in iotqs:
+                    if p['serial_number'][0:6] == iot.serial_number.serial_number:
+                        p['iot'].append(
+                            {
+                                'endpoint': iot.endpoint,
+                                'token_iot_number': iot.token_iot_number
+
+                            }
+                        )
+
                 p['vod'] = []
                 for dm in ubqs:
                     if p['UID'] == dm['uid']:
@@ -450,17 +531,178 @@ class EquipmentManagerV3(View):
         else:
             return response.json(tko.code)
 
+    def do_fuzzy_query(self, userID, request_dict, response):
+        fuzzy = request_dict.get('fuzzy', None)
+        page = request_dict.get('page', None)
+        line = request_dict.get('line', None)
+
+        if page and line:
+            page = int(page)
+            line = int(line)
+            device_qs = Device_Info.objects.filter(userID=userID)
+            device_qs = device_qs.filter(~Q(isExist=2))
+            if device_qs.exists():
+                if fuzzy:
+                    device_qs = device_qs.filter(Q(UID__contains=fuzzy) | Q(NickName__contains=fuzzy))
+
+                device_qs = device_qs.values('id', 'userID', 'NickName', 'UID', 'View_Account',
+                                             'View_Password', 'ChannelIndex', 'Type', 'isShare',
+                                             'primaryUserID', 'primaryMaster', 'data_joined', 'vodPrimaryUserID',
+                                             'vodPrimaryMaster', 'userID__userEmail',
+                                             'version', 'isVod', 'isExist', 'NotificationMode', 'isCameraOpenCloud', 'serial_number')
+
+                dvls = CommonService.qs_to_list(device_qs)
+                uid_list = []
+                serial_number_list = []
+                for dvl in dvls:
+                    uid_list.append(dvl['UID'])
+                    serial_number_list.append(dvl['serial_number'][0:6])
+
+                # 新增获取IOT证书内容
+                iotqs = iotdeviceInfoModel.objects.filter(serial_number__serial_number__in=serial_number_list)
+
+                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('id', 'uid', 'version', 'nickname', 'ucode',
+                                                                            'detect_status', 'detect_group',
+                                                                            'detect_interval',
+                                                                            'region_alexa', 'is_alexa', 'deviceModel',
+                                                                            'TimeZone', 'TimeStatus', 'SpaceUsable',
+                                                                            'SpaceSum', 'MirrorType', 'RecordType',
+                                                                            'OutdoorModel', 'WIFIName', 'isDetector',
+                                                                            'DetectorRank')
+                uv_dict = {}
+                for us in us_qs:
+                    uv_dict[us['uid']] = {
+                        'version': us['version'],
+                        'nickname': us['nickname'],
+                        'ucode': us['ucode'],
+                        'detect_interval': us['detect_interval'],
+                        'detect_group': us['detect_group'],
+                        'detect_status': us['detect_status'],
+                        'region_alexa': us['region_alexa'],
+                        'is_alexa': us['is_alexa'],
+                        'deviceModel': us['deviceModel'],
+                        'TimeZone': us['TimeZone'],
+                        'TimeStatus': us['TimeStatus'],
+                        'SpaceUsable': us['SpaceUsable'],
+                        'SpaceSum': us['SpaceSum'],
+                        'MirrorType': us['MirrorType'],
+                        'RecordType': us['RecordType'],
+                        'OutdoorModel': us['OutdoorModel'],
+                        'WIFIName': us['WIFIName'],
+                        'isDetector': us['isDetector'],
+                        'DetectorRank': us['DetectorRank']
+                    }
+                    # 从uid_channel里面取出通道配置信息
+                    ucs_qs = UidChannelSetModel.objects.filter(uid__id=us['id']).values()
+                    channels = []
+                    for ucs in ucs_qs:
+                        channel = {
+                            'channel': ucs['channel'],
+                            'pir_audio': ucs['pir_audio'],
+                            'mic_audio': ucs['mic_audio'],
+                            'battery_status': ucs['battery_status'],
+                            'battery_level': ucs['battery_level'],
+                            'sleep_status': ucs['sleep_status'],
+                            'sleep_time': ucs['sleep_time'],
+                            'light_night_model': ucs['light_night_model'],
+                            'light_alarm_type': ucs['light_alarm_type'],
+                            'light_alarm_level': ucs['light_alarm_level'],
+                            'light_alarm_man_en': ucs['light_alarm_man_en'],
+                            'light_alarm_vol': ucs['light_alarm_vol'],
+                            'light_long_light': ucs['light_long_light']
+                        }
+                        channels.append(channel)
+                    uv_dict[us['uid']]['channels'] = channels
+
+                for p in dvls:
+                    # 新增IOT
+                    p['iot'] = []
+                    for iot in iotqs:
+                        if p['serial_number'][0:6] == iot.serial_number.serial_number:
+                            p['iot'].append(
+                                {
+                                    'endpoint': iot.endpoint,
+                                    'token_iot_number': iot.token_iot_number
+
+                                }
+                            )
+                    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['ucode'] = uv_dict[p_uid]['ucode']
+                        p['detect_interval'] = uv_dict[p_uid]['detect_interval']
+                        p['detect_status'] = uv_dict[p_uid]['detect_status']
+                        p['detect_group'] = uv_dict[p_uid]['detect_group']
+                        p['region_alexa'] = uv_dict[p_uid]['region_alexa']
+                        p['is_alexa'] = uv_dict[p_uid]['is_alexa']
+                        p['deviceModel'] = uv_dict[p_uid]['deviceModel']
+                        p['TimeZone'] = uv_dict[p_uid]['TimeZone']
+                        p['TimeStatus'] = uv_dict[p_uid]['TimeStatus']
+                        p['SpaceUsable'] = uv_dict[p_uid]['SpaceUsable']
+                        p['SpaceSum'] = uv_dict[p_uid]['SpaceSum']
+                        p['MirrorType'] = uv_dict[p_uid]['MirrorType']
+                        p['RecordType'] = uv_dict[p_uid]['RecordType']
+                        p['OutdoorModel'] = uv_dict[p_uid]['OutdoorModel']
+                        p['WIFIName'] = uv_dict[p_uid]['WIFIName']
+                        p['isDetector'] = uv_dict[p_uid]['isDetector']
+                        p['DetectorRank'] = uv_dict[p_uid]['DetectorRank']
+                        p['channels'] = uv_dict[p_uid]['channels']
+                        # 设备昵称 调用影子信息昵称,先阶段不可
+                        if uv_dict[p_uid]['nickname']:
+                            p['NickName'] = uv_dict[p_uid]['nickname']
+                    else:
+                        # 设备版本号
+                        p['uid_version'] = ''
+                        p['ucode'] = ''
+                    data.append(p)
+                result = data
+                items = []
+                # print('缓存分页')
+                for index, item in enumerate(result):
+                    if (page - 1) * line <= index:
+                        if index < page * line:
+                            # 加密
+                            item['View_Password'] = self.encrypt_pwd(item['View_Password'])
+                            print(item)
+                            items.append(item)
+                print(items)
+                return response.json(0, items)
+            else:
+                return response.json(0, [])
+        else:
+            return response.json(444)
+
     # 加密
-    def encrypt_pwd(self,userPwd):
+    def encrypt_pwd(self, userPwd):
         for i in range(1, 4):
             if i == 1:
-                userPwd = RandomStr(3, False)+userPwd+RandomStr(3, False)
+                userPwd = RandomStr(3, False) + userPwd + RandomStr(3, False)
                 userPwd = base64.b64encode(str(userPwd).encode("utf-8")).decode('utf8')
             if i == 2:
-                userPwd = RandomStr(2, False)+str(userPwd)+RandomStr(2, False)
+                userPwd = RandomStr(2, False) + str(userPwd) + RandomStr(2, False)
                 userPwd = base64.b64encode(str(userPwd).encode("utf-8")).decode('utf8')
             if i == 3:
-                userPwd = RandomStr(1, False)+str(userPwd)+RandomStr(1, False)
+                userPwd = RandomStr(1, False) + str(userPwd) + RandomStr(1, False)
                 userPwd = base64.b64encode(str(userPwd).encode("utf-8")).decode('utf8')
         return userPwd
 
@@ -496,4 +738,29 @@ class EquipmentManagerV3(View):
             qs = Device_User.objects.filter(userID=dvq[0]['vodPrimaryUserID']).values('userID', 'NickName', 'username', 'userEmail', 'phone')
             qs = CommonService.qs_to_list(qs)
 
-        return response.json(0, qs)
+        if not qs:
+            uidq = UIDMainUser.objects.filter(UID=UID).values('user_id')
+            if uidq.exists():
+                qs = Device_User.objects.filter(userID=uidq[0]['user_id']).values('userID', 'NickName', 'username', 'userEmail', 'phone')
+                qs = CommonService.qs_to_list(qs)
+
+        return response.json(0, qs)
+
+    def do_get_device_features(self, request_dict, response):
+        uid = request_dict.get('uid', None)
+
+        if uid:
+            uid = CommonService.decode_data(uid)
+
+            if uid:
+                uid_qs = UidSetModel.objects.filter(uid=uid)
+                if uid_qs.exists():
+                    uid_qs = uid_qs.values('is_alexa', 'is_human', 'is_custom_voice', 'double_wifi')
+                    return response.json(0, uid_qs[0])
+                else:
+                    return response.json(173)
+            else:
+                return response.json(444)
+
+        else:
+            return response.json(444)

+ 21 - 13
Controller/EquipmentOTA.py

@@ -7,7 +7,7 @@ from django.views.decorators.csrf import csrf_exempt
 from django.views.generic.base import View
 
 from Ansjer.config import BASE_DIR, SERVER_DOMAIN
-from Model.models import Equipment_Version, EquipmentVersionLimitModel
+from Model.models import Equipment_Version, EquipmentVersionLimitModel, CountryIPModel
 from Object.RedisObject import RedisObject
 from Object.ResponseObject import ResponseObject
 from Object.TokenObject import TokenObject
@@ -64,22 +64,21 @@ class EquipmentOTA(View):
 
     def delete(self, request_dict, userID, response):
         eid = request_dict.get('eid', None)
-        if not eid:
-            return response.json(444, 'eid')
+        version = request_dict.get('version', None)
+        if not eid or not version:
+            return response.json(444, 'eid or version')
         own_perm = ModelService.check_perm(userID=userID, permID=230)
         if not own_perm:
             return response.json(404)
-        ev = Equipment_Version.objects.filter(eid=eid)
-        if not ev.exists():
+        equipment_version = Equipment_Version.objects.filter(eid=eid, version=version)
+        if not equipment_version.exists():
             return response.json(173)
         try:
-            has_ev = Equipment_Version.objects.filter(filePath=ev[0].filePath)
-            if has_ev.exists():
-                pass
-            else:
-                filepath = os.path.join(BASE_DIR, ev[0].filePath)
-                os.remove(filepath)
-            ev.delete()
+            # 删除文件和相应数据
+            file_path = equipment_version[0].filePath
+            file_path = os.path.join(BASE_DIR, file_path).replace('\\', '/')
+            os.remove(file_path)
+            equipment_version.delete()
         except Exception as e:
             return response.json(176, repr(e))
         else:
@@ -286,7 +285,16 @@ class EquipmentVersionView(View):
             if ov > eqs[0].softwareVersion:
                 return response.json(0, {'softwareVersion': ov})
         equipment = eqs[0]
-        evl_qs = EquipmentVersionLimitModel.objects.filter(equipment_version_id=equipment.eid, status=1).values()
+        redisObject = RedisObject()
+        key = 'limit_{eid}'.format(eid=equipment.eid)
+
+        evl_qs = redisObject.get_data(key=key)
+        if evl_qs:
+            evl_qs = json.loads(evl_qs)
+        else:
+            evl_qs = EquipmentVersionLimitModel.objects.filter(equipment_version_id=equipment.eid, status=1).values()
+            if evl_qs.exists():
+                redisObject.set_data(key=key, val=json.dumps(list(evl_qs.values())), expire=600)
         if evl_qs and len(evl_qs) > 0:
             evl = evl_qs[0]
             if evl['type'] == 1:  # uid限制

+ 12 - 1
Controller/EquipmentStatus.py

@@ -12,6 +12,8 @@
 @Contact: chanjunkai@163.com
 """
 import base64
+import json
+import threading
 import urllib.parse
 import time
 import oss2
@@ -21,7 +23,9 @@ from django.views.decorators.csrf import csrf_exempt
 from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET
 from Model.models import Device_Info
 from Object.ETkObject import ETkObject
+from Object.RedisObject import RedisObject
 from Object.ResponseObject import ResponseObject
+from Service.ModelService import ModelService
 from Service.CommonService import CommonService
 
 '''
@@ -109,7 +113,13 @@ def getTZ(request):
         uid = c.decode('utf-8')
         if len(uid) == 20:
             print(uid)
-            if update:
+            redisObject = RedisObject(db=7)
+            data = redisObject.get_data(key=ip)
+
+            if data:
+                info = json.loads(data)
+                return JsonResponse(status=200, data={'code': 0, 'msg': 'success', 'data': info})
+            elif update:
                 info = CommonService.getIpIpInfo(ip=ip, lang=lang,update=True)
             else:
                 info = CommonService.getIpIpInfo(ip=ip, lang=lang,update=False)
@@ -124,6 +134,7 @@ def getTZ(request):
                 elif len(tz) == 8:
                     gmtz = tz.replace('UTC-', 'GMT-0').replace('UTC+', 'GMT+0')
                     info['gmt_offset'] = gmtz
+                redisObject.set_data(key=ip, val=json.dumps(info), expire=3600)
             except Exception as e:
                 pass
             return JsonResponse(status=200, data={'code': 0, 'msg': 'success', 'data': info})

+ 74 - 5
Controller/FAQController.py

@@ -6,6 +6,7 @@ import shutil
 import time
 import traceback
 
+from django.core import serializers
 from django.http import HttpResponse
 from django.utils.decorators import method_decorator
 from django.views.decorators.csrf import csrf_exempt
@@ -20,7 +21,8 @@ from Object.ResponseObject import ResponseObject
 from Object.TokenObject import TokenObject
 from var_dump import var_dump
 
-from Service.ModelService import ModelService
+from Service.CommonService import CommonService
+from Service.ModelService import ModelService, ZositechHelpModel
 
 
 class FAQUploadView(View):
@@ -168,9 +170,9 @@ class FAQView(View):
     def validate(self, request_dict, operation):
         token = TokenObject(request_dict.get('token', None))
         response = ResponseObject()
-        if token.code != 0:
-            return response.json(token.code)
-
+        if operation != 'zositechHelp':
+            if token.code != 0:
+                return response.json(token.code)
         if operation == 'add':
             return self.do_add(token, request_dict, response)
         elif operation == 'query':
@@ -179,6 +181,10 @@ class FAQView(View):
             return self.do_update(token, request_dict, response)
         elif operation == 'delete':
             return self.do_delete(token.userID, request_dict, response)
+        elif operation == 'zositechHelp':
+            return self.do_zositechHelp(request_dict, response)
+        elif operation == 'synZositechHelp':
+            return self.do_synZositechHelp(request_dict, response)
         else:
             return response.json(404)
 
@@ -321,4 +327,67 @@ class FAQView(View):
             else:
                 return response.json(0)
         else:
-            return response.json(444)
+            return response.json(444)
+
+    def do_zositechHelp(self, request_dict, response):
+
+        locale = request_dict.get('locale', None)
+        label_names = request_dict.get('label_names', None)
+        origin = request_dict.get('origin', None)
+        help_qs = None
+        if label_names:
+            help = ZositechHelpModel.objects.filter(locale=locale, label_names__contains=label_names,
+                                                    origin=origin).values()
+        else:
+            help = ZositechHelpModel.objects.filter(locale=locale, origin=origin).values()
+
+        if help.exists():
+            # send_dict = CommonService.qs_to_dict(help)
+            send_dict = list(help)
+
+            return response.json(0, send_dict)
+
+        else:
+            return response.json(444)
+
+    def do_synZositechHelp(self, request_dict, response):
+        zhresults = request_dict.get('zhresults', None).replace("\'", "XX??????XX")
+        #.replace("\"", "XX??????XX").replace("\'", "\"").replace("XX??????XX", "\'")
+        zhresults = json.loads(zhresults)
+
+        enresults = request_dict.get('enresults', None).replace("\'", "XX??????XX")
+        enresults = json.loads(enresults)
+
+        ZositechHelpModel.objects.all().delete()
+
+        for data in zhresults['results']:
+            labname = ""
+            if data['label_names']:
+                for lab in data['label_names']:
+                    if lab:
+                        labname += ","
+                    labname = lab
+            if not labname:
+                labname = None
+            ZositechHelpModel.objects.create(**{
+                'locale': data['locale'],
+                'label_names': labname,
+                'origin': 'web_widget',
+                'content': json.dumps(data).replace("\'", "\"").replace("XX??????XX", "\'")
+            })
+        for data in enresults['results']:
+            labname = ""
+            if data['label_names']:
+                for lab in data['label_names']:
+                    if lab:
+                        labname += ","
+                    labname = lab
+            if not labname:
+                labname = None
+            ZositechHelpModel.objects.create(**{
+                'locale': data['locale'],
+                'label_names': labname,
+                'origin': 'web_widget',
+                'content': json.dumps(data).replace("\'", "\"").replace("XX??????XX", "\'")
+            })
+        return response.json(0)

+ 35 - 0
Controller/FeedBack.py

@@ -56,6 +56,8 @@ class FeedBackView(View):
                 return self.do_query_by_admin(userID, request_dict, response)
             elif operation == 'deleteByAdmin':
                 return self.do_delete_by_admin(userID, request_dict, response)
+            elif operation == 'deleteImage':
+                return self.do_delete_image(userID, request_dict, response)
             else:
                 return response.json(414)
         else:
@@ -264,3 +266,36 @@ class FeedBackView(View):
                 return response.json(0)
         else:
             return response.json(404)
+
+    def do_delete_image(self, userID, request_dict, response):
+        # own_perm = ModelService.check_perm(userID, 10)
+        # if not own_perm:
+        #     return response.json(404)
+        end_time = request_dict.get('end_time', None)
+        if end_time is None:
+            return response.json(444)
+        sys_ms_qs = FeedBackModel.objects.filter(addTime__lt=end_time).order_by('id').values('id')
+        ids = []
+        for sys_ms in sys_ms_qs:
+            ids.append(sys_ms['id'])
+
+        sm_qs = StatResModel.objects.filter(feedbackmodel__id__in=ids).values('id', 'name')
+        names = []
+        time_struct = time.localtime()
+        current_year = time_struct.tm_year
+        target_year = current_year - 1
+        str_prefix = str(target_year)
+        print(str_prefix)
+        for sm in sm_qs:
+            name = sm['name']
+            if name.find(str_prefix) == 0:
+                names.append('feedback/' + name)
+
+        # auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
+        # bucket = oss2.Bucket(auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
+        # bucket.batch_delete_objects(names)
+        # FeedBackModel.objects.filter(id__in=ids).delete()
+        print(names)
+        print(len(names))
+
+        return response.json(0)

+ 541 - 0
Controller/FileController.py

@@ -0,0 +1,541 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import base64
+import json
+import logging
+import os
+import time
+import zipfile
+
+import xlwt
+
+from django.http import StreamingHttpResponse, HttpResponse, QueryDict
+from django.utils.decorators import method_decorator
+from django.views import View
+from django.views.decorators.csrf import csrf_exempt
+from django.db import transaction
+
+from Ansjer.config import BASE_DIR
+from Model.models import UIDModel, UserUIDModel, UserModel, LogModel, MacModel, OrderTaskModel, OrderUIDModel
+from Object.RedisObject import RedisObject
+from Object.TokenObject import TokenObject
+from Object.uidManageResponseObject import uidManageResponseObject
+from Service.CommonService import CommonService
+
+
+class UploadUIDFileView(View):
+
+    @method_decorator(csrf_exempt)
+    def dispatch(self, request, *args, **kwargs):
+        return super(UploadUIDFileView, self).dispatch(request, *args, **kwargs)
+
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.GET
+        fileName = request.FILES.get('fileName', None)
+        return self.validate(fileName, request_dict, request)
+
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.POST
+        fileName = request.FILES.get('fileName', None)
+        return self.validate(fileName, request_dict, request)
+
+    def validate(self, fileName, request_dict, request):
+        token = request_dict.get('token', None)
+        area = request_dict.get('area', None)
+        isReset = request_dict.get('isReset', 0)
+        content = request_dict.get('fileName', None)
+        vpg_id = request_dict.get('vpg_id', None)
+
+        print('content')
+        print(content)
+
+        content = base64.b64decode(content).decode().strip()
+        content = content[3:(len(content) - 3)]
+        uids = content.split('\n')
+        # print(uids)
+        # print(len(uids))
+
+        response = uidManageResponseObject()
+
+        tko = TokenObject(token)
+        if tko.code != 0:
+            return response.json(tko.code)
+
+        # if not fileName and not area:
+        #     return response.json(444, 'fileName,area')
+
+        data = {}
+        duplicate = []
+        for line in uids:
+
+            if len(line) < 20:
+                continue
+
+            if data.__contains__(line):
+                duplicate.append(line)
+            else:
+                data[line] = ''
+
+        if isReset == 0:
+            return self.do_insert(data, duplicate, vpg_id, area, response, request, tko)
+        else:
+            return self.do_reset(data, response, area, request, tko)
+
+    @transaction.atomic
+    def do_insert(self, data, duplicate, vpg_id, area, response, request, token):
+        bulk = []
+        count = 0
+        add_time = int(time.time())
+        update_time = int(time.time())
+        keys = data.keys()
+
+        # 获取最新的mac
+        mac = MacModel.objects.filter().values('id', 'value', 'is_active')[0]
+        if not mac['is_active']:
+            return response.json(175)
+        # redisObject = RedisObject(db=3)
+        key = ''
+        tmpMac = mac['value']
+        savePoint = None
+        for item in keys:
+            key = item.strip()
+            # value = redisObject.get_data(key)
+            # if value is False:
+            #     # redisObject.set_data(key, '1', 600)
+            # else:
+            #     duplicate.append(key)
+            #     continue
+            bulk.append(UIDModel(
+                uid=item.strip(),
+                uid_extra='',
+                status=0,
+                add_time=add_time,
+                update_time=update_time,
+                area=area,
+                mac=mac['value'],
+                vpg_id=vpg_id
+            ))
+            try:
+                try:
+                    if (count % 5000) == 0:
+                        savePoint = transaction.savepoint()
+                        UIDModel.objects.bulk_create(bulk)
+                        bulk.clear()
+                        data = {
+                            'value': mac['value'],
+                            'is_active': tmpMac is not None
+                        }
+                        MacModel.objects.filter().update(**data)
+                except Exception as e:
+                    # print('--------------------------error 5000')
+                    # print(repr(e))
+                    if savePoint:
+                        transaction.rollback(savePoint)
+                    djangoLogger = logging.getLogger('django')
+                    djangoLogger.exception(repr(e))
+                    return response.json(174, str(e))
+                else:
+                    savePoint = None
+            except Exception as e:
+                # print('--------------------------error 5001')
+                # print(repr(e))
+                djangoLogger = logging.getLogger('django')
+                djangoLogger.exception(repr(e))
+                return response.json(174, str(e))
+            count += 1
+            tmpMac = CommonService.updateMac(mac['value'])
+            if tmpMac is None:
+                # 能分配的mac已用完
+                break
+            else:
+                mac['value'] = tmpMac
+
+        # 当bulk不足5000时,还有数据要插入
+        try:
+            try:
+                savePoint = transaction.savepoint()  # 事务保存点
+                if len(bulk) > 0:
+                    UIDModel.objects.bulk_create(bulk)
+                    bulk.clear()
+            except Exception as e:
+                # print('--------------------------error')
+                # print(repr(e))
+                if savePoint:
+                    transaction.rollback(savePoint)
+                djangoLogger = logging.getLogger('django')
+                djangoLogger.exception(repr(e))
+                return response.json(174)
+            else:
+                del data
+                del bulk
+                data = {
+                    'value': mac['value'],
+                    'is_active': tmpMac is not None
+                }
+                MacModel.objects.filter().update(**data)
+        except Exception as e:
+            # print('--------------------------error 1111')
+            # print(repr(e))
+            djangoLogger = logging.getLogger('django')
+            djangoLogger.exception(repr(e))
+            return response.json(174)
+
+        # print('重复:')
+        # print(duplicate)
+
+        try:
+            operation = self.formatOperation(operation='上传', quantity=int(count), area=int(area))
+            print(operation)
+            self.add_log(request, operation, token)
+        except Exception as e:
+            djangoLogger = logging.getLogger('django')
+            djangoLogger.exception(repr(e))
+
+        if tmpMac is None:
+            return response.json(175, {'last_uid': key})
+        return response.json(0, {'count': count, 'duplicate_count': len(duplicate), 'data': duplicate})
+
+    def do_reset(self, data, response, area, request, token):
+        keys = data.keys()
+        uids = []
+        count = 0
+        for key in keys:
+            uids.append(key.strip())
+            if len(uids) % 5000 == 0:
+                count += self.do_update_uid_status(uids, area)
+                uids.clear()
+
+        if len(uids) > 0:
+            count += self.do_update_uid_status(uids, area)
+            uids.clear()
+
+        operation = self.formatOperation('重置', int(count), int(area))
+        self.add_log(request, operation, token)
+        return response.json(0)
+
+    def do_update_uid_status(self, uids, area):
+        uid_qs = UIDModel.objects.filter(uid__in=uids, area=area, status=2)
+        if uid_qs.exists():
+            uid_ids = []
+            for uid in uid_qs:
+                if uid.status == 2:
+                    uid.status = 1
+                    uid_ids.append(uid.id)
+            UIDModel.objects.bulk_update(uid_qs, fields=['status'])
+
+            try:
+                OrderUIDModel.objects.filter(uid__id__in=tuple(uid_ids)).delete()
+            except Exception as e:
+                print(e)
+
+            return uid_qs.count()
+        return 0
+
+    def add_log(self, request, operation, token):
+        ip = CommonService.get_ip_address(request)
+        now_time = time.time()
+        content = json.loads(json.dumps(request.POST))
+        user_qs = UserModel.objects.filter(id=token.userID)
+
+        if content.__contains__('fileName'):
+            del content['fileName']
+        log = {
+            'status': 200,
+            'content': json.dumps(content),
+            'ip': ip,
+            'time': now_time,
+            'url': 'upload',
+            'operation': operation,
+            'user': user_qs[0]
+        }
+
+        try:
+            LogModel.objects.create(**log)
+        except Exception as e:
+            print('出错')
+            print(repr(e))
+
+    def formatOperation(self, operation, quantity, area):
+        str = '{operation}{quantity}个{area}UID'
+        if area == 0:
+            return str.format(operation=operation, quantity=quantity, area='国内')
+        else:
+            return str.format(operation=operation, quantity=quantity, area='国外')
+
+
+class DownloadUIDFileView(View):
+
+    @method_decorator(csrf_exempt)
+    def dispatch(self, request, *args, **kwargs):
+        return super(DownloadUIDFileView, self).dispatch(request, *args, **kwargs)
+
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.GET
+        return self.validate(request_dict)
+
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.POST
+        return self.validate(request_dict)
+
+    def validate(self, request_dict):
+        token = request_dict.get('token', None)
+        area = request_dict.get('area', None)
+        quantity = int(request_dict.get('quantity', None))
+        fileType = request_dict.get('fileType', None)
+        order_number = request_dict.get('order_number', None)
+        board = request_dict.get('board', None)
+        plan = request_dict.get('plan', None)
+        checksum = request_dict.get('checksum', None)
+        ic_model = request_dict.get('ic_model', None)
+        order_quantity = request_dict.get('order_quantity', None)
+        response = uidManageResponseObject()
+
+        # print(area)
+        # print(quantity)
+        token = TokenObject(token)
+        if token.code != 0:
+            return response.json(token.code)
+
+        if not area or not order_number or not board or not plan or not checksum or not ic_model or not order_quantity or not fileType:
+            return response.json(444)
+
+        area = int(area)
+
+        if area >= 0 and quantity > 0:
+
+            # 保存订单信息
+            now_time = int(time.time())
+            order = {
+                'order_number': order_number,
+                'board': board,
+                'plan': plan,
+                'checksum': checksum,
+                'ic_model': ic_model,
+                'quantity': order_quantity,
+                'add_time': now_time
+            }
+
+            tmp = OrderTaskModel.objects.create(**order)
+            print(tmp)
+
+            order = OrderTaskModel.objects.filter(order_number=order_number).order_by('-add_time')[0]
+
+            uid_qs = UserUIDModel.objects.filter(user__id=token.userID, uid__status=1, uid__area=area)
+
+            uid_values = uid_qs.values('uid__id', 'uid__uid', 'uid__mac', 'uid__uid_extra', 'uid__add_time', 'uid__update_time', 'uid__area')
+
+            count = uid_values.count()
+            if count < quantity:
+                return response.json(444, '设备UID不足')
+
+            if uid_values.exists():
+
+                uid_values = uid_values[0:quantity]
+                uid_qs = uid_qs[0: quantity]
+                if fileType == 'txt':
+                    # return self.download_txt(uid_values, uid_qs, order)
+                    # return self.download_excel(uid_values, order)
+                    return self.download_zip(uid_values, order)
+                elif fileType == 'excel':
+                    return self.download_excel(uid_values, order)
+                else:
+                    return response.json(444, 'fileType')
+            else:
+                return response.json(444, '111')
+        else:
+            return response.json(444, '222')
+
+    def download_txt(self, uid_values, uid_qs, order):
+        updates = []
+        updates_uid = []
+        content = ''
+        now_time = int(time.time())
+        for i in range(len(uid_values)):
+            # print(item)
+            item = uid_values[i]
+            mac = str(item['uid__mac'])
+            index = mac.rfind(':')
+            tmp = mac[0:index] + '\t' + mac[index:]
+            content += tmp + '\t'
+            content += item['uid__uid'].strip()
+            content += '\r\n'
+            uidModel = UIDModel(
+                id=item['uid__id'],
+                uid=item['uid__uid'],
+                mac=item['uid__mac'],
+                uid_extra=item['uid__uid_extra'],
+                status=2,
+                add_time=item['uid__add_time'],
+                update_time=now_time,
+                area=item['uid__area']
+            )
+            updates.append(uidModel)
+
+            order_uid = OrderUIDModel(uid=uidModel, order=order, add_time=now_time, update_time=now_time)
+            updates_uid.append(order_uid)
+
+            if len(updates) % 5000 == 0:
+                UIDModel.objects.bulk_update(updates, fields=["status"])
+                OrderUIDModel.objects.bulk_create(updates_uid)
+                updates.clear()
+                updates_uid.clear()
+            # print(item['uid__uid'])
+
+        if len(updates) > 0:
+            UIDModel.objects.bulk_update(updates, fields=["status"])
+            OrderUIDModel.objects.bulk_create(updates_uid)
+            updates.clear()
+            updates_uid.clear()
+
+        del updates
+        del updates_uid
+        content = content[0:len(content) - 1]
+        response = StreamingHttpResponse(content)
+        response['Content-Type'] = 'application/octet-stream'
+        response['Content-Disposition'] = 'attachment;filename=UID'+time.strftime('-%Y-%m-%d-%H-%M-%S', time.localtime()) + '.txt'
+        return response
+
+    def download_excel(self, uid_qs, order):
+        response = HttpResponse(content_type='application/vnd.ms-excel')
+        response['Content-Disposition'] = 'attachment; filename=UID' + time.strftime('-%Y-%m-%d-%H-%M-%S',
+                                                                                     time.localtime()) + '.xls'
+        workbook = xlwt.Workbook(encoding='utf-8')
+        sheet1 = workbook.add_sheet('UID')
+        # row1 = [u'设备UID']
+        # for i in range(0, len(row1)):
+        #     sheet1.write(0, i, row1[i])
+
+        num = 1
+        updates = []
+        updates_uid = []
+        now_time = int(time.time())
+        for item in uid_qs:
+            uid = item['uid__uid']
+            mac = item['uid__mac']
+            index = mac.rfind(':')
+            sheet1.write(num, 0, mac[0:index])
+            sheet1.write(num, 1, mac[index:])
+            sheet1.write(num, 2, uid)
+            num += 1
+            uidModel = UIDModel(
+                id=item['uid__id'],
+                uid=item['uid__uid'],
+                mac=item['uid__mac'],
+                uid_extra=item['uid__uid_extra'],
+                status=2,
+                add_time=item['uid__add_time'],
+                update_time=now_time,
+                area=item['uid__area']
+            )
+            updates.append(uidModel)
+
+            order_uid = OrderUIDModel(uid=uidModel, order=order, add_time=now_time, update_time=now_time)
+            updates_uid.append(order_uid)
+
+            if len(updates) % 5000 == 0:
+                UIDModel.objects.bulk_update(updates, fields=["status"])
+                OrderUIDModel.objects.bulk_create(updates_uid)
+                updates.clear()
+                updates_uid.clear()
+            # print(item['uid__uid'])
+
+        if len(updates) > 0:
+            UIDModel.objects.bulk_update(updates, fields=["status"])
+            OrderUIDModel.objects.bulk_create(updates_uid)
+            updates.clear()
+            updates_uid.clear()
+
+        UIDModel.objects.bulk_update(updates, fields=["status"])
+        workbook.save(response)
+        return response
+
+    def download_zip(self, uid_qs, order):
+        dir_name = 'static/' + time.strftime('%Y_%m_%d_%H_%M_%S', time.localtime())
+        path = '/'.join((BASE_DIR, dir_name)).replace('\\', '/') + '/'
+        if not os.path.exists(path):
+            os.mkdir(path)
+
+        filename = time.strftime('_%Y_%m_%d_%H_%M_%S', time.localtime())
+        txt_filename = 'UID' + filename + '.txt'
+        excel_filename = 'UID' + filename + '.xls'
+
+        txt_file = open(path + txt_filename, 'w+')
+        workbook = xlwt.Workbook(encoding='utf-8')
+        sheet1 = workbook.add_sheet('UID')
+        num = 1
+
+        updates = []
+        updates_uid = []
+        content = ''
+        now_time = int(time.time())
+        for i in range(len(uid_qs)):
+            # print(item)
+            item = uid_qs[i]
+            uid = item['uid__uid']
+            mac = item['uid__mac']
+            index = mac.rfind(':')
+            tmp = mac[0:index] + '\t' + mac[index:]
+            content += tmp + '\t'
+            content += item['uid__uid'].strip()
+            content += '\r\n'
+
+            sheet1.write(num, 0, mac[0:index])
+            sheet1.write(num, 1, mac[index:])
+            sheet1.write(num, 2, uid)
+            num += 1
+
+            uidModel = UIDModel(
+                id=item['uid__id'],
+                uid=item['uid__uid'],
+                mac=item['uid__mac'],
+                uid_extra=item['uid__uid_extra'],
+                status=2,
+                add_time=item['uid__add_time'],
+                update_time=now_time,
+                area=item['uid__area']
+            )
+            updates.append(uidModel)
+
+            order_uid = OrderUIDModel(uid=uidModel, order=order, add_time=now_time, update_time=now_time)
+            updates_uid.append(order_uid)
+
+            if len(updates) % 5000 == 0:
+                UIDModel.objects.bulk_update(updates, fields=["status"])
+                OrderUIDModel.objects.bulk_create(updates_uid)
+                updates.clear()
+                updates_uid.clear()
+            # print(item['uid__uid'])
+
+        if len(updates) > 0:
+            UIDModel.objects.bulk_update(updates, fields=["status"])
+            OrderUIDModel.objects.bulk_create(updates_uid)
+            updates.clear()
+            updates_uid.clear()
+
+        del updates
+        del updates_uid
+        content = content[0:len(content) - 1]
+        txt_file.write(content)
+        txt_file.close()
+
+        workbook.save(path + excel_filename)
+
+        zip_name = path[0:path.rfind('/')] + '.zip'
+        return self.get_zip(path, os.listdir(path), zip_name)
+
+    def get_zip(self, path, files, zip_name):
+        zp = zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED)
+        for file in files:
+            zp.write(filename=(path + file), arcname=str(file))
+        zp.close()
+
+        response = StreamingHttpResponse(open(zip_name, 'rb'))
+        response['content_type'] = "application/octet-stream"
+        response['Content-Disposition'] = 'attachment; filename=UID' + time.strftime('_%Y_%m_%d_%H_%M_%S',
+                                                                                     time.localtime()) + '.zip'
+        return response
+

+ 402 - 0
Controller/HistoryUIDController.py

@@ -0,0 +1,402 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import json
+import logging
+import time
+
+from django.db import transaction
+from django.http import StreamingHttpResponse
+from django.utils.decorators import method_decorator
+from django.views import View
+from django.views.decorators.csrf import csrf_exempt
+from django.db.models import Avg,Max,Min,Count,Sum, Q  #   引入函数
+
+from Model.models import UIDModel, UserModel, UserUIDModel, HistoryUIDModel
+from Object.RedisObject import RedisObject
+from Object.uidManageResponseObject import uidManageResponseObject
+from Object.TokenObject import TokenObject
+from Service.ModelService import ModelService
+
+
+class HistoryUIDView(View):
+
+    @method_decorator(csrf_exempt)
+    def dispatch(self, request, *args, **kwargs):
+        return super(HistoryUIDView, self).dispatch(request, *args, **kwargs)
+
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.GET
+        operation = kwargs.get('operation')
+        return self.validate(request_dict, operation)
+
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.POST
+        operation = kwargs.get('operation')
+        return self.validate(request_dict, operation)
+
+    def validate(self, request_dict, operation):
+        token = request_dict.get('token', None)
+        response = uidManageResponseObject()
+
+        token = TokenObject(token)
+        if token.code != 0:
+            return response.json(token.code)
+
+        if operation == 'quantity':
+            return self.do_quantity(request_dict, response)
+        elif operation == 'remove':
+            return self.do_remove(request_dict, response)
+        elif operation == 'download':
+            return self.download_txt(token, response)
+        elif operation == 'list':
+            return self.do_list(request_dict, response)
+        elif operation == 'delete':
+            return self.do_delete(token.userID, request_dict, response)
+        elif operation == 'batchDelete':
+            return self.do_batch_delete(token.userID, request_dict, response)
+        elif operation == 'adminUpdate':
+            return self.do_admin_update(token.userID, request_dict, response)
+        else:
+            return response.json(309)
+
+    # 查询当前可用的UID的数量
+    def do_quantity(self, request_dict, response):
+        token = request_dict.get('token', None)
+
+        token = TokenObject(token)
+        if token.code != 0:
+            return response.json(token.code)
+
+        user_qs = UserModel.objects.filter(id=token.userID)
+        if user_qs.exists():
+            user = user_qs[0]
+            if user.permission == '0':
+                return self.do_admin_quantity(request_dict, response, user.username)
+            else:
+                return self.do_not_admin_quantity(request_dict, response, user.username)
+        else:
+            return response.json(9)
+
+    # 管理员的查询UID数量操作
+    def do_admin_quantity(self, request_dict, response, admin):
+        datas = []
+        domestic = HistoryUIDModel.objects.filter(area=0, status=0).count()
+        foreign = HistoryUIDModel.objects.filter(area=1, status=0).count()
+        item = {}
+        item['isAdmin'] = 1
+        item['domestic'] = domestic
+        item['foreign'] = foreign
+        item['username'] = admin
+        datas.append(item)
+
+        user_qs = UserModel.objects.filter(~Q(Q(permission='0')))
+        for user in user_qs:
+            item = {'isAdmin': 0}
+            result = UserUIDModel.objects.filter(user__id=user.id, uid__status=1, uid__area=0).aggregate(num=Count('uid__status'))
+            item['domestic'] = result['num']
+            result = UserUIDModel.objects.filter(user__id=user.id, uid__status=1, uid__area=1).aggregate(num=Count('uid__status'))
+            item['foreign'] = result['num']
+            item['username'] = user.username
+            datas.append(item)
+
+        return response.json(0, {'data': datas})
+
+    # 非管理员的查询UID数量操作
+    def do_not_admin_quantity(self, request_dict, response, username):
+        user_qs = UserModel.objects.filter(username=username)
+        if user_qs.exists():
+            user = user_qs[0]
+            datas = []
+            item = {'isAdmin': 0}
+            result = UserUIDModel.objects.filter(user__id=user.id, uid__status=1, uid__area=0).aggregate(num=Count('uid__status'))
+            item['domestic'] = result['num']
+            result = UserUIDModel.objects.filter(user__id=user.id, uid__status=1, uid__area=1).aggregate(num=Count('uid__status'))
+            item['foreign'] = result['num']
+            item['username'] = user.username
+            datas.append(item)
+            return response.json(0, {'data': datas})
+        else:
+            return response.json(444)
+
+    # 分配UID
+    @transaction.atomic
+    def do_allot(self, request_dict, response):
+        username = request_dict.get('username', None)
+        quantity = int(request_dict.get('quantity', None))
+        area = request_dict.get('area', None)
+        token = request_dict.get('token', None)
+
+        token = TokenObject(token)
+        if token.code != 0:
+            return response.json(token.code)
+        user = UserModel.objects.get(id=token.userID)
+
+        if not user or '0' not in user.permission:
+            return response.json(404)
+
+        # 要分配的对象
+        allot_user_qs = UserModel.objects.filter(username=username)
+        if not allot_user_qs.exists():
+            return response.json(444, 'username')
+
+        # 取出对应区域可用的UID分配给allot_user
+        uid_qs = HistoryUIDModel.objects.filter(area=area, status=0)
+        count = uid_qs.count()
+        if count < quantity:
+            return response.json(444, '设备UID不足')
+
+        updates = []
+        datas = []
+        count = 0
+        if uid_qs.exists():
+            uid_qs = uid_qs[0:quantity]
+            now_time = int(time.time())
+            savePoint = transaction.savepoint()
+            for item in uid_qs:
+                item.status = 1
+                item.update_time = time.time()
+                user_uid = UserUIDModel()
+                user_uid.uid = item
+                user_uid.user = allot_user_qs[0]
+                user_uid.add_time = now_time
+                user_uid.update_time = now_time
+                datas.append(user_uid)
+                updates.append(item)
+
+                if len(datas) % 5000 == 0:
+                    result = self.do_update(datas, updates, savePoint)
+                    if result != 0:
+                        return response.json(result)
+
+            if len(datas) > 0:
+                result = self.do_update(datas, updates, savePoint)
+                if result != 0:
+                    return response.json(result)
+            redisObject = RedisObject()
+            values = uid_qs.values('uid')
+            print(values)
+            redisObject.set_data(key=token.token, val=json.dumps(list(values)), expire=3600)
+            del datas
+            del updates
+            return response.json(0)
+        else:
+            return response.json(444)
+
+    def do_update(self, datas, updates, savePoint, count=0):
+        try:
+            try:
+                if count == 2:
+                    raise Exception("Invalid level!")
+                UserUIDModel.objects.bulk_create(datas)
+                HistoryUIDModel.objects.bulk_update(updates, fields=['status', 'update_time'])
+                datas.clear()
+                updates.clear()
+            except Exception as e:
+                if savePoint:
+                    transaction.savepoint_rollback(savePoint)
+                djangoLogger = logging.getLogger('django')
+                djangoLogger.exception(repr(e))
+                return 174
+        except Exception as e:
+            return 174
+        return 0
+
+    # 把UID表中的数据移动到HistoryUID表中
+    def do_remove(self, request_dict, response):
+        token = TokenObject(request_dict.get('token', None))
+        id = request_dict.get('id', None)
+        start = request_dict.get('start', None)
+        stop = request_dict.get('stop', None)
+
+        if token.code != 0:
+            return response.json(token.code)
+
+        # 通过userID查找用户,判断是否是管理员
+        user_qs = UserModel.objects.filter(id=token.userID)
+        if user_qs.exists():
+            user = user_qs[0]
+            if user.permission != '0':
+                return response.json(404)
+        else:
+            return response.json(9)
+
+        if id:
+            return self.do_remove_by_id(id, response)
+        elif start and stop:
+            return self.do_bulk_remove(int(start), int(stop), response)
+        else:
+            return response.json(444, 'id,start,stop')
+
+    # 移除单条UID记录,id:记录id
+    def do_remove_by_id(self, id, response):
+        id = int(id)
+        uid_qs = HistoryUIDModel.objects.filter(id=id)
+        if not uid_qs.exists():
+            return response.json(173)
+
+        uid = uid_qs[0]
+        if uid:
+            data = {
+                'uid': uid.uid,
+                'uid_extra': uid.uid_extra,
+                'status': uid.status,
+                'add_time': uid.add_time,
+                'update_time': uid.update_time,
+                'area': uid.area
+            }
+            HistoryUIDModel.objects.create(**data)
+            uid.delete()
+            return response.json(0)
+        else:
+            return response.json(444, 'id')
+
+    # 批量移除UID记录。start:开始的UID记录的id;stop:结束的UID记录的id
+    def do_bulk_remove(self, start, stop, response):
+        uid_qs = UIDModel.objects.filter(id__range=(start, stop))
+        histories = []
+        if uid_qs.exists():
+            for item in uid_qs:
+                histories.append(HistoryUIDModel(
+                    uid=item.uid,
+                    uid_extra=item.uid_extra,
+                    status=item.status,
+                    add_time=item.add_time,
+                    update_time=item.update_time,
+                    area=item.area
+                ))
+                if len(histories) % 5000 == 0:
+                    HistoryUIDModel.objects.bulk_create(histories)
+                    histories.clear()
+            if len(histories) > 0:
+                HistoryUIDModel.objects.bulk_create(histories)
+                histories.clear()
+            uid_qs.delete()
+            return response.json(0)
+        else:
+            return response.json(173)
+
+    def download_txt(self, token, response):
+
+        redisObject = RedisObject()
+        uid_qs = redisObject.get_data(key=token.token)
+
+        if uid_qs is False:
+            return response.json(308)
+
+        uid_qs = json.loads(uid_qs)
+        content = ''
+        for item in uid_qs:
+            # print(item)
+            content += item['uid']
+            content += '\r\n'
+
+        redisObject.del_data(key=token.token)
+
+        content = content[0:len(content) - 1]
+        response = StreamingHttpResponse(content)
+        response['Content-Type'] = 'application/octet-stream'
+        filename = 'uid_need_to_set_up_push.txt'
+        response['Content-Disposition'] = 'attachment;filename=' + filename
+
+        return response
+
+    def do_list(self, request_dict, response):
+        page = request_dict.get('page', None)
+        line = request_dict.get('limit', None)
+        status = request_dict.get('status', None)
+        area = request_dict.get('area', None)
+        start_time = request_dict.get('starttime', None)
+        stop_time = request_dict.get('endtime', None)
+        uid = request_dict.get('uid', None)
+
+        if page and line:
+
+            uid_qs = HistoryUIDModel.objects.filter()
+            res = {
+                'count': 0,
+                'data': []
+            }
+
+            if uid_qs.exists():
+                page = int(page)
+                line = int(line)
+
+                start = (page - 1) * line
+                end = start + line
+
+                if uid:
+                    uid_qs = uid_qs.filter(uid=uid)
+
+                if status:
+                    uid_qs = uid_qs.filter(status=status)
+
+                if area:
+                    uid_qs = uid_qs.filter(area=area)
+
+                if start_time:
+                    uid_qs = uid_qs.filter(update_time__gte=start_time)
+
+                if stop_time:
+                    if stop_time > start:
+                        uid_qs = uid_qs.filter(update_time__lte=stop_time)
+
+                res['count'] = uid_qs.count()
+                uid_qs = uid_qs.values()[start:end]
+
+                res['data'] = list(uid_qs)
+
+            print(res)
+            return response.json(0, res)
+        else:
+            return response.json(444)
+
+    def do_delete(self, userID, request_dict, response):
+        uid = request_dict.get('uid', None)
+        user_qs = UserModel.objects.filter(id=userID)
+
+        if user_qs.exists():
+            user = user_qs[0]
+            if int(user.permission) != 0:
+                return response.json(309)
+
+            HistoryUIDModel.objects.filter(uid=uid).delete()
+            return response.json(0)
+        else:
+            return response.json(309)
+
+    def do_batch_delete(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        uids = request_dict.get('uidlist', None)
+
+        if uids:
+            uids = json.loads(uids)
+            HistoryUIDModel.objects.filter(uid__in=uids).delete()
+            return response.json(0)
+        else:
+            return response.json(444)
+
+    def do_admin_update(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        uid = request_dict.get('uid', None)
+        content = request_dict.get('content', None)
+
+        if uid and content:
+            content = json.loads(content)
+            print(content)
+            content['update_time'] = int(time.time())
+            uid_qs = HistoryUIDModel.objects.filter(uid=uid)
+            if uid_qs.exists():
+                uid_qs.update(**content)
+                return response.json(0)
+            else:
+                return response.json(173)
+        else:
+            return response.json(444)

+ 111 - 0
Controller/IotCoreController.py

@@ -0,0 +1,111 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import hashlib
+import json
+import time
+import uuid
+
+import boto3
+from django.views import View
+
+from Controller.DeviceConfirmRegion import Device_Region
+from Model.models import Device_User, Device_Info, iotdeviceInfoModel, UIDCompanySerialModel, \
+    SerialNumberModel
+from Object.IOTCore.IotObject import IOTClient
+from Object.ResponseObject import ResponseObject
+from Service.CommonService import CommonService
+
+
+class IotCoreView(View):
+
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.GET
+        operation = kwargs.get('operation', None)
+        return self.validate(operation, request_dict, request)
+
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.POST
+        operation = kwargs.get('operation', None)
+        return self.validate(operation, request_dict, request)
+
+    def validate(self, operation, request_dict, request):
+
+        response = ResponseObject()
+
+        if operation == 'createKeysAndCertificate':
+            return self.create_keys_and_certificate(request_dict, response, request)
+        else:
+            return response.json(404)
+
+
+    # CVM注册  :正使用
+    def create_keys_and_certificate(self, request_dict, response, request):
+        serial_number = request_dict.get('serial_number', None)
+        serial_number_code = request_dict.get('serial_number_code', None)
+        token = request_dict.get('token', None)
+        time_stamp = request_dict.get('time_stamp', None)
+        device_version = request_dict.get('device_version', None).replace('.', '_') # 物品组命名不能包含'.'
+        language = request_dict.get('language', None)
+
+        if serial_number and token and time_stamp and serial_number_code and device_version and language:
+            uid_code = CommonService.decode_data(serial_number_code)
+            token = int(CommonService.decode_data(token))
+            time_stamp = int(time_stamp)
+
+            now_time = int(time.time())
+            distance = now_time - time_stamp
+            thingGroup = device_version + '_' + language
+
+            # if token != time_stamp and distance > 600: 暂时去掉延时
+            # if token != time_stamp or serial_number != serial_number_code :
+            #     return response.json(404)
+
+            serial = serial_number[0:6]
+
+            iotqs = iotdeviceInfoModel.objects.filter(serial_number__serial_number=serial)
+
+            # 判断设备是否已注册证书
+            if not iotqs.exists():
+                ip = CommonService.get_ip_address(request)
+                region_id = Device_Region().get_device_region(ip)
+
+                iotClient = IOTClient(region_id)
+                res = iotClient.create_keys_and_certificate(serial_number, thingGroup)
+                nowTime = int(time.time())
+                token_iot_number = hashlib.md5((str(uuid.uuid1()) + str(nowTime)).encode('utf-8')).hexdigest()
+
+                sn = SerialNumberModel.objects.get(serial_number=serial)
+
+                iotdeviceInfoModel.objects.create(serial_number=sn,
+                                                  endpoint=res[0]['endpoint'],
+                                                  certificate_id=res[0]['certificateId'],
+                                                  certificate_pem=res[0]['certificatePem'],
+                                                  public_key=res[0]['publicKey'],
+                                                  private_key=res[0]['privateKey'],
+                                                  thing_name=res[1]['ThingName'],
+                                                  token_iot_number=token_iot_number
+                                                  )
+                res = {
+                    'certificateId': res[0]['certificateId'],
+                    'certificatePem': res[0]['certificatePem'],
+                    'publicKey': res[0]['publicKey'],
+                    'privateKey': res[0]['privateKey'],
+                    'endpoint': res[0]['endpoint']
+                }
+                return response.json(0, {'res': res})
+            else:
+
+                iot = iotqs[0]
+                res = {
+                    'certificateId': iot.certificate_id,
+                    'certificatePem': iot.certificate_pem,
+                    'publicKey': iot.public_key,
+                    'privateKey': iot.private_key,
+                    'endpoint': iot.endpoint
+                }
+                # print('此设备已注册证书')
+                return response.json(0, {'res': res})
+        else:
+            return response.json(444)

+ 97 - 0
Controller/LanguageController.py

@@ -0,0 +1,97 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import time
+
+from django.views import View
+
+from Model.models import LanguageModel
+from Object.uidManageResponseObject import uidManageResponseObject
+from Object.TokenObject import TokenObject
+from Service.ModelService import ModelService
+
+
+class LanguageView(View):
+
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation', None)
+        request_dict = request.GET
+        return self.validate(request_dict, operation)
+
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation', None)
+        request_dict = request.POST
+        return self.validate(request_dict, operation)
+
+    def validate(self, request_dict, operation):
+        token = TokenObject(request_dict.get('token', None))
+
+        response = uidManageResponseObject()
+
+        if token.code != 0:
+            return response.json(token.code)
+
+        if operation == 'add':
+            return self.do_add(token.userID, request_dict, response)
+        elif operation == 'update':
+            return self.do_update(token.userID, request_dict, response)
+        elif operation == 'getLanguage':
+            return self.do_get(request_dict, response)
+        else:
+            return response.json(404)
+
+    def do_add(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        lang = request_dict.get('lang', None)
+        lang_youdao = request_dict.get('lang_youdao', None)
+
+        if lang:
+            now_time = int(time.time())
+
+            language = LanguageModel(lang=lang, lang_youdao=lang_youdao, add_time=now_time, update_time=now_time)
+            language.save()
+            return response.json(0)
+        else:
+            return response.json(444)
+
+    def do_update(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        id = request_dict.get('id', None)
+        if id:
+            lang = request_dict.get('lang', None)
+            lang_youdao = request_dict.get('lang_youdao', None)
+
+            update = {
+
+            }
+            if lang:
+                update['lang'] = lang
+
+            if lang_youdao:
+                update['lang_youdao'] = lang_youdao
+
+            LanguageModel.objects.filter(id=id).update(**update)
+            return response.json(0)
+        else:
+            return response.json(444)
+
+    def do_get(self, request_dict, response):
+        type = request_dict.get('type', None)
+
+        if type:
+            lang_qs = LanguageModel.objects.filter(lang=type)
+            if lang_qs.exists():
+                lang = lang_qs.values('id', 'lang', 'lang_youdao')
+
+                return response.json(0, lang)
+            else:
+                return response.json(173)
+        else:
+            return response.json(444)

+ 99 - 0
Controller/LogController.py

@@ -0,0 +1,99 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+from django.utils.decorators import method_decorator
+from django.views import View
+from django.views.decorators.csrf import csrf_exempt
+
+from Model.models import LogModel
+from Object.uidManageResponseObject import uidManageResponseObject
+from Object.TokenObject import TokenObject
+
+
+class LogView(View):
+
+    @method_decorator(csrf_exempt)
+    def dispatch(self, request, *args, **kwargs):
+        return super(LogView, self).dispatch(request, *args, **kwargs)
+
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.GET
+        operation = kwargs.get('operation')
+        return self.validate(request_dict, operation)
+
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.POST
+        operation = kwargs.get('operation')
+        return self.validate(request_dict, operation)
+
+    def validate(self, request_dict, operation):
+        token = TokenObject(request_dict.get('token', None))
+        response = uidManageResponseObject()
+
+        if token.code != 0:
+            return response.json(token.code)
+
+        if operation == 'query':
+            return self.do_query(request_dict, token, response)
+        elif operation == 'queryAll':
+            return self.do_query_all(request_dict, token, response)
+        elif operation == 'delete':
+            return self.do_delete(request_dict, response)
+        elif operation == 'adminQuery':
+            return self.do_admin_query(request_dict, token, response)
+        else:
+            return response.json(404)
+
+    def do_query(self, request_dict, token: TokenObject, response):
+        page = request_dict.get('page', None)
+        line = request_dict.get('line', None)
+
+        if page and line:
+            log_qs = LogModel.objects.filter(user__id=token.userID).values('id', 'operation', 'time', 'ip', 'user__username')
+            if log_qs.exists():
+                page = int(page)
+                line = int(line)
+                start = (page - 1) * line
+                count = log_qs.count()
+                data = log_qs[start:(start + line)]
+                return response.json(0, {'count': count, 'data': list(data)})
+            else:
+                return response.json(0, {'count': 0, 'data': []})
+        else:
+            return response.json(444)
+
+    def do_query_all(self, request_dict, token: TokenObject, response: uidManageResponseObject):
+        log_qs = LogModel.objects.filter(user__id=token.userID).values('id', 'operation', 'time', 'ip')
+        if log_qs.exists():
+            count = log_qs.count()
+            return response.json(0, {'count': count, 'data': list(log_qs)})
+        else:
+            return response.json(0, {'count': 0, 'data': []})
+
+    def do_delete(self, request_dict, response):
+        id = request_dict.get('id', None)
+
+        if id:
+            LogModel.objects.filter(id=id).delete()
+            return response.json(0)
+        else:
+            return response.json(444)
+
+    def do_admin_query(self, request_dict, token: TokenObject, response):
+        page = request_dict.get('page', None)
+        line = request_dict.get('limit', None)
+
+        if page and line:
+            log_qs = LogModel.objects.filter().values('id', 'operation', 'time', 'ip', 'user__username')
+            if log_qs.exists():
+                page = int(page)
+                line = int(line)
+                start = (page - 1) * line
+                count = log_qs.count()
+                data = log_qs[start:(start + line)]
+                return response.json(0, {'count': count, 'data': list(data)})
+            else:
+                return response.json(0, {'count': 0, 'data': []})
+        else:
+            return response.json(444)

+ 80 - 9
Controller/OTAEquipment.py

@@ -479,7 +479,7 @@ def getNewVerInterface(request):
     now_ver = request_dict.get('ver', None)
     uid = request_dict.get('uid', None)
     if not code or not now_ver:
-        return response.json(902, {'param': 'code,ver'})
+        return response.json(902, {'param':'code,ver'})
         # return response.json(444, 'code,ver')
     tko = TokenObject(token)
     response.lang = tko.lang
@@ -494,7 +494,7 @@ def getNewVerInterface(request):
 
     if equipmentValid.exists():
         equipment = equipmentValid[0]
-        redisObject = RedisObject(db=3)
+        redisObject = RedisObject()
         key = 'limit_{eid}'.format(eid=equipment.eid)
 
         evl_qs = redisObject.get_data(key=key)
@@ -506,15 +506,15 @@ def getNewVerInterface(request):
                 redisObject.set_data(key=key, val=json.dumps(list(evl_qs.values())), expire=600)
         if evl_qs and len(evl_qs) > 0:
             evl = evl_qs[0]
-            if evl['type'] == 1:  # uid限制
+            if evl['type'] == 1: # uid限制
                 uids = json.loads(evl['content'])
                 if not uids.__contains__(uid):
                     return response.json(902)
-            elif evl['type'] == 2:  # user限制
+            elif evl['type'] == 2: # user限制
                 users = json.loads(evl['content'])
                 if not users.__contains__(tko.userID):
                     return response.json(902)
-            elif evl['type'] == 3:  # 国家地区限制
+            elif evl['type'] == 3: # 国家地区限制
                 countries = json.loads(evl['content'])
                 country_ip_qs = CountryIPModel.objects.filter(user_ex__userID=tko.userID)
                 if country_ip_qs.exists():
@@ -538,10 +538,10 @@ def getNewVerInterface(request):
             #     url = SERVER_DOMAIN + 'dlotapack/' + file_path
             # else:
             #     这里调用国内服务器进行下载,防止下载bug
-            # if code == '18E201200CA' or code == '18E201200CZ':
-            #     url = 'http://www.zositech.xyz/dlotapack/' + file_path
-            # else:
-            #     url = SERVER_DOMAIN + 'dlotapack/' + file_path
+                # if code == '18E201200CA' or code == '18E201200CZ':
+                #     url = 'http://www.zositech.xyz/dlotapack/' + file_path
+                # else:
+                #     url = SERVER_DOMAIN + 'dlotapack/' + file_path
             return response.json(0, {
                 'ver': ver,
                 'url': url,
@@ -685,3 +685,74 @@ def downloadOTAInterfaceV2(request, fullPath, *callback_args, **callback_kwargs)
             return res.json(907)
     else:
         return res.json(444, 'fullPath')
+
+
+@csrf_exempt
+def getDownLoadOTApackUrl(request):
+    # QT获取升级文件的下载链接
+    response = ResponseObject()
+    if request.method == "POST":
+        request_dict = request.POST
+    elif request.method == "GET":
+        request_dict = request.GET
+    else:
+        return response.json(444)
+    deviceType = request_dict.get('deviceType', None)
+    version = request_dict.get('version', None)
+    if not deviceType or not version:
+        return response.json(444, 'deviceType or version')
+    equipmentVersion = Equipment_Version.objects.filter(mci=deviceType, version=version)
+    # 判断是否有该版本存在
+    if not equipmentVersion.exists():
+        return response.json(907)
+    file_path = equipmentVersion[0].filePath
+    if file_path:
+        if file_path.find('static/otapack') != -1:  # 只下载otapack路径下的文件
+            url = SERVER_DOMAIN + 'OTA/downloadsPack/' + file_path  # 复用app下载ota包的方式
+            # SERVER_DOMAIN = 'https://test.dvema.com/'
+            # url = SERVER_DOMAIN + 'OTA/downloadsPack/' + file_path
+            res = {
+                "url": url,
+            }
+            return response.json(0, res)
+        else:
+            return response.json(901)
+    else:
+        return response.json(901)
+
+
+@csrf_exempt
+def checkMaxVersion(request):
+    # QT检查ota设备软件版本是否需要更新
+    response = ResponseObject()
+    if request.method == "POST":
+        request_dict = request.POST
+    elif request.method == "GET":
+        request_dict = request.GET
+    else:
+        return response.json(444)
+    deviceType = request_dict.get('deviceType', None)
+    version = request_dict.get('version', None) # 设备版本:当前版本+设备规格代码
+    lang = request_dict.get('lang', None)   # 'zh-Hans','en'
+    if not deviceType or not version:
+        return response.json(444, 'deviceType or version')
+    now_version = version[1:version.rindex('.')] # 去掉V
+    code = version[version.rindex('.')+1:]
+    equipmentVersion = Equipment_Version.objects.filter(mci=deviceType, code=code, lang=lang, status=1) # order by data_joined
+    # 判断是否有该版本存在
+    if not equipmentVersion.exists():
+        return response.json(907)
+
+    filePath = equipmentVersion[0].filePath
+    softwareVersion = equipmentVersion[0].softwareVersion   # 可用最新版本的版本号
+    maxVersion = equipmentVersion[0].max_ver
+    if now_version >= softwareVersion:
+        # 当前版本大于等于最新版本,不需要更新
+        return response.json(902)
+    url = SERVER_DOMAIN + 'OTA/downloadsPack/' + filePath   # 复用app下载ota包的方式
+    res = {
+        'url': url,
+    }
+    return response.json(0, res)
+
+

+ 77 - 0
Controller/OperatingLogs.py

@@ -0,0 +1,77 @@
+from django.views import View
+from Object.ResponseObject import ResponseObject
+from Model.models import OperatingLogsModel
+from Controller.ProcessInfo import ProcessInfoView
+from Object.TokenObject import TokenObject
+from Object.LogsObject import LogsObject
+
+class OperatingLogsView(View):
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.GET
+        operation = kwargs.get('operation', None)
+        return self.validate(request_dict, operation)
+
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.POST
+        operation = kwargs.get('operation', None)
+        return self.validate(request_dict, operation)
+
+    def validate(self, request_dict, operation):
+        response = LogsObject()
+        # token = request_dict.get('token', None)
+        # tko = TokenObject(token)
+
+        if operation is None:
+            return response.json(444, 'error path')
+        elif operation == 'add_logs':
+            return self.add_logs(request_dict, response)
+        elif operation == 'delete_logs':
+            return self.delete_logs(request_dict, response)
+
+    def add_logs(self, request_dict, response):
+        d = self.get_info(request_dict)
+        if(d['userId'] == ''):
+            return response.json(908)
+        OperatingLogsModel.objects.create(
+            userId=d['userId'],
+            operatingcontent=d['operatingcontent'],
+            operatingtype=d['operatingtype'],
+            is_saveprocessinfo=d['is_saveprocessinfo'],
+            devUid=d['devUid'],
+            userIp=d['userIp'],
+        )
+        if d['is_saveprocessinfo'] == '1':
+            ProcessInfoView.validate(ProcessInfoView(), request_dict, 'add_processinfo')
+        return response.json(0)
+
+    def delete_logs(self, request_dict, response):
+        userId = request_dict.get('userId', None)
+        if userId:
+            OperatingLogsModel.objects.filter(userId=userId).delete()
+            return response.json(0)
+        else:
+            return response.json(444, 'userId is not exist')
+
+
+    def get_info(self, request_dict):
+        userId = request_dict.get('userId', None)
+        operatingcontent = request_dict.get('operatingcontent', None)
+        operatingtype = request_dict.get('operatingtype', None)
+        is_saveprocessinfo = request_dict.get('is_saveprocessinfo', None)
+        devUid = request_dict.get('devUid', None)
+        userIp = request_dict.get('userIp', None)
+        return {
+            'userId': userId,
+            'operatingcontent': operatingcontent,
+            'operatingtype': operatingtype,
+            'is_saveprocessinfo': is_saveprocessinfo,
+            'devUid': devUid,
+            'userIp': userIp,
+        }
+
+
+
+
+

+ 104 - 0
Controller/OrderTaskController.py

@@ -0,0 +1,104 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import json
+
+from django.views import View
+
+from Model.models import OrderTaskModel
+from Object.uidManageResponseObject import uidManageResponseObject
+from Object.TokenObject import TokenObject
+from Service.ModelService import ModelService
+
+
+class OrderTaskView(View):
+
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation', None)
+        request_dict = request.GET
+        return self.validate(request_dict, operation)
+
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation', None)
+        request_dict = request.POST
+        return self.validate(request_dict, operation)
+
+    def validate(self, request_dict, operation):
+
+        token = request_dict.get('token', None)
+
+        response = uidManageResponseObject()
+        token = TokenObject(token)
+
+        if token.code != 0:
+            return response.json(0)
+
+        if operation == 'query':
+            return self.do_query(token.userID, request_dict, response)
+        elif operation == 'update':
+            return self.do_update(token.userID, request_dict, response)
+        elif operation == 'delete':
+            return self.do_delete(token.userID, request_dict, response)
+        else:
+            return response.json(404)
+
+    def do_query(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        page = request_dict.get('page', None)
+        line = request_dict.get('limit', None)
+
+        if page and line:
+
+            order_task_qs = OrderTaskModel.objects.filter()
+            res = {
+                'count': 0,
+                'data': []
+            }
+            if order_task_qs.exists():
+                page = int(page)
+                line = int(line)
+
+                res['count'] = order_task_qs.count()
+                start = (page - 1) * line
+                end = start + line
+
+                order_task_qs = order_task_qs[start:end].values()
+                res['data'] = list(order_task_qs)
+
+            return response.json(0, res)
+        else:
+            return response.json(444)
+
+    def do_update(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        id = request_dict.get('id', None)
+        content = request_dict.get('content', None)
+        print(content)
+
+        if id and content:
+            content = json.loads(content)
+            print(content)
+            OrderTaskModel.objects.filter(id=id).update(**content)
+            return response.json(0)
+        else:
+            return response.json(444)
+
+    def do_delete(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        id = request_dict.get('id', None)
+
+        if id:
+            OrderTaskModel.objects.filter(id=id).delete()
+            return response.json(0)
+        else:
+            return response.json(444)

+ 64 - 0
Controller/ProcessInfo.py

@@ -0,0 +1,64 @@
+from django.views import View
+from Object.ResponseObject import ResponseObject
+from Model.models import ProcessInfoLogsModel
+from Object.TokenObject import TokenObject
+from Object.LogsObject import LogsObject
+
+class ProcessInfoView(View):
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.GET
+        operation = kwargs.get('operation', None)
+        return self.validate(request_dict, operation)
+
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.POST
+        operation = kwargs.get('operation', None)
+        return self.validate(request_dict, operation)
+
+    def validate(self, request_dict, operation):
+        response = LogsObject()
+        # token = request_dict.get('token', None)
+
+        if operation is None:
+            return response.json(444, 'error path')
+        elif operation == 'add_processinfo':
+            return self.add_processinfo(request_dict, response)
+        elif operation == 'delete_processinfo':
+            return self.delete_processinfo(request_dict, response)
+
+    def add_processinfo(self, request_dict, response):
+        d = self.get_info(request_dict)
+        if(d['userId'] == ''):
+            return response.json(908)
+        ProcessInfoLogsModel.objects.create(
+            userId=d['userId'],
+            devUid=d['devUid'],
+            operatingcontent=d['operatingcontent'],
+        )
+        return response.json(0)
+
+    def delete_processinfo(self, request_dict, response):
+        userId = request_dict.get('userId', None)
+        if userId:
+            ProcessInfoLogsModel.objects.filter(userId=userId).delete()
+            return response.json(0)
+        else:
+            return response.json(444, 'userId is not exist')
+
+    def get_info(self, request_dict):
+        devUid = request_dict.get('devUid', None)
+        operatingcontent = request_dict.get('operatingcontent', None)
+        operatingtime = request_dict.get('operatingtime', None)
+        userId = request_dict.get('userId', None)
+        return {
+            'devUid': devUid,
+            'operatingcontent': operatingcontent,
+            'operatingtime': operatingtime,
+            'userId': userId,
+        }
+
+
+
+

+ 295 - 0
Controller/RegionController.py

@@ -0,0 +1,295 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import json
+import time
+
+from django.views import View
+
+from Model.models import RegionModel, CountryModel, LanguageModel, CountryLanguageModel
+from Object.uidManageResponseObject import uidManageResponseObject
+from Object.TokenObject import TokenObject
+from Service.CommonService import CommonService
+from Service.ModelService import ModelService
+
+
+class RegionView(View):
+
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation', None)
+        request_dict = request.GET
+        return self.validate(request_dict, operation)
+
+    def post(self, request, *arg, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation', None)
+        request_dict = request.POST
+        return self.validate(request_dict, operation)
+
+    def validate(self, request_dict, operation):
+        token = TokenObject(request_dict.get('token', None))
+
+        response = uidManageResponseObject()
+
+        if operation == 'getCountry':
+            return self.get_country(request_dict, response)
+        else:
+            if token.code != 0:
+                return response.json(token.code)
+
+            if operation == 'add':
+                return self.do_add(token.userID, request_dict, response)
+            elif operation == 'update':
+                return self.do_update(token.userID, request_dict, response)
+            elif operation == 'delete':
+                return self.do_delete(token.userID, request_dict, response)
+            elif operation == 'list':
+                return self.do_list(token.userID, request_dict, response)
+            elif operation == 'addCountry':
+                return self.do_add_country(token.userID, request_dict, response)
+            elif operation == 'updateCountry':
+                return self.do_update_country(token.userID, request_dict, response)
+            elif operation == 'deleteCountry':
+                return self.do_delete_country(token.userID, request_dict, response)
+            elif operation == 'listCountry':
+                return self.do_list_country(token.userID, request_dict, response)
+            else:
+                return response.json(404)
+
+    def do_add(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        name = request_dict.get('region', None)
+
+        if name:
+            region = RegionModel(name=name)
+            region.save()
+
+            return response.json(0)
+        else:
+            return response.json(444)
+
+    def do_update(self,  userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        id = request_dict.get('id', None)
+        name = request_dict.get('region', None)
+
+        if id and name:
+            region_qs = RegionModel.objects.filter(id=id)
+            if region_qs.exists():
+                region = region_qs[0]
+                region.name = name
+                region.save()
+                return response.json(0)
+            else:
+                return response.json(173)
+        else:
+            return response.json(444)
+
+    def do_delete(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        id = request_dict.get('id', None)
+
+        if id:
+            region_qs = RegionModel.objects.filter(id=id)
+            if region_qs.exists():
+                region_qs.delete()
+                return response.json(0)
+            else:
+                return response.json(173)
+        else:
+            return response.json(444)
+
+    def do_list(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        page = request_dict.get('page', None)
+        line = request_dict.get('limit', None)
+
+        if page and line:
+            page = int(page)
+            line = int(line)
+
+            start = (page - 1) * line
+            end = start + line
+
+            region_qs = RegionModel.objects.filter()
+            count = region_qs.count()
+
+            region_qs = region_qs[start: end].values()
+
+            res = {
+                'count': count,
+                'data': list(region_qs)
+            }
+
+            return response.json(0, res)
+        else:
+            return response.json(444)
+
+    def do_add_country(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        number = request_dict.get('number', None)
+        region_id = request_dict.get('region_id', None)
+        countries = request_dict.get('countries', None)
+        countries_en = request_dict.get('countries_en', None)
+
+        if number and region_id and countries:
+            res = {
+                '1': countries,
+                '2': countries_en
+            }
+            now_time = int(time.time())
+            # countries = json.loads(countries)
+
+            country_qs =CountryModel.objects.filter(number=number)
+            if not country_qs.exists():
+                country = CountryModel(number=number, region_id=region_id, add_time=now_time, update_time=now_time, country_name=countries)
+                country.save()
+            else:
+                country = country_qs[0]
+
+            for item in res:
+                country_language_qs = CountryLanguageModel.objects.filter(language_id=item, country_id=country.id)
+                if not country_language_qs.exists():
+                    countryLanguage = CountryLanguageModel(
+                        country_name=res[item], language_id=item, country_id=country.id, add_time=now_time, update_time=now_time)
+                    countryLanguage.save()
+            return response.json(0)
+        else:
+            return response.json(444)
+
+    def do_update_country(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        id = request_dict.get('country_id', None)
+        number = request_dict.get('number', None)
+        region_id = request_dict.get('region_id', None)
+        countries = request_dict.get('countries', None)
+
+        if id and number and region_id and countries:
+
+            country_qs = CountryModel.objects.filter(id=id)
+            if not country_qs.exists():
+                return response.json(173)
+
+            now_time = int(time.time())
+            countries = json.loads(countries)
+            country = {
+                'number': number,
+                'region_id': region_id,
+                'update_time': now_time,
+            }
+
+            country_qs.update(**country)
+
+            return response.json(0)
+        else:
+            return response.json(444)
+
+    def do_delete_country(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        id = request_dict.get('id', None)
+
+        if id:
+            country_qs = CountryModel.objects.filter(id=id)
+            if country_qs.exists():
+                country_qs.delete()
+                return response.json(0)
+            else:
+                return response.json(173)
+        else:
+            return response.json(444)
+
+    def do_list_country(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        region_id = request_dict.get('region_id', None)
+        page = request_dict.get('page', None)
+        line = request_dict.get('limit', None)
+
+        if page and line:
+            page = int(page)
+            line = int(line)
+
+            start = (page - 1) * line
+            end = start + line
+
+            region_qs = CountryLanguageModel.objects.filter(language_id=1)
+            if region_id:
+                region_qs = region_qs.filter(country__region__id=region_id)
+
+            count = region_qs.count()
+
+            if region_qs.exists():
+                region_qs = region_qs[start: end].values('country_id', 'country_name', 'country__number', 'country__region__name', 'add_time', 'update_time')
+            else:
+                region_qs = []
+            res = {
+                'count': count,
+                'data': list(region_qs)
+            }
+
+            return response.json(0, res)
+        else:
+            return response.json(444)
+
+    def get_country(self, request_dict, response):
+        type = request_dict.get('type', None)
+        token = request_dict.get('token', None)
+        time_stamp = request_dict.get('time_stamp', None)
+
+        if token and time_stamp and type:
+            token = int(CommonService.decode_data(token))
+            time_stamp = int(time_stamp)
+
+            now_time = int(time.time())
+            distance = now_time - time_stamp
+
+            if token != time_stamp or distance > 30000 or distance < 0:
+                return response.json(404)
+
+            lang_qs = LanguageModel.objects.filter(lang=type)
+
+            if not lang_qs.exists():
+                lang_qs = LanguageModel.objects.filter(lang='en')
+
+            lang = lang_qs[0]
+            country_qs = CountryLanguageModel.objects.filter(language_id=lang.id).values('country_name', 'country__number')
+
+            return response.json(0, list(country_qs))
+        else:
+            return response.json(444)
+
+    def get_country_info(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        country_number = request_dict.get('country_number', None)
+
+        if country_number:
+            country_language_qs = CountryLanguageModel.objects.filter(country__number=country_number)
+            if country_language_qs.exists():
+                country_language_qs = country_language_qs
+        pass

+ 46 - 0
Controller/RegionCountryController.py

@@ -0,0 +1,46 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import time
+
+from django.views import View
+
+from Model.models import Device_User
+from Object.ResponseObject import ResponseObject
+from Object.TokenObject import TokenObject
+
+class RegionCountryView(View):
+
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation', None)
+        request_dict = request.GET
+        return self.validate(request_dict, operation)
+
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation', None)
+        request_dict = request.POST
+        return self.validate(request_dict, operation)
+
+    def validate(self, request_dict, operation):
+        token = TokenObject(request_dict.get('token', None))
+
+        response = ResponseObject()
+
+        if token.code != 0:
+            return response.json(token.code)
+
+        if operation == 'initUserRegion':
+            return self.do_initUserRegion(token.userID, request_dict, response)
+        else:
+            return response.json(404)
+
+    def do_initUserRegion(self, userID, request_dict, response):
+        user = Device_User.objects.get(userID=userID)
+        number = request_dict.get('number', None)
+        if not user:
+            return response.json(309)
+
+        user.region_country=number
+        user.save()
+        return response.json(0)

+ 107 - 0
Controller/SalesController.py

@@ -0,0 +1,107 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import datetime
+import json
+import random
+
+from django.utils.decorators import method_decorator
+from django.views import View
+from django.views.decorators.csrf import csrf_exempt
+
+from Ansjer.config import SALES, ONLINE_DEVICE
+from Object.uidManageResponseObject import uidManageResponseObject
+
+
+class SalesView(View):
+
+    @method_decorator(csrf_exempt)
+    def dispatch(self, request, *args, **kwargs):
+        return super(SalesView, self).dispatch(request, *args, **kwargs)
+
+    def get(self, request, *args, **kwargs):
+        request_dict = request.GET
+        return self.validate(request_dict)
+
+    def post(self, request, *args, **kwargs):
+        request_dict = request.POST
+        return self.validate(request_dict)
+
+    def validate(self, request_dict):
+        year = request_dict.get('year', 0)
+        response = uidManageResponseObject()
+        if year:
+            year = int(year)
+            if year == 0:
+                data = SALES.copy()
+                data[2020] = self.get_last_year_data(SALES[2020])
+                return response.json(0, {'data': self.format_data(data)})
+            elif 2015 < year < 2020:
+                data = {year: SALES[year]}
+                return response.json(0, {'data': self.format_data(data)})
+            elif year == 2020:
+                data = {year: self.get_last_year_data(SALES[year])}
+                return response.json(0, {'data': self.format_data(data)})
+            else:
+                return response.json(444)
+        else:
+            return response.json(444)
+
+    def get_last_year_data(self, data):
+        result = []
+        month = datetime.datetime.now().month
+        print(month)
+        sum = 0
+        for item in data:
+            value = item['value']
+            sale = int(value[0] / 12 * month)
+            sum += sale
+
+        for item in data:
+            tmp = {}
+            tmp['name'] = item['name']
+            value = item['value']
+            sale = int(value[0] / 12 * month)
+            percent = round(sale * 100 / sum, 3)
+
+            tmpValue = []
+            tmpValue.append(sale)
+            tmpValue.append(percent)
+            tmpValue.append(value[2])
+            tmp['value'] = tmpValue
+            result.append(tmp)
+        print(result)
+        return result
+
+    def format_data(self, data: dict):
+        result = []
+        keys = data.keys()
+        for key in keys:
+            tmp = {
+                'time': key,
+                'data': data[key]
+            }
+            result.append(tmp)
+        return result
+
+
+class DeviceOnlineView(View):
+
+    @method_decorator(csrf_exempt)
+    def dispatch(self, request, *args, **kwargs):
+        return super(DeviceOnlineView, self).dispatch(request, *args, **kwargs)
+
+    def get(self, request, *args, **kwargs):
+        request_dict = request.GET
+        return self.validate(request_dict)
+
+    def post(self, request, *args, **kwargs):
+        request_dict = request.POST
+        return self.validate(request_dict)
+
+    def validate(self, request_dict):
+        response = uidManageResponseObject()
+        return response.json(0,{'online': random.randint((0.9 * ONLINE_DEVICE), ONLINE_DEVICE)})
+
+
+
+

+ 390 - 0
Controller/SerialNumberController.py

@@ -0,0 +1,390 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import logging
+import random
+import time
+
+from django.db import transaction
+from django.views import View
+
+from Controller.DeviceConfirmRegion import Device_Region
+from Model.models import SerialNumberModel, CompanySerialModel, UIDCompanySerialModel, CompanyModel, RegionModel, \
+    CountryModel, UIDModel, Device_Info, iotdeviceInfoModel
+from Object.RedisObject import RedisObject
+from Object.uidManageResponseObject import uidManageResponseObject
+from Object.TokenObject import TokenObject
+from Service.AlgorithmService import AlgorithmBaseOn35
+from Service.CommonService import CommonService
+from Service.ModelService import ModelService
+
+
+class SerialNumberView(View):
+
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation', None)
+        request_dict = request.GET
+        return self.validate(request_dict, operation, request)
+
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation', None)
+        request_dict = request.POST
+        return self.validate(request_dict, operation, request)
+
+    def validate(self, request_dict, operation, request):
+        token = TokenObject(request_dict.get('token', None))
+        response = uidManageResponseObject()
+
+        if operation == 'getUID':
+            return self.do_get_uid(request_dict, response)
+        elif operation == 'getSerial':
+            return self.do_get_serial_number(request_dict, response)
+        elif operation == 'attachUID':
+            return self.do_attach_uid(request_dict, response, request)
+        else:
+            if token.code != 0:
+                return response.json(token.code)
+
+            if operation == 'create':
+                return self.do_create(request_dict, response)
+            elif operation == 'list':
+                return self.do_list(token.userID, request_dict, response)
+            elif operation == 'update':
+                return self.do_update(token.userID, request_dict, response)
+            elif operation == 'detachUID':
+                return self.do_detach_uid(token.userID, request_dict, response)
+            else:
+                return response.json(404)
+
+    def do_create(self, request_dict, response):
+        quantity = int(request_dict.get('quantity', None))
+        p2p = int(request_dict.get('p2p', None))
+
+        if not quantity:
+            return response.json(444)
+        start_time = time.strftime('%Y-%m-%d %H:%M:%S')
+        print('start create ' + start_time)
+        tmp = []
+        algorithm = AlgorithmBaseOn35()
+
+        for i in range(quantity):
+            sum = SerialNumberModel.objects.last().id + 1
+            serial_number = algorithm.getLetter(sum)
+            tmp_len = 6 - len(serial_number)
+            # 前面补0
+            for j in range(tmp_len):
+                serial_number = '0' + serial_number
+            data = []
+            now_time = int(time.time())
+            data.append(SerialNumberModel(serial_number=serial_number, add_time=now_time, p2p=p2p))
+            SerialNumberModel.objects.bulk_create(data)
+            data.clear()
+            start_time = time.strftime('%Y-%m-%d %H:%M:%S')
+            print('start create ' + start_time)
+            redis = RedisObject()
+            redis.del_data(key='serial_number_count')
+        return response.json(0)
+
+    # 提供给pc端获取序列号
+    def do_get_serial_number(self, request_dict, response):
+        quantity = request_dict.get('quantity', None)
+        company_id = request_dict.get('company_id', None)
+        token = request_dict.get('token', None)
+        time_stamp = request_dict.get('time_stamp', None)
+        p2p_type = request_dict.get('p2p_type', None)
+
+        if token and time_stamp and quantity and company_id:
+
+            token = int(CommonService.decode_data(token))
+            time_stamp = int(time_stamp)
+
+            now_time = int(time.time())
+            distance = now_time - time_stamp
+
+            if token != time_stamp or distance > 60000 or distance < 0:
+                return response.json(404)
+
+            redisObject = RedisObject()
+            key = 'serial_lock'
+            value = redisObject.lpop(key)
+            count = 0
+            while value is False and count < 5:
+                time.sleep(1)
+                value = redisObject.lpop(key)
+                count += 1
+
+            if count == 5 and value is False:    #暂时注释
+                return response.json(5)
+
+            quantity = int(quantity)
+
+            company_serial_qs = CompanySerialModel.objects.filter(company__secret=company_id, status=0,
+                                                                  serial_number__p2p=p2p_type)
+            if not company_serial_qs.exists():
+                redisObject.rpush(key, value)
+                return response.json(373)
+
+            # 存在对应的企业
+            company_serial_qs = company_serial_qs[0:quantity]
+
+            #company_serial_qs = company_serial_qs.values('id', 'serial_number__serial_number', 'company__mark')
+            data = []
+            ids = []
+            for serial in company_serial_qs:
+                ids.append(serial.id)
+                data.append(serial.serial_number.serial_number + serial.company.mark)
+            CompanySerialModel.objects.filter(id__in=ids).update(status=1)
+            redisObject.rpush(key, value)
+            return response.json(0, data)
+        else:
+            return response.json(444)
+
+    def do_list(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        page = request_dict.get('page', None)
+        line = request_dict.get('limit', None)
+        serial_number = request_dict.get('serial_number', None)
+        status = request_dict.get('status', None)
+
+        if page and line:
+            page = int(page)
+            line = int(line)
+
+            serial_qs = SerialNumberModel.objects.filter().order_by('-id')
+
+            if serial_number:
+                serial_qs = serial_qs.filter(serial_number__contains=serial_number)
+
+            if status:
+                serial_qs = serial_qs.filter(status=status)
+
+            count = serial_qs.count()
+
+            start = (page - 1) * line
+            end = start + line
+
+            serial_qs = serial_qs[start: end].values()
+            res = {
+                'count': count,
+                'data': list(serial_qs)
+            }
+
+            return response.json(0, res)
+        else:
+            return response.json(444)
+
+    @transaction.atomic
+    def do_attach_uid(self, request_dict, response, request):
+        serial_number = request_dict.get('serial_number', None)
+        country_id = request_dict.get('country_id', None)
+        company_id = request_dict.get('company_id', None)
+        token = request_dict.get('token', None)
+        time_stamp = request_dict.get('time_stamp', None)
+
+        if serial_number and len(serial_number) == 9  and company_id:
+
+            token = int(CommonService.decode_data(token))
+            time_stamp = int(time_stamp)
+
+            now_time = int(time.time())
+            distance = now_time - time_stamp
+
+            if token != time_stamp or distance > 60000 or distance < 0:
+                return response.json(404)
+
+            mark = serial_number[6:9]
+            serial = serial_number[0:6]
+
+            savePoint = transaction.savepoint()
+            try:
+                try:
+                    if not country_id :
+                        ip = CommonService.get_ip_address(request)
+                        country_id = Device_Region().get_device_region(ip)
+
+                    # 判断序列号是否已和企业关联
+                    company_serial_qs = CompanySerialModel.objects.filter(company__secret=company_id,
+                                                                          serial_number__serial_number=serial)
+                    if not company_serial_qs.exists():
+                        return response.json(173)
+
+                    # 当序列号已关联UID
+                    company_serial = company_serial_qs[0]
+
+                    if company_serial.status == 0:
+                        # 该序列号未绑定企业
+                        return response.json(173)
+                    elif company_serial.status == 1:
+                        # 确定所在区域
+                        country_qs = CountryModel.objects.filter(number=country_id)
+                        if not country_qs.exists():
+                            return response.json(374)
+
+                        region = country_qs.values('region_id')[0]
+
+                        count = 0
+                        while count < 3:
+                            p2p = SerialNumberModel.objects.filter(serial_number=serial).values('p2p')
+                            print('此序列号的p2p类型:', p2p[0]['p2p'])
+                            uid_qs = UIDModel.objects.filter(vpg__company_id=company_serial.company.id, vpg__region_id=region['region_id'],
+                                                             status=0, p2p_type=p2p[0]['p2p']).order_by('id')[0:10]
+                            # uid_qs:未进行绑定的uid列表
+                            if uid_qs.exists():
+                                uid = uid_qs[0]
+                                # uid.status = 2
+                                # uid.update_time = int(time.time())
+                                result = UIDModel.objects.filter(id=uid.id, status=0).update(**{
+                                    'status': 2, 'update_time': int(time.time())
+                                })
+
+                                if int(result) <= 0:
+                                    count += 1
+                                    continue
+
+                                now_time = int(time.time())
+                                uid_serial = UIDCompanySerialModel(uid_id=uid.id, company_serial_id=company_serial.id,
+                                                                   add_time=now_time, update_time=now_time)
+                                uid_serial.save()
+
+                                company_serial.status = 2
+                                company_serial.save()
+
+                                dev = Device_Info.objects.filter(UID=uid.uid)
+                                if dev.exists():
+                                    dev.update(serial_number=serial_number)
+
+                                res = {
+                                    'full_uid_code': CommonService.encode_data(uid.full_uid_code),
+                                    'uid': CommonService.encode_data(uid.uid),
+                                    'mac': CommonService.encode_data(uid.mac),
+                                    'extra': uid.uid_extra
+                                }
+                                return response.json(0, res)
+                            else:
+                                return response.json(375)
+
+                        return response.json(5)
+                    else:
+                        uid_qs = UIDCompanySerialModel.objects.filter(company_serial_id=company_serial.id)
+                        if uid_qs.exists():
+                            uid = uid_qs.values('uid__uid', 'uid__mac', 'uid__uid_extra', 'uid__full_uid_code')[0]
+                            res = {
+                                'full_uid_code': CommonService.encode_data(uid['uid__full_uid_code']),
+                                'uid': CommonService.encode_data(uid['uid__uid']),
+                                'mac': CommonService.encode_data(uid['uid__mac']),
+                                'extra': uid['uid__uid_extra']
+                            }
+                            return response.json(0, res)
+                        else:
+                            return response.json(173)
+                except Exception as e:
+                    # print('--------------------------error 5000')
+                    # print(repr(e))
+                    if savePoint:
+                        transaction.rollback(savePoint)
+                    djangoLogger = logging.getLogger('django')
+                    djangoLogger.exception(repr(e))
+                    return response.json(176, str(e))
+            except Exception as e:
+                # print('--------------------------error 5001')
+                # print(repr(e))
+                djangoLogger = logging.getLogger('django')
+                djangoLogger.exception(repr(e))
+                return response.json(176, str(e))
+
+        else:
+            return response.json(444)
+
+    def do_get_uid(self, request_dict, response):
+        serial_number = request_dict.get('serial_number', None)
+        token = request_dict.get('token', None)
+        time_stamp = request_dict.get('time_stamp', None)
+
+        if token and time_stamp and serial_number and len(serial_number) == 9:
+
+            token = int(CommonService.decode_data(token))
+            time_stamp = int(time_stamp)
+
+            now_time = int(time.time())
+            distance = now_time - time_stamp
+
+            if token != time_stamp or distance > 300 or distance < 0:
+                return response.json(404)
+
+            mark = serial_number[6:9]
+            serial = serial_number[0:6]
+            uid_company_serial_qs = UIDCompanySerialModel.objects.filter(company_serial__company__mark=mark, company_serial__serial_number__serial_number=serial)
+
+            if uid_company_serial_qs.exists():
+                uid = uid_company_serial_qs.values('uid__uid', 'uid__mac', 'uid__uid_extra')[0]
+
+                res = {
+                    'uid': CommonService.encode_data(uid['uid__uid']),
+                    'mac': CommonService.encode_data(uid['uid__mac']),
+                    'extra': uid['uid__uid_extra']
+                }
+
+                return response.json(0, res)
+            else:
+                return response.json(173)
+        else:
+            return response.json(444)
+
+    def do_detach_uid(self, userID, request_dict, response):
+        serial_number = request_dict.get('serial_number', None)
+
+        if serial_number:
+            serial = serial_number[0:6]
+
+            uid_serial_qs = UIDCompanySerialModel.objects.filter(company_serial__serial_number__serial_number=serial)
+            if uid_serial_qs.exists():
+                uid_serial = uid_serial_qs[0]
+
+                iot = iotdeviceInfoModel.objects.filter(serial_number__serial_number=serial)
+                if iot.exists():
+                    iot.delete()
+
+                company_serial_qs = CompanySerialModel.objects.filter(id=uid_serial.company_serial.id)
+                if company_serial_qs.exists():
+                    company_serial = company_serial_qs[0]
+                    company_serial.status = 1
+                    company_serial.save()
+
+                uid_qs = UIDModel.objects.filter(uid=uid_serial.uid)
+                if uid_qs.exists():
+                    uid = uid_qs[0]
+                    uid.status = 0
+                    uid.save()
+                uid_serial.delete()
+
+                dev = Device_Info.objects.filter(UID=uid.uid)
+                if dev.exists():
+                    dev.update(serial_number='')
+                return response.json(0)
+            else:
+                return response.json(173)
+        else:
+            return response.json(444)
+
+    def do_update(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        id = request_dict.get('id', None)
+        status = request_dict.get('status', None)
+        p2p = request_dict.get('p2p', None)
+
+        if id and status:
+            serial_number_qs = SerialNumberModel.objects.filter(id=id)
+            if serial_number_qs.exists():
+                serial_number_qs.update(**{'status': status, 'p2p': p2p})
+                return response.json(0)
+            else:
+                return response.json(173)
+        else:
+            return response.json(444)

+ 11 - 11
Controller/StatisticsController.py

@@ -157,7 +157,7 @@ def statistcsPushDay(request):
         return response.json(token.code)
 
     current_time = int(time.time())
-    count = int(current_time / (24 * 3600))
+    count = int((current_time + 8 * 3600) / (24 * 3600))
     end_time = count * 24 * 3600 - 8 * 3600
     start_time = end_time - 24 * 3600
     print(start_time)
@@ -204,18 +204,17 @@ def statistcsPushMonth(request):
     if token.code != 0:
         return response.json(token.code)
 
-    localtime = time.localtime()
-    current_month = localtime.tm_mon
-
-    distance_time = 8 * 60 * 60
+    gmtime = time.gmtime(int(time.time()) + 28800)
+    current_month = gmtime.tm_mon - 1
+    # print(current_month)
 
-    time_struct = [localtime.tm_year, localtime.tm_mon, 1, 0, 0, 0, 0, 0, 0]
-    start_time = int(time.mktime(tuple(time_struct)))
-    start_time = start_time - time.timezone - distance_time
+    time_struct = [gmtime.tm_year, current_month, 1, 0, 0, 0, 0, 0, gmtime.tm_isdst]
+    start_time = int(time.mktime(tuple(time_struct))) - 28800
+    # print(start_time)
 
     time_struct[1] = current_month + 1
-    end_time = int(time.mktime(tuple(time_struct)))
-    end_time = end_time - time.timezone - distance_time
+    end_time = int(time.mktime(tuple(time_struct))) - 28800
+    # print(end_time)
 
     eq_qs = EquipmentInfoExStatisticsModel.objects.filter(statistics_date__gte=start_time, statistics_date__lte=end_time, date_type=0)
     # 0:APNS推送,1:谷歌推送,2:极光推送
@@ -231,7 +230,8 @@ def statistcsPushMonth(request):
             do_sum_two(eq, gcm)
         elif eq.push_type == 2:
             do_sum_two(eq, jpush)
-        do_sum_two(eq, total)
+        elif eq.push_type == -1:
+            do_sum_two(eq, total)
     datas = []
     datas.append(apns)
     datas.append(gcm)

+ 2 - 2
Controller/SysManage.py

@@ -104,8 +104,8 @@ def initMsgFunc(request):
     if tko.code == 0:
         userID = tko.userID
         sm_count = SysMsgModel.objects.filter(userID_id=userID, status=0).count()
-        eq_count = Equipment_Info.objects.filter(status=False,userID_id=userID).count()
-        rq_count = Equipment_Info.objects.filter(status=False, eventType=57,userID_id=userID).count()
+        eq_count = Equipment_Info.objects.filter(userID_id=userID).filter(status=False).count()
+        rq_count = Equipment_Info.objects.filter(userID_id=userID).filter(eventType=57, status=False,).count()
         uid_reset_count = Device_Info.objects.filter(userID_id=userID, isExist=2).count()
         res = {
             'sm_count': sm_count,  # 系统消息未读数量

+ 0 - 1
Controller/SysMsg.py

@@ -250,5 +250,4 @@ class SysMsgView(View):
                 return response.json(173)
         else:
             return response.json(444, 'sid')
-
 # 回复记录

+ 71 - 5
Controller/TestApi.py

@@ -21,6 +21,7 @@ import json
 import math
 import time
 import urllib
+import datetime
 from Object.AliPayObject import AliPayObject
 import logging
 import boto3
@@ -29,6 +30,9 @@ from botocore.exceptions import ClientError
 import oss2
 import paypalrestsdk
 import logging
+import requests
+import hashlib
+import hmac
 from aliyunsdkcore import client
 from aliyunsdksts.request.v20150401 import AssumeRoleRequest
 from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
@@ -36,7 +40,6 @@ from django.utils.decorators import method_decorator
 from django.views.decorators.csrf import csrf_exempt
 from django.views.generic.base import View
 from django.contrib.auth.hashers import make_password, check_password  # 对密码加密模块
-
 from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, OSS_ROLE_ARN, SERVER_DOMAIN, PAYPAL_CRD, \
     SERVER_DOMAIN_SSL
 from Model.models import Device_Info, Order_Model, Store_Meal, VodHlsModel, OssCrdModel, UID_Bucket
@@ -50,6 +53,7 @@ from Model.models import Device_User, Device_Info, UID_Bucket, UID_Preview, UidS
 
 
 
+
 SERVER_DOMAIN = 'http://test.dvema.com/'
 ACCESS_KEY = "AKIA2E67UIMD3CYTIWPA"
 SECRET_KEY = "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"
@@ -77,8 +81,8 @@ class testView(View):
         if operation is None:
             return response.json(444, 'error path')
         elif operation == 'tests':
-             res = make_password(123456)
-             return JsonResponse(status=200, data=res,safe=False)
+            res = make_password(123456)
+            return JsonResponse(status=200, data=res,safe=False)
         elif operation == 'cbu':
             return self.createBucket()
         elif operation == 'vodList':
@@ -96,8 +100,17 @@ class testView(View):
         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)
+        elif operation == 'test_request':
+            userID = '158943604783713800138000'
+            return self.testRequest(request,request_dict)
         else:
-            return 12344444
+            return 123
 
     def createBucket(self):
 
@@ -431,7 +444,7 @@ class testView(View):
     def do_get_sign_sts(self, request_dict, ip, response):
         # uid = 'GZL2PEFJPLY7W6BG111A'
         # channel = 2
-        uid = 'VVDHCVBYDKFMJRWA111A'
+        uid = '86YC8Z192VB1VMKU111A'
         channel = 1
         now_time = int(time.time())
         ubqs = UID_Bucket.objects.filter(uid=uid, channel=channel, endTime__gte=now_time). \
@@ -674,4 +687,57 @@ class testView(View):
             vod_play_list.append({'name': vod['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()
+        res = tko.generate(
+            data={'userID': 158943594633713800138000, 'lang': 'cn', 'user': '597471180@qq.com', 'm_code': '123413243214'})
+        #uidToken
+        # utko = UidTokenObject()
+        # res = utko.generate(data={'uid': 'XKWZSC5FCJYT19B7111A','channel': 1})
+        return JsonResponse(status=200, data=res,safe=False)
+
+
+    def test_upload_s3(self,request_dict):
+        testd = hmac.new('AWS4rf/xnQ3jIgY8bj7Sz4An4KbYct2sq2MbrfmP8rVV'.encode("utf-8"), '20210223'.encode("utf-8"), hashlib.sha256).digest()
+        region_sign = hmac.new(testd, 'cn-northwest-1'.encode("utf-8"), hashlib.sha256).hexdigest()
+        exit(region_sign)
+        kService = sign(kRegion, 's3')
+        kSigning = sign(kService, 'aws4_request')
+
+        # exit(CommonService.getIpIpInfo("120.197.196.156",'CN'))
+        aws_key = "ASIA2MMWBR4DUPTFDTOJ" #【你的 aws_access_key】
+        aws_secret = "tTFZ9wpxFadeufhfaJ1erErv4U1bJ+TS/SJwTptx" #【你的 aws_access_key】
+        aws_session_token = "IQoJb3JpZ2luX2VjEJT//////////wEaDmNuLW5vcnRod2VzdC0xIkYwRAIgenLaMN6NdFji0x18OuaUTPvvtRBAWwjdEYdBTCMh0ywCIEzntAbgRPmwS+YFuNg+F31z60I4J1IoqmrQHR7wmPzVKtsCCML//////////wEQABoMNzEzODE2MTE2OTk5IgyJTmdtNJ319TtNORAqrwLPG6Px0z5CsEQpFt/TCbSSMRtYqBU+x5Ll9hZIuTvg8H+56H02/cr0nSCNiy05z7dSrSWMFoMhVKvHq7as5TRvVXkvMbbYPQuQxxPFr7EswaB+XITeDpdGBI6N7mqnt6h4YJbhk2dNRa2/4Ypr1DuyGnhVV6NxNHA5INtY7apLi3UTcNKwKSQRVzUWZBpoj86wG3j77KOZg18I9P8UWBpA9fpz/Wiv4xrzZSexrUnq5svTLEqMfTYCPBXkxrJBjNrwVjvkBkgeIfQZPz+A5X97p7wXbPf0Jo5aHHRDefbAmBuXYoSfpHjiFWindkcvCaMxQzUiHVLvnN/5SvgQEzN3pLUAAioepRZIZQLaky1aRmYYm1wOCjzgsg9V+GV6gKTE+ipFG/6Nv03Vh++Hv+YwyamJgQY6mgEmxhOhncek0PgQeExx2EXk73olY/6L15eDyHbSWoEKBMTmdlmpYD9Cj3qP4aUUW6UT6V5Tql/s5eBEsYwY+hzgtQiTmd7vjytXxae+dpN9VsWGW4AJ9P+/LgBe6zExUx2MOVst0+hb+dd8bg/qkz7UBYNQAmU+BEoL2Cd7lNXdrv56Gboapo+BosQO49GT8u1k5EheQ9JKHCqv"
+        session = Session(aws_access_key_id=aws_key,
+                          aws_secret_access_key=aws_secret,
+                          aws_session_token=aws_session_token,
+                          region_name="cn-northwest-1") # 此处根据自己的 s3 地区位置改变
+        s3 = session.resource("s3")
+        # client = session.client("s3")
+        bucket = "7cdk" # 【你 bucket 的名字】 # 首先需要保.证 s3 上已经存在该存储桶,否则报错
+        upload_data = open("./././static/log/test.log", "rb")
+        upload_key = "XKWZSC5FCJYT19B7111A/test/test6/test.log"
+        file_obj = s3.Bucket(bucket).put_object(Key=upload_key, Body=upload_data)
+        print('---------------------')
+        print(file_obj)
+        print(8/0)
+        exit()
+
+
+    def testRequest(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")
+
+
+
 

+ 63 - 0
Controller/TestController.py

@@ -0,0 +1,63 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import hashlib
+
+from django.contrib.auth.hashers import make_password, check_password
+from django.views import View
+
+from Object.uidManageResponseObject import uidManageResponseObject
+
+
+class TestView(View):
+
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation', None)
+        request_dict = request.GET
+        return self.validate(request_dict, operation)
+
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation', None)
+        request_dict = request.POST
+        return self.validate(request_dict, operation)
+
+    def validate(self, request_dict, operation):
+
+        response = uidManageResponseObject()
+
+        if operation == 'createPassword':
+            return self.do_create_password(request_dict, response)
+        elif operation == 'checkPassword':
+            return self.do_check_password(request_dict, response)
+        else:
+            return response.json(404)
+
+    def do_create_password(self, request_dict, response):
+        password = request_dict.get('password', None)
+        print(password)
+        result = make_password(password)
+        print(result)
+        print(check_password(password, result))
+        return response.json(0, result)
+
+    def do_check_password(self, request_dict, response):
+        password = request_dict.get('password', None)
+        password2 = request_dict.get('password2', None)
+        print(password)
+        print(password2)
+        check = check_password(password, password2)
+
+        return response.json(0, check)
+
+    # def make_password(self, password):
+    #     md5 = hashlib.md5()
+    #     md5.update(str(password).encode('utf-8'))
+    #     return md5.hexdigest()
+    #
+    # def check_password(self, password, encryp):
+    #     print(password)
+    #     print(encryp)
+    #     password1 = self.make_password(password)
+    #     print(password1)
+    #     return encryp == self.make_password(password)

+ 479 - 0
Controller/UIDController.py

@@ -0,0 +1,479 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import json
+import logging
+import time
+
+from django.db import transaction
+from django.http import StreamingHttpResponse
+from django.utils.decorators import method_decorator
+from django.views import View
+from django.views.decorators.csrf import csrf_exempt
+from django.db.models import Avg,Max,Min,Count,Sum, Q  #   引入函数
+
+from Model.models import UIDModel, UserModel, UserUIDModel, HistoryUIDModel
+from Object.RedisObject import RedisObject
+from Object.uidManageResponseObject import uidManageResponseObject
+from Object.TokenObject import TokenObject
+from Service.ModelService import ModelService
+
+
+class UIDView(View):
+
+    @method_decorator(csrf_exempt)
+    def dispatch(self, request, *args, **kwargs):
+        return super(UIDView, self).dispatch(request, *args, **kwargs)
+
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.GET
+        operation = kwargs.get('operation')
+        return self.validate(request_dict, operation)
+
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.POST
+        operation = kwargs.get('operation')
+        return self.validate(request_dict, operation)
+
+    def validate(self, request_dict, operation):
+        token = request_dict.get('token', None)
+        response = uidManageResponseObject()
+
+        token = TokenObject(token)
+        if token.code != 0:
+            return response.json(token.code)
+
+        if operation == 'quantity':
+            return self.do_quantity(request_dict, response)
+        elif operation == 'allot':
+            return self.do_allot(request_dict, response)
+        elif operation == 'remove':
+            return self.do_remove(request_dict, response)
+        elif operation == 'download':
+            return self.download_txt(token, response)
+        elif operation == 'download_1':
+            return self.download_txt_two(token, response)
+        elif operation == 'list':
+            return self.do_list(request_dict, response)
+        elif operation == 'delete':
+            return self.do_delete(token.userID, request_dict, response)
+        elif operation == 'batchDelete':
+            return self.do_batch_delete(token.userID, request_dict, response)
+        elif operation == 'adminUpdate':
+            return self.do_admin_update(token.userID, request_dict, response)
+        elif operation == 'history':
+            return self.do_history(token.userID, request_dict, response)
+        elif operation == 'statistics':
+            return self.do_admin_statistics(token.userID, request_dict, response)
+        else:
+            return response.json(309)
+
+    # 查询当前可用的UID的数量
+    def do_quantity(self, request_dict, response):
+        token = request_dict.get('token', None)
+
+        token = TokenObject(token)
+        if token.code != 0:
+            return response.json(token.code)
+
+        user_qs = UserModel.objects.filter(id=token.userID)
+        if user_qs.exists():
+            user = user_qs[0]
+            if user.permission == '0':
+                return self.do_admin_quantity(request_dict, response, user.username)
+            else:
+                return self.do_not_admin_quantity(request_dict, response, user.username)
+        else:
+            return response.json(9)
+
+    # 管理员的查询UID数量操作
+    def do_admin_quantity(self, request_dict, response, admin):
+        datas = []
+        domestic = UIDModel.objects.filter(area=0, status=0).count()
+        foreign = UIDModel.objects.filter(area=1, status=0).count()
+        item = {}
+        item['isAdmin'] = 1
+        item['domestic'] = domestic
+        item['foreign'] = foreign
+        item['username'] = admin
+        datas.append(item)
+
+        user_qs = UserModel.objects.filter(~Q(Q(permission='0')))
+        for user in user_qs:
+            item = {'isAdmin': 0}
+            result = UserUIDModel.objects.filter(user__id=user.id, uid__status=1, uid__area=0).aggregate(num=Count('uid__status'))
+            item['domestic'] = result['num']
+            result = UserUIDModel.objects.filter(user__id=user.id, uid__status=1, uid__area=1).aggregate(num=Count('uid__status'))
+            item['foreign'] = result['num']
+            item['username'] = user.username
+            datas.append(item)
+
+        return response.json(0, {'data': datas})
+
+    # 非管理员的查询UID数量操作
+    def do_not_admin_quantity(self, request_dict, response, username):
+        user_qs = UserModel.objects.filter(username=username)
+        if user_qs.exists():
+            user = user_qs[0]
+            datas = []
+            item = {'isAdmin': 0}
+            result = UserUIDModel.objects.filter(user__id=user.id, uid__status=1, uid__area=0).aggregate(num=Count('uid__status'))
+            item['domestic'] = result['num']
+            result = UserUIDModel.objects.filter(user__id=user.id, uid__status=1, uid__area=1).aggregate(num=Count('uid__status'))
+            item['foreign'] = result['num']
+            item['username'] = user.username
+            datas.append(item)
+            return response.json(0, {'data': datas})
+        else:
+            return response.json(444)
+
+    # 分配UID
+    @transaction.atomic
+    def do_allot(self, request_dict, response):
+        username = request_dict.get('username', None)
+        quantity = int(request_dict.get('quantity', None))
+        area = request_dict.get('area', None)
+        token = request_dict.get('token', None)
+
+        token = TokenObject(token)
+        if token.code != 0:
+            return response.json(token.code)
+        user = UserModel.objects.get(id=token.userID)
+
+        if not user or '0' not in user.permission:
+            return response.json(404)
+
+        # 要分配的对象
+        allot_user_qs = UserModel.objects.filter(username=username)
+        if not allot_user_qs.exists():
+            return response.json(444, 'username')
+
+        # 取出对应区域可用的UID分配给allot_user
+        uid_qs = UIDModel.objects.filter(area=area, status=0)
+        count = uid_qs.count()
+        if count < quantity:
+            return response.json(444, '设备UID不足')
+
+        updates = []
+        datas = []
+        count = 0
+        if uid_qs.exists():
+            uid_qs = uid_qs[0:quantity]
+            now_time = int(time.time())
+            savePoint = transaction.savepoint()
+            for item in uid_qs:
+                item.status = 1
+                item.update_time = time.time()
+                user_uid = UserUIDModel()
+                user_uid.uid = item
+                user_uid.user = allot_user_qs[0]
+                user_uid.add_time = now_time
+                user_uid.update_time = now_time
+                datas.append(user_uid)
+                updates.append(item)
+
+                if len(datas) % 5000 == 0:
+                    result = self.do_update(datas, updates, savePoint)
+                    if result != 0:
+                        return response.json(result)
+
+            if len(datas) > 0:
+                result = self.do_update(datas, updates, savePoint)
+                if result != 0:
+                    return response.json(result)
+            redisObject = RedisObject()
+            values = uid_qs.values('uid')
+            print(values)
+            redisObject.set_data(key=token.token, val=json.dumps(list(values)), expire=3600)
+            del datas
+            del updates
+            return response.json(0)
+        else:
+            return response.json(444)
+
+    def do_update(self, datas, updates, savePoint, count=0):
+        try:
+            try:
+                UserUIDModel.objects.bulk_create(datas)
+                UIDModel.objects.bulk_update(updates, fields=['status', 'update_time'])
+                datas.clear()
+                updates.clear()
+            except Exception as e:
+                if savePoint:
+                    transaction.savepoint_rollback(savePoint)
+                djangoLogger = logging.getLogger('django')
+                djangoLogger.exception(repr(e))
+                return 174
+        except Exception as e:
+            return 174
+        return 0
+
+    # 把UID表中的数据移动到HistoryUID表中
+    def do_remove(self, request_dict, response):
+        token = TokenObject(request_dict.get('token', None))
+        id = request_dict.get('id', None)
+        start = request_dict.get('start', None)
+        stop = request_dict.get('stop', None)
+
+        if token.code != 0:
+            return response.json(token.code)
+
+        # 通过userID查找用户,判断是否是管理员
+        user_qs = UserModel.objects.filter(id=token.userID)
+        if user_qs.exists():
+            user = user_qs[0]
+            if user.permission != '0':
+                return response.json(404)
+        else:
+            return response.json(9)
+
+        if id:
+            return self.do_remove_by_id(id, response)
+        elif start and stop:
+            return self.do_bulk_remove(int(start), int(stop), response)
+        else:
+            return response.json(444, 'id,start,stop')
+
+    # 移除单条UID记录,id:记录id
+    def do_remove_by_id(self, id, response):
+        id = int(id)
+        uid_qs = UIDModel.objects.filter(id=id)
+        if not uid_qs.exists():
+            return response.json(173)
+
+        uid = uid_qs[0]
+        if uid:
+            data = {
+                'uid': uid.uid,
+                'uid_extra': uid.uid_extra,
+                'status': uid.status,
+                'add_time': uid.add_time,
+                'update_time': uid.update_time,
+                'area': uid.area
+            }
+            HistoryUIDModel.objects.create(**data)
+            uid.delete()
+            return response.json(0)
+        else:
+            return response.json(444, 'id')
+
+    # 批量移除UID记录。start:开始的UID记录的id;stop:结束的UID记录的id
+    def do_bulk_remove(self, start, stop, response):
+        uid_qs = UIDModel.objects.filter(id__range=(start, stop))
+        histories = []
+        if uid_qs.exists():
+            for item in uid_qs:
+                histories.append(HistoryUIDModel(
+                    uid=item.uid,
+                    uid_extra=item.uid_extra,
+                    status=item.status,
+                    add_time=item.add_time,
+                    update_time=item.update_time,
+                    area=item.area
+                ))
+                if len(histories) % 5000 == 0:
+                    HistoryUIDModel.objects.bulk_create(histories)
+                    histories.clear()
+            if len(histories) > 0:
+                HistoryUIDModel.objects.bulk_create(histories)
+                histories.clear()
+            uid_qs.delete()
+            return response.json(0)
+        else:
+            return response.json(173)
+
+    def download_txt(self, token, response):
+
+        redisObject = RedisObject()
+        uid_qs = redisObject.get_data(key=token.token)
+
+        if uid_qs is False:
+            return response.json(308)
+
+        uid_qs = json.loads(uid_qs)
+        content = ''
+        for item in uid_qs:
+            # print(item)
+            content += item['uid']
+            content += '\r\n'
+
+        redisObject.del_data(key=token.token)
+
+        content = content[0:len(content) - 1]
+        response = StreamingHttpResponse(content)
+        response['Content-Type'] = 'application/octet-stream'
+        filename = 'uid_need_to_set_up_push.txt'
+        response['Content-Disposition'] = 'attachment;filename=' + filename
+
+        return response
+
+    def download_txt_two(self, token, response):
+
+        uid_qs = UIDModel.objects.filter(status=1)
+
+        if not uid_qs.exists():
+            return response.json(308)
+
+        uid_qs = uid_qs.values()
+        content = ''
+        for item in uid_qs:
+            # print(item)
+            content += item['uid']
+            content += '\r\n'
+
+        content = content[0:len(content) - 1]
+        response = StreamingHttpResponse(content)
+        response['Content-Type'] = 'application/octet-stream'
+        filename = 'uid_need_to_set_up_push.txt'
+        response['Content-Disposition'] = 'attachment;filename=' + filename
+
+        return response
+
+    def do_list(self, request_dict, response):
+        page = request_dict.get('page', None)
+        line = request_dict.get('limit', None)
+        status = request_dict.get('status', None)
+        area = request_dict.get('area', None)
+        start_time = request_dict.get('starttime', None)
+        stop_time = request_dict.get('endtime', None)
+        uid = request_dict.get('uid', None)
+
+        if page and line:
+
+            uid_qs = UIDModel.objects.filter()
+            res = {
+                'count': 0,
+                'data': []
+            }
+
+            if uid_qs.exists():
+                page = int(page)
+                line = int(line)
+
+                start = (page - 1) * line
+                end = start + line
+
+                if uid:
+                    uid_qs = uid_qs.filter(uid=uid)
+
+                if status:
+                    uid_qs = uid_qs.filter(status=status)
+
+                if area:
+                    uid_qs = uid_qs.filter(area=area)
+
+                if start_time:
+                    uid_qs = uid_qs.filter(update_time__gte=start_time)
+
+                if stop_time:
+                    if stop_time > start:
+                        uid_qs = uid_qs.filter(update_time__lte=stop_time)
+
+                res['count'] = uid_qs.count()
+                uid_qs = uid_qs.values()[start:end]
+
+                res['data'] = list(uid_qs)
+
+            print(res)
+            return response.json(0, res)
+        else:
+            return response.json(444)
+
+    def do_delete(self, userID, request_dict, response):
+        uid = request_dict.get('uid', None)
+        user_qs = UserModel.objects.filter(id=userID)
+
+        if user_qs.exists():
+            user = user_qs[0]
+            if int(user.permission) != 0:
+                return response.json(309)
+
+            UIDModel.objects.filter(uid=uid).delete()
+            return response.json(0)
+        else:
+            return response.json(309)
+
+    def do_batch_delete(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        uids = request_dict.get('uidlist', None)
+
+        if uids:
+            uids = json.loads(uids)
+            UIDModel.objects.filter(uid__in=uids).delete()
+            return response.json(0)
+        else:
+            return response.json(444)
+
+    def do_admin_update(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        uid = request_dict.get('uid', None)
+        content = request_dict.get('content', None)
+        print(content)
+
+        if uid and content:
+            content = json.loads(content)
+            print(content)
+            content['update_time'] = int(time.time())
+            uid_qs = UIDModel.objects.filter(uid=uid)
+            if uid_qs.exists():
+                uid_qs.update(**content)
+                return response.json(0)
+            else:
+                return response.json(173)
+        else:
+            return response.json(444)
+
+    def do_history(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        uid_qs = UIDModel.objects.filter(status=2)
+
+        if uid_qs.exists():
+
+            uids = []
+            for uid in uid_qs:
+                uids.append(uid)
+
+                if (len(uids) % 5000) == 0:
+                    HistoryUIDModel.objects.bulk_create(uids)
+                    uids.clear()
+
+            if len(uids) > 0:
+                HistoryUIDModel.objects.bulk_create(uids)
+                uids.clear()
+
+        uid_qs.delete()
+
+        return response.json(0)
+
+    def do_admin_statistics(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        uid_not_use = UIDModel.objects.filter(status=0).count()
+
+        uid_allocated = UIDModel.objects.filter(status=1).count()
+
+        uid_has_use = UIDModel.objects.filter(status=2).count()
+
+        total = uid_not_use + uid_allocated + uid_has_use
+
+        res = {
+            'uid_not_use': uid_not_use,
+            'uid_allocated': uid_allocated,
+            'uid_has_use': uid_has_use,
+            'total': total
+        }
+
+        return response.json(0, res)
+

+ 296 - 0
Controller/UIDManageUserController.py

@@ -0,0 +1,296 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import time
+
+from django.db.models import Q
+from django.utils.decorators import method_decorator
+from django.views import View
+from django.views.decorators.csrf import csrf_exempt
+
+from Model.models import UserModel
+from Object.uidManageResponseObject import uidManageResponseObject
+from Object.TokenObject import TokenObject
+from Service.ModelService import ModelService
+
+
+class UserView(View):
+
+    @method_decorator(csrf_exempt)
+    def dispatch(self, request, *args, **kwargs):
+        return super(UserView, self).dispatch(request, *args, **kwargs)
+
+    def get(self, request, *args, **kwargs):
+        # print('get')
+        request.encoding = 'utf-8'
+        request_dict = request.GET
+        operation = kwargs.get('operation')
+        return self.validation(request_dict, operation)
+
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.POST
+        operation = kwargs.get('operation')
+        return self.validation(request_dict, operation)
+
+    def validation(self, request_dict, operation):
+
+        if operation == 'login':
+            return self.login(request_dict)
+        elif operation == 'logout':
+            return self.logout(request_dict)
+        else:
+            token = request_dict.get('token', None)
+
+            token = TokenObject(token)
+            response = uidManageResponseObject()
+            if token.code != 0:
+                return response.json(token.code)
+
+            if operation == 'query':
+                return self.do_query(request_dict)
+            elif operation == 'modify':
+                return self.do_modify_password(request_dict)
+            elif operation == 'list':
+                return self.do_list(request_dict)
+            elif operation == 'adminAdd':
+                return self.do_admin_add(token.userID, request_dict, response)
+            elif operation == 'adminDelete':
+                return self.do_admin_delete(token.userID, request_dict, response)
+            elif operation == 'adminUpdate':
+                return self.do_admin_update(token.userID, request_dict, response)
+            elif operation == 'adminReset':
+                return self.do_admin_reset(token.userID, request_dict, response)
+            else:
+                return uidManageResponseObject().json(309)
+
+    def login(self, request_dict):
+        username = request_dict.get('username', None)
+        password = request_dict.get('password', None)
+
+        response = uidManageResponseObject()
+
+        if username is None or password is None:
+            return response.json(444)
+
+        user = UserModel.objects.filter(username=username)
+        if user.exists():
+            if user[0].password != password:
+                return response.json(99)
+            else:
+                token = TokenObject()
+                res = token.generate({'userID': user[0].id})
+                res['permission'] = user[0].permission
+                res['username'] = user[0].username
+                user[0].online = 1
+                update = {
+                    'online': 1
+                }
+                user.update(**update)
+                return response.json(0, res)
+        else:
+            return response.json(99)
+
+    def do_query(self, request_dict):
+        # print('do_query')
+        token = TokenObject(request_dict.get('token', None))
+        # page = request_dict.get('page', None)
+        # line = request_dict.get('line', None)
+        # username = request_dict.get('username', None)
+        response = uidManageResponseObject()
+
+        if token.code != 0:
+            return response.json(token.code)
+
+        # if username:
+        #     user_qs = UserModel.objects.filter(username__icontains=username)
+        #     if user_qs.exists():
+        #         users = list(user_qs.values('username'))
+        #         return response.json(0, {'data': users})
+        #     else:
+        #         return response.json(0, {'data': []})
+        # elif page and line:
+        #     print('query_page')
+        #     user_qs = UserModel.objects.filter(id=token.userID)
+        #     if user_qs.exists():
+        #         user = user_qs[0]
+        #         if user.permission == '0':
+        #             return self.do_query_pagination(int(page), int(line), response)
+        #         else:
+        #             return response.json(404)
+        #     else:
+        #         return response.json(9)
+
+        user_qs = UserModel.objects.filter(~Q(Q(permission='0'))).values('id', 'username')
+
+        return response.json(0, {'data': list(user_qs)})
+
+    def do_query_pagination(self, page, line, response):
+        # print('query start')
+        user_qs = UserModel.objects.filter().values()
+        if user_qs.exists():
+            count = user_qs.count()
+            start = (page - 1) * line
+            end = start + line
+            users = list(user_qs[start:end])
+            # print('query end')
+            return response.json(0, {'count': count, 'data': users})
+        else:
+            return response.json(0, {'count': 0, 'data': []})
+
+    def do_modify_password(self, request_dict):
+        token = request_dict.get('token', None)
+        old_password = request_dict.get('oldPassword', None)
+        new_password = request_dict.get('newPassword', None)
+        token = TokenObject(token)
+
+        response = uidManageResponseObject()
+        if token.code != 0:
+            return response.json(token.code)
+
+        if old_password and new_password:
+            user_qs = UserModel.objects.filter(id=token.userID)
+            if user_qs.exists():
+                if user_qs[0].password != old_password:
+                    return response.json(47)
+                user = {
+                    'password': new_password
+                }
+                user_qs.update(**user)
+                return response.json(0)
+            else:
+                return response.json(9)
+        else:
+            return response.json(444)
+
+    def logout(self, request_dict):
+        token = request_dict.get('token', None)
+        token = TokenObject(token)
+        response = uidManageResponseObject()
+        if token.code != 0:
+            return response.json(0)
+
+        user_qs = UserModel.objects.filter(id=token.userID)
+        if user_qs.exists():
+            user = {
+                'online': 0
+            }
+            user_qs.update(**user)
+            return response.json(0)
+        else:
+            return response.json(0)
+
+    def do_list(self, request_dict):
+        token = request_dict.get('token', None)
+
+        response = uidManageResponseObject()
+        token = TokenObject(token)
+        if token.code != 0:
+            return response.json(token.code)
+
+        page = request_dict.get('page', None)
+        line = request_dict.get('limit', None)
+
+        if page and line:
+            user_qs = UserModel.objects.filter()
+
+            res = {
+                'count': user_qs.count(),
+                'data': []
+            }
+            if user_qs.exists():
+                page = int(page)
+                line = int(line)
+
+                start = (page - 1) * line
+                end = start + line
+
+                user_qs = user_qs[start:end].values('id', 'username', 'permission', 'phone', 'login_time', 'add_time')
+
+                res['data'] = list(user_qs)
+            return response.json(0, res)
+        else:
+            return response.json(444)
+
+    def do_admin_add(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        print(request_dict)
+        username = request_dict.get('username', None)
+        password = request_dict.get('password', None)
+        phone = request_dict.get('phone', None)
+        role = request_dict.get('role', None)
+
+        if username and password and role:
+            user = UserModel()
+            user.username = username
+            user.password = password
+            user.permission = role
+            user.phone = phone
+            user.add_time = int(time.time())
+            user.save()
+            return response.json(0)
+        else:
+            return response.json(444)
+
+    def do_admin_delete(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        username = request_dict.get('username', None)
+
+        if username:
+            user_qs = UserModel.objects.filter(username=username)
+            if user_qs.exists():
+                user_qs.delete()
+                return response.json(0)
+            else:
+                return response.json(9)
+        else:
+            return response.json(444)
+
+    def do_admin_update(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        username = request_dict.get('username', None)
+        role = request_dict.get('role', None)
+        password = request_dict.get('password', None)
+        phone = request_dict.get('phone', None)
+
+        if username:
+            update_data = {}
+
+            if role:
+                update_data['permission'] = role
+
+            if password:
+                update_data['password'] = password
+
+            if phone:
+                update_data['phone'] = phone
+
+            UserModel.objects.filter(username=username).update(**update_data)
+            return response.json(0)
+        else:
+            return response.json(444)
+
+    def do_admin_reset(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        username = request_dict.get('username', None)
+
+        if username:
+            user_qs = UserModel.objects.filter(username=username)
+            if user_qs.exists():
+                user_qs.update(password='123456')
+                return response.json(0)
+            else:
+                return response.json(9)
+        else:
+            return response.json(444)

+ 24 - 1
Controller/UidSetController.py

@@ -23,7 +23,8 @@ from django.views.decorators.csrf import csrf_exempt
 from django.views.generic.base import View
 
 from Model.models import UidSetModel, Device_User, Device_Info, UidPushModel, Equipment_Info, UID_Preview, UID_Bucket, \
-    VodHlsModel, Order_Model, OssCrdModel, UidUserModel, UidChannelSetModel, User_Brand
+    VodHlsModel, Order_Model, OssCrdModel, UidUserModel, UidChannelSetModel, User_Brand, ExperienceContextModel, \
+    StsCrdModel, Unused_Uid_Meal
 from Object.ResponseObject import ResponseObject
 from Object.TokenObject import TokenObject
 from Service.CommonService import CommonService
@@ -89,6 +90,8 @@ class UidSetView(View):
             return self.do_update_channel_set(request_dict, response)
         elif operation == 'setVoicePrompt':
             return self.do_set_voice(userID, request_dict, response)
+        elif operation == 'vod_reset':
+            return self.vod_reset(request_dict, response)
         # elif operation == 'test':
         #     return self.do_test(response)
         else:
@@ -484,6 +487,26 @@ class UidSetView(View):
             else:
                 return response.json(0)
 
+    # 重置设备云存
+    def vod_reset(self, request_dict, response):
+        uid = request_dict.get('uid', None)
+        if uid:
+            try:
+                with transaction.atomic():
+                    # 删除和更新设备云存相关数据
+                    UID_Bucket.objects.filter(uid=uid).delete()
+                    Unused_Uid_Meal.objects.filter(uid=uid).delete()
+                    Order_Model.objects.filter(UID=uid).delete()
+                    StsCrdModel.objects.filter(uid=uid).delete()
+                    VodHlsModel.objects.filter(uid=uid).delete()
+                    ExperienceContextModel.objects.filter(uid=uid).delete()
+                    Device_Info.objects.filter(UID=uid).update(vodPrimaryUserID='', vodPrimaryMaster='')
+            except Exception as e:
+                print(e)
+                return response.json(500, repr(e))
+            else:
+                return response.json(0)
+
     # def do_test(self, response):
     #     di_qs = Device_Info.objects.values('Type').annotate(c=Count('UID', distinct=True)).order_by()
     #     for di in di_qs:

+ 130 - 54
Controller/UserController.py

@@ -14,7 +14,7 @@
 import datetime
 import traceback
 import time
-
+import logging
 import jwt
 import simplejson
 import simplejson as json
@@ -32,7 +32,7 @@ from ratelimit.decorators import ratelimit
 from Ansjer.config import AuthCode_Expire, SERVER_DOMAIN, APNS_CONFIG, JPUSH_CONFIG, FCM_CONFIG, TUTK_PUSH_DOMAIN
 from Controller.CheckUserData import DataValid, date_handler, RandomStr
 from Model.models import Device_User, Role, UidPushModel, UserOauth2Model, UserExModel, Device_Info, UidSetModel, \
-    UserAppFrequencyModel, CountryIPModel
+    UserAppFrequencyModel, CountryIPModel, CountryModel
 from Object.AWS.SesClassObject import SesClassObject
 from Object.AliSmsObject import AliSmsObject
 from Object.RedisObject import RedisObject
@@ -49,7 +49,6 @@ from PIL import Image, ImageDraw, ImageFont
 from django.shortcuts import HttpResponse
 from Ansjer.config import BASE_DIR
 
-
 # 获取验证码
 class authCodeView(TemplateView):
 
@@ -173,6 +172,9 @@ class registerView(TemplateView):
         password = request_dict.get('userPwd', None)
         authCode = request_dict.get('identifyingCode', None)
         language = request_dict.get('language', None)
+        unique = request_dict.get('unique', None)
+        if unique:
+            delete_local_account(unique)
         response = ResponseObject(language)
         if username and password and authCode:
             # 过滤空格
@@ -286,7 +288,6 @@ class registerView(TemplateView):
         else:
             return response.json(109)
 
-
 # 登出
 class LogoutView(TemplateView):
     @method_decorator(csrf_exempt)
@@ -858,6 +859,10 @@ class v2registerView(TemplateView):
         password = request_dict.get('password', None)
         authcode = request_dict.get('authcode', None)
         lang = request_dict.get('lang', None)
+        unique = request_dict.get('unique', None)
+        number = request_dict.get('number', None)
+        if unique:
+            delete_local_account(unique)
         response = ResponseObject(lang)
         if not lang:
             lang = request_dict.get('language', None)
@@ -866,13 +871,13 @@ class v2registerView(TemplateView):
         if authcode is None:
             return response.json(444, 'identifyingCode')
         if phone is not None:
-            return self.do_phone_register(phone, password, authcode, response)
+            return self.do_phone_register(phone, password, authcode, number, response)
         elif email is not None:
-            return self.do_email_register(email, password, authcode, response)
+            return self.do_email_register(email, password, authcode, number, response)
         else:
             return response.json(444, 'phone or email')
 
-    def do_phone_register(self, phone, password, authcode, response):
+    def do_phone_register(self, phone, password, authcode, number, response):
         data_valid = DataValid()
         if data_valid.mobile_validate(phone) is not True:
             return response.json(100)
@@ -891,15 +896,19 @@ class v2registerView(TemplateView):
         if phone_qs.exists():
             return response.json(101)
         try:
-            users = Device_User.objects.create(
-                username=phone,
-                NickName=phone,
-                phone=phone,
-                password=make_password(password),
-                userID=CommonService.getUserID(μs=False, setOTAID=True),
-                is_active=True,
-                user_isValid=True,
-            )
+            create_data = {
+                "username": phone,
+                "NickName": phone,
+                "phone": phone,
+                "password": make_password(password),
+                "userID": CommonService.getUserID(μs=False, setOTAID=True),
+                "is_active": True,
+                "user_isValid": True,
+            }
+            if number:
+                create_data["region_country"] = number
+
+            users = Device_User.objects.create(**create_data)
         except Exception as e:
             errorInfo = traceback.format_exc()
             print(errorInfo)
@@ -938,7 +947,7 @@ class v2registerView(TemplateView):
         print(res)
         return response.json(0, res)
 
-    def do_email_register(self, email, password, authcode, response):
+    def do_email_register(self, email, password, authcode, number, response):
         data_valid = DataValid()
         if data_valid.email_validate(email) is not True:
             return response.json(105)
@@ -957,15 +966,18 @@ class v2registerView(TemplateView):
         if email_qs.exists():
             return response.json(103)
         try:
-            users = Device_User.objects.create(
-                username=email,
-                NickName=email,
-                userEmail=email,
-                password=make_password(password),
-                userID=CommonService.getUserID(μs=False, setOTAID=True),
-                is_active=True,
-                user_isValid=True,
-            )
+            create_data = {
+                "username": email,
+                "NickName": email,
+                "userEmail": email,
+                "password": make_password(password),
+                "userID": CommonService.getUserID(μs=False, setOTAID=True),
+                "is_active": True,
+                "user_isValid": True,
+            }
+            if number:
+                create_data["region_country"] = number
+            users = Device_User.objects.create(**create_data)
         except Exception as e:
             errorInfo = traceback.format_exc()
             print(errorInfo)
@@ -999,6 +1011,8 @@ class v3registerView(TemplateView):
         authcode = request_dict.get('authcode', None)
         lang = request_dict.get('lang', None)
         unique = request_dict.get('unique', None)
+        number = request_dict.get('number', None)
+
         if unique:
             delete_local_account(unique)
         response = ResponseObject(lang)
@@ -1045,13 +1059,13 @@ class v3registerView(TemplateView):
             if authcode is None:
                 return response.json(444, 'identifyingCode')
             if phone is not None:
-                return self.do_phone_register(phone, password, authcode, response)
+                return self.do_phone_register(phone, password, authcode, number, response)
             elif email is not None:
-                return self.do_email_register(email, password, authcode, response)
+                return self.do_email_register(email, password, authcode, number, response)
             else:
                 return response.json(444, 'phone or email')
 
-    def do_phone_register(self, phone, password, authcode, response):
+    def do_phone_register(self, phone, password, authcode, number, response):
         data_valid = DataValid()
         if data_valid.mobile_validate(phone) is not True:
             return response.json(100)
@@ -1070,15 +1084,20 @@ class v3registerView(TemplateView):
         if phone_qs.exists():
             return response.json(101)
         try:
-            users = Device_User.objects.create(
-                username=phone,
-                NickName=phone,
-                phone=phone,
-                password=make_password(password),
-                userID=CommonService.getUserID(μs=False, setOTAID=True),
-                is_active=True,
-                user_isValid=True,
-            )
+            create_data = {
+                "username": phone,
+                "NickName": phone,
+                "phone": phone,
+                "password": make_password(password),
+                "userID": CommonService.getUserID(μs=False, setOTAID=True),
+                "is_active": True,
+                "user_isValid": True,
+            }
+            if number:
+                create_data["region_country"] = number
+
+            users = Device_User.objects.create(**create_data)
+
         except Exception as e:
             errorInfo = traceback.format_exc()
             print(errorInfo)
@@ -1116,7 +1135,7 @@ class v3registerView(TemplateView):
         res['phone'] = user_list[0]["phone"] if user_list[0]["phone"] is not None else ''
         return response.json(0, res)
 
-    def do_email_register(self, email, password, authcode, response):
+    def do_email_register(self, email, password, authcode, number, response):
         data_valid = DataValid()
         if data_valid.email_validate(email) is not True:
             return response.json(105)
@@ -1130,20 +1149,25 @@ class v3registerView(TemplateView):
         # 验证码是否正确
         if authcode != identifyingCode:
             return response.json(121)
+
         email_qs = Device_User.objects.filter(Q(userEmail=email) | Q(username=email))
         # 是否已存在
         if email_qs.exists():
             return response.json(103)
         try:
-            users = Device_User.objects.create(
-                username=email,
-                NickName=email,
-                userEmail=email,
-                password=make_password(password),
-                userID=CommonService.getUserID(μs=False, setOTAID=True),
-                is_active=True,
-                user_isValid=True,
-            )
+            create_data = {
+                "username": email,
+                "NickName": email,
+                "userEmail": email,
+                "password": make_password(password),
+                "userID": CommonService.getUserID(μs=False, setOTAID=True),
+                "is_active": True,
+                "user_isValid": True,
+            }
+            if number:
+                create_data["region_country"] = number
+            users = Device_User.objects.create(**create_data)
+
         except Exception as e:
             errorInfo = traceback.format_exc()
             print(errorInfo)
@@ -1765,8 +1789,7 @@ class v3LoginView(TemplateView):
             user_qs.update(subscribe_email=subscribe)
 
         users = user_qs.values('role__rid', 'role__roleName', 'userID', 'NickName', 'username', 'userEmail',
-                               'phone', 'password', 'userIconPath', 'fingerprint_enable', 'fingerprint_key',
-                               'subscribe_email')[0]
+                               'phone', 'password', 'userIconPath', 'fingerprint_enable', 'fingerprint_key', 'subscribe_email')[0]
         if not check_password(password, users['password']):
             return response.json(111)
         userID = users['userID']
@@ -1778,6 +1801,7 @@ class v3LoginView(TemplateView):
         if oauth_qs.exists():
             auth_type = oauth_qs[0].authType
 
+
         if tko.code == 0:
             now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
             user_qs.update(last_login=now_time, language=response.lang)
@@ -1829,8 +1853,7 @@ class InitInfoView(View):
         else:
             return response.json(tko.code)
 
-        # 初始化设备token
-
+    # 初始化设备token
     def init_info(self, request_dict, userID, response, request):
         # 未读的系统消息
         token_val = request_dict.get('token_val', None)
@@ -2824,12 +2847,12 @@ class generatePictureCodeView(TemplateView):
         kumo_font = ImageFont.truetype(path, 40, encoding="unic")  # 设置字体
         print("字体可以")
         valid_code_str = ''
-        for i in range(5):
+        for i in range(6):
             random_num = str(random.randint(0, 9))
             random_low_alpha = chr(random.randint(97, 122))
             random_high_alpha = chr(random.randint(65, 90))
             random_char = random.choice([random_num, random_low_alpha, random_high_alpha])
-            draw.text((i * 50 + 20, -3), random_char, 'white', kumo_font)
+            draw.text((i * 40 + 20, -3), random_char, 'white', kumo_font)
 
             # 保存验证码字符串
             valid_code_str += random_char
@@ -2914,6 +2937,7 @@ class Image_Code_RegisterView(TemplateView):
         response = ResponseObject(lang)
         valid_code = request_dict.get('id_v_code', None)
         unique = request_dict.get('unique', None)
+        number = request_dict.get('number', None)
         if unique:
             delete_local_account(unique)
         if not all([userEmail, password, lang, imageCodeId, valid_code]):
@@ -2990,6 +3014,8 @@ class Image_Code_RegisterView(TemplateView):
             "is_active": True,
             "user_isValid": True,
         }
+        if number:
+            create_data["region_country"] = number
         users = Device_User.objects.create(**create_data)
         return self.do_login(email_qs, response)
 
@@ -3244,6 +3270,7 @@ class v3LoginByCodeView(View):
         if oauth_qs.exists():
             auth_type = oauth_qs[0].authType
 
+
         if tko.code == 0:
             now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
             user_qs.update(last_login=now_time, language=response.lang)
@@ -3492,6 +3519,7 @@ class AppleAuthLogin(View):
         if oauth_qs.exists():
             auth_type = oauth_qs[0].authType
         res['authType'] = auth_type
+
         user_qs.update(last_login=now_time, online=True)
         return response.json(0, res)
 
@@ -3696,3 +3724,51 @@ def updateUserCountry(request):
         # CountryIPModel.objects.filter(id__in=tuple(ids)).update(status=1)
     response = ResponseObject()
     return response.json(0)
+
+
+class InitUserInformationView(View):
+
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation', None)
+        request_dict = request.GET
+        return self.validate(request_dict, operation)
+
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation', None)
+        request_dict = request.POST
+        return self.validate(request_dict, operation)
+
+    def validate(self, request_dict, operation):
+        token = TokenObject(request_dict.get('token', None))
+
+        response = ResponseObject()
+
+        if token.code != 0:
+            return response.json(token.code)
+
+        if operation == 'init':
+            return self.do_init(token.userID, request_dict, response)
+        else:
+            return response.json(444)
+
+    def do_init(self, userID, request_dict, response):
+        appBundleId = request_dict.get('appBundleId', None)
+
+        if appBundleId:
+            user_ex_qs = UserExModel.objects.filter(userID_id=userID)
+            now_time = int(time.time())
+            if user_ex_qs.exists():
+                update = {
+                    'appBundleId':appBundleId,
+                    'updTime': now_time
+                }
+                user_ex_qs.update(**update)
+            else:
+
+                user_ex = UserExModel(userID_id=userID, appBundleId=appBundleId, addTime=now_time, updTime=now_time)
+                user_ex.save()
+            return response.json(0)
+        else:
+            return response.json(444)

+ 270 - 0
Controller/VPGController.py

@@ -0,0 +1,270 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import os
+import re
+import time
+
+from django.db import transaction
+from django.views import View
+from django.views.decorators.csrf import csrf_exempt
+
+from Ansjer.config import BASE_DIR
+from Model.models import RegionModel, CompanyModel, VPGModel, UIDModel, MacModel, UIDCompanySerialModel
+from Object.uidManageResponseObject import uidManageResponseObject
+from Object.TokenObject import TokenObject
+from Service.CommonService import CommonService
+from Service.ModelService import ModelService
+
+
+class VPGView(View):
+
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation', None)
+        request_dict = request.GET
+        return self.validate(request_dict, operation)
+
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation', None)
+        request_dict = request.POST
+        return self.validate(request_dict, operation)
+
+    def validate(self, request_dict, operation):
+        token = TokenObject(request_dict.get('token', None))
+        response = uidManageResponseObject()
+
+        if token.code != 0:
+            return response.json(token.code)
+
+        if operation == 'add':
+            return self.do_add(token.userID, request_dict, response)
+        elif operation == 'update':
+            return self.do_update(token.userID, request_dict, response)
+        elif operation == 'delete':
+            return self.do_delete(token.userID, request_dict, response)
+        elif operation == 'list':
+            return self.do_list(token.userID, request_dict, response)
+        elif operation == 'uid_list':
+            return self.do_uid_list(token.userID, request_dict, response)
+        else:
+            return response.json(404)
+
+    def do_add(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        name = request_dict.get('vpg', None)
+        region_id = request_dict.get('region_id', None)
+        company_id = request_dict.get('company_id', None)
+
+        if name and region_id and company_id:
+            region_qs = RegionModel.objects.filter(id=region_id)
+            if not region_qs.exists():
+                return response.json(374)
+
+            company_qs = CompanyModel.objects.filter(secret=company_id)
+            if not company_qs.exists():
+                return response.json(373)
+
+            company = company_qs[0]
+            now_time = int(time.time())
+            vpgModel = VPGModel(name=name, region_id=region_id, company_id=company.id, add_time=now_time, update_time=now_time)
+            vpgModel.save()
+            return response.json(0)
+        else:
+            return response.json(444)
+
+    def do_update(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        id = request_dict.get('id', None)
+        name = request_dict.get('vpg', None)
+        region_id = request_dict.get('region_id', None)
+        company_id = request_dict.get('company_id', None)
+
+        if id:
+            vpg_qs = VPGModel.objects.filter(id=id)
+
+            if vpg_qs.exists():
+
+                now_time = int(time.time())
+                update = {
+                    'update_time': now_time
+                }
+
+                if name:
+                    update['name'] = name
+
+                if region_id:
+                    update['region_id'] = region_id
+
+                if company_id:
+                    update['company_id'] = company_id
+
+                vpg_qs.update(**update)
+                return response.json(0)
+            else:
+                return response.json(173)
+        else:
+            return response.json(444)
+
+    def do_delete(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        id = request_dict.get('id', None)
+        if id:
+            vpg_qs = VPGModel.objects.filter(id=id)
+
+            if vpg_qs.exists():
+                vpg_qs.delete()
+                return response.json(0)
+            else:
+                return response.json(173)
+        else:
+            return response.json(444)
+
+    def do_list(self, userID, request_dict, response):
+        # perm = ModelService.check_perm_uid_manage(userID, 0)
+        # if not perm:
+        #     return response.json(309)
+
+        company_id = request_dict.get('company_id', None)
+        region_id = request_dict.get('region_id', None)
+        page = request_dict.get('page', None)
+        line = request_dict.get('limit', None)
+
+        if page and line:
+            page = int(page)
+            line = int(line)
+
+            start = (page - 1) * line
+            end = start + line
+
+            vpg_qs = VPGModel.objects.filter()
+
+            if company_id:
+                vpg_qs.filter(company_id=company_id)
+
+            if region_id:
+                vpg_qs.filter(region_id=region_id)
+
+            count = vpg_qs.count()
+            vpg_qs = vpg_qs.values('id', 'name', 'region__name', 'region_id', 'company__name', 'add_time',
+                                   'update_time', 'company__secret', 'uid_count')
+            vpg_qs = vpg_qs[start:end]
+            # for vpg in vpg_qs:
+            #     vpg['uid_count'] = UIDModel.objects.filter(vpg_id=vpg['id']).count()
+
+            res = {
+                'count': count,
+                'data': list(vpg_qs),
+            }
+
+            return response.json(0, res)
+        else:
+            return response.json(444)
+
+
+    def do_uid_list(self, userID, request_dict, response):
+        vpg_id = request_dict.get('vpg_id', None)
+        page = int(request_dict.get('page', None))
+        line = int(request_dict.get('limit', None))
+
+        if not vpg_id:
+            return response.json(444)
+
+        start = (page - 1) * line
+        end = start + line
+        uid_qs = UIDModel.objects.filter(vpg_id=vpg_id).values('uid')
+
+        count = VPGModel.objects.get(id=vpg_id).uid_count   # 从vpg表获取uid总数
+        uid_qs = uid_qs[start:end]  # 显示条数
+        res = {
+            'count': count,
+            'data': list(uid_qs),
+        }
+        return response.json(0, res)
+
+
+@csrf_exempt
+def do_upload_uid(request):
+    # 上传UID,需要request.FILES,单独提取出来
+    # perm = ModelService.check_perm_uid_manage(userID, 0)
+    # if not perm:
+    #     return response.json(309)
+
+    request.encoding = 'utf-8'
+    response = uidManageResponseObject()
+    if request.method == "POST":
+        request_dict = request.POST
+    elif request.method == "GET":
+        request_dict = request.GET
+    else:
+        return response.json(444)
+    file = request.FILES.get('file', None)
+    vpg_id = request_dict.get('vpg_id', None)
+
+    bulk = []
+    add_time = update_time = int(time.time())
+    MAC = MacModel.objects.filter().values('id', 'value', 'is_active')[0]   # 获取最新可用的mac
+    current_mac = MAC['value']
+    if (not MAC['is_active']) or (current_mac[-8:] == 'FF.FF.FF'):
+        return response.json(175)
+
+    # path = '/'.join((BASE_DIR, 'static/uid')).replace('\\', '/') + '/'
+    # if not os.path.exists(path):
+    #     os.makedirs(path)
+    # full_path = path + str(file)
+    # with open(full_path, 'wb+') as uid_file:
+    try:
+        for chunk in file.chunks():
+            # str_chunk = str(chunk)
+            # print('str(chunk):', str_chunk)
+            # str_chunk = re.findall("b\'(.*)\'", str_chunk)[0]
+            # str_chunk = str_chunk.split('\\r\\n')
+            # print('str(chunk):', str_chunk)
+            uid_list = re.findall("b\'(.*)\'", str(chunk))[0].split('\\r\\n')
+            for uid in uid_list:
+                UID = UIDModel(
+                    mac=current_mac,
+                    uid_extra='',
+                    status=0,
+                    add_time=add_time,
+                    update_time=update_time,
+                    area=0,  # 关联vgp表已有区域信息,可以考虑去掉
+                    vpg_id=vpg_id,
+                )
+                if len(uid) == 14:  # 宸云
+                    UID.p2p_type = 1
+                    UID.uid = uid
+                elif len(uid) == 20:    # tutk
+                    UID.p2p_type = 2
+                    UID.uid = uid
+                elif len(uid) == 23:    # 宸云完整uid
+                    a = uid.split('-')
+                    new_uid = a[0] + a[1] + a[2].split(',')[0]
+                    UID.p2p_type = 1
+                    UID.uid = new_uid
+                    UID.full_uid_code = uid
+                bulk.append(UID)
+                temp_mac = CommonService.updateMac(current_mac)    # mac地址值+1;后3个字节为FF时返回None
+                if temp_mac:
+                    current_mac = temp_mac  # 更新赋值写入uid表
+                else:
+                    temp_mac = current_mac  # 赋值为FF写入mac表
+                    break
+        with transaction.atomic():
+            UIDModel.objects.bulk_create(bulk)  # 批量写入uid数据
+            uid_count = UIDModel.objects.filter(vpg_id=vpg_id).count()  # 获取族群下uid的数量
+            VPGModel.objects.filter(id=vpg_id).update(uid_count=uid_count)   # 更新vgp表的uid_count
+            MacModel.objects.filter().update(value=temp_mac)  # 更新mac表的mac地址值
+        return response.json(0)
+    except Exception as e:
+        print(e)
+        return response.json(500, repr(e))

+ 121 - 0
Controller/VerifyCodeController.py

@@ -0,0 +1,121 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+from django.views import View
+
+from Controller.CheckUserData import DataValid
+from Object.RedisObject import RedisObject
+from Object.ResponseObject import ResponseObject
+from Object.TokenObject import TokenObject
+from Service.CommonService import CommonService
+
+
+class VerifyCodeView(View):
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation', None)
+        request_dict = request.GET
+        return self.validate(request_dict, operation)
+
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation', None)
+        request_dict = request.POST
+        return self.validate(request_dict, operation)
+
+    def validate(self, request_dict, operation):
+
+        response = ResponseObject()
+
+        if operation == 'forget':
+            return self.verify_forget(request_dict, response)
+        elif operation == 'register':
+            return self.verify_register(request_dict, response)
+        elif operation == 'image':
+            return self.verify_image(request_dict, response)
+        else:
+            return response.json(404)
+
+    def verify_forget(self, request_dict, response):
+        email = request_dict.get('email', None)
+        phone = request_dict.get('phone', None)
+        authcode = request_dict.get('authcode', None)
+        key = '_forgetPwdResetCode'
+
+        if authcode is None:
+            return response.json(444)
+
+        authcode = CommonService.decode_data(authcode)
+
+        if email is not None:
+            email = email.strip()
+            return self.email_validate(key, email, authcode, response)
+        elif phone is not None:
+            phone = phone.strip()
+            return self.phone_validate(key, phone, authcode, response)
+        else:
+            return response.json(444)
+
+    def verify_register(self, request_dict, response):
+        email = request_dict.get('email', None)
+        phone = request_dict.get('phone', None)
+        authcode = request_dict.get('authcode', None)
+        key = '_identifyingCode'
+        if authcode is None:
+            return response.json(444)
+
+        authcode = CommonService.decode_data(authcode)
+
+        if email is not None:
+            email = email.strip()
+            return self.email_validate(key, email, authcode, response)
+        elif phone is not None:
+            phone = phone.strip()
+            return self.phone_validate(key, phone, authcode, response)
+        else:
+            return response.json(444)
+
+    def verify_image(self, request_dict, response):
+        imageCodeId = request_dict.get('imageCodeId', None)
+        authcode = request_dict.get('authcode', None)
+
+        if imageCodeId and authcode:
+
+            authcode = CommonService.decode_data(authcode)
+            image_code_key = 'image_code_' + imageCodeId
+            redisObj = RedisObject(db=6)
+            # redis里面的验证码
+            redis_image_code = redisObj.get_data(key=image_code_key)
+            # 验证用户输入的验证码和redis中的验证码
+            if redis_image_code is False or authcode.lower() != redis_image_code.lower():
+                return response.json(121)
+            else:
+                return response.json(0)
+        else:
+            return response.json(444)
+
+    def email_validate(self, key, email, authcode, response):
+        authcode.strip()
+        data_valid = DataValid()
+        if data_valid.email_validate(email) is not True:
+            return response.json(105)
+        reds = RedisObject()
+        resetCode = reds.get_data(key=email + key)
+        if resetCode is False:
+            return response.json(120)
+        if authcode != resetCode:
+            return response.json(121)
+        return response.json(0)
+
+    def phone_validate(self, key, phone, authcode, response):
+        authcode.strip()
+        data_valid = DataValid()
+        if data_valid.mobile_validate(phone) is not True:
+            return response.json(100)
+        reds = RedisObject()
+        resetCode = reds.get_data(key=phone + key)
+        if resetCode is False:
+            return response.json(120)
+        print(resetCode)
+        if authcode != resetCode:
+            return response.json(121)
+        return response.json(0)

+ 13 - 8
Controller/VodBucket.py

@@ -18,10 +18,12 @@ from django.utils.decorators import method_decorator
 from django.views.decorators.csrf import csrf_exempt
 from django.views.generic.base import View
 
-from Model.models import VodBucketModel, UID_Bucket, Store_Meal, Device_Info, OssCrdModel
+from Model.models import VodBucketModel, UID_Bucket, Store_Meal, Device_Info, OssCrdModel, VodHlsModel, StsCrdModel, \
+    Unused_Uid_Meal
 from Object.ResponseObject import ResponseObject
 from Object.TokenObject import TokenObject
 from Service.ModelService import ModelService
+from django.db import transaction
 import time
 
 
@@ -239,13 +241,16 @@ class UidBucketView(View):
             id = request_dict.get('id', None)
             page = int(request_dict.get('page', None))
             line = int(request_dict.get('line', None))
-            d_ubqs = UID_Bucket.objects.filter(id=id)
-            uid = d_ubqs[0].uid
-            channel = d_ubqs[0].channel
-            d_ubqs.delete()
-            oss_crd_qs = OssCrdModel.objects.filter(uid=uid, channel=channel)
-            if oss_crd_qs.exists():
-                oss_crd_qs.delete()
+            uid_bucket_qs = UID_Bucket.objects.filter(id=id)
+            uid = uid_bucket_qs[0].uid
+            bucket_id = uid_bucket_qs[0].bucket_id
+            # channel = uid_bucket_qs[0].channel
+            with transaction.atomic():
+                uid_bucket_qs.delete()
+                # OssCrdModel.objects.filter(uid=uid, channel=channel).delete()
+                VodHlsModel.objects.filter(uid=uid).delete()
+                StsCrdModel.objects.filter(uid=uid).delete()
+                Unused_Uid_Meal.objects.filter(uid=uid).delete()
         except Exception as e:
             return response.json(10, repr(e))
         else:

+ 0 - 0
Model/__init__.py


+ 31 - 29
Model/models.py

@@ -118,22 +118,6 @@ class Role(models.Model):
             permslist.sort()
             return permslist
 
-
-class RegionCountryModel(models.Model):
-    number = models.IntegerField(primary_key=True, verbose_name='唯一标识')
-    region_id = models.IntegerField(verbose_name='大洲编号')
-    name = models.CharField(max_length=50, verbose_name=u'名称')
-    cn = models.CharField(blank=True, max_length=64, verbose_name=u'中文名称')
-    en = models.CharField(blank=True, max_length=64, verbose_name=u'英文名称')
-    add_time = models.IntegerField(default=0, verbose_name='添加时间')
-    update_time = models.IntegerField(default=0, verbose_name='更新时间')
-
-    class Meta:
-        db_table = 'region_country'
-        verbose_name = '地区表'
-        verbose_name_plural = verbose_name
-
-
 class Device_User(AbstractBaseUser):
     userID = models.CharField(blank=True, max_length=32, primary_key=True,
                               verbose_name=u'用户ID', unique=True)
@@ -257,8 +241,7 @@ class Device_Info(models.Model):
     isVod = models.SmallIntegerField(blank=True, default=0, verbose_name='是否支持云存')  # 是否支持云存设备
     isExist = models.SmallIntegerField(blank=True, default=1, verbose_name='是否被删除')  # 是否被删除了(需主用户交互) 1存在,0不存在,2设备被重置
     isCameraOpenCloud =  models.SmallIntegerField(blank=True, default=1, verbose_name='是否开启云存')  # 0:不开启  1:开启
-    endpoint = models.CharField(blank=True, max_length=256, default='', verbose_name=u'iot端点')
-    token_iot_number = models.CharField(blank=True, default='', max_length=50, verbose_name='连接iot令牌')
+    serial_number = models.CharField(blank=True, max_length=9, default='', verbose_name='关联序列号')
     ###
     REQUIRED_FIELDS = []
 
@@ -303,7 +286,7 @@ class Access_Log(models.Model):
 
 class Equipment_Info(models.Model):
     id = models.AutoField(primary_key=True, verbose_name=u'自增标记ID')
-    devUid = models.CharField(default='', blank=True, max_length=32, verbose_name=u'设备ID')
+    devUid = models.CharField(default='', db_index=True, blank=True, max_length=32, verbose_name=u'设备ID')
     devNickName = models.CharField(blank=True, max_length=32, default='', verbose_name=u'设备昵称')
     Channel = models.IntegerField(default=1, blank=True, verbose_name=u'设备通道')
     eventType = models.IntegerField(default=0, blank=True, verbose_name=u'事件类型')
@@ -1327,6 +1310,9 @@ class CompanyModel(models.Model):
 class RegionModel(models.Model):
     id = models.AutoField(primary_key=True)
     name = models.CharField(max_length=32, default='', verbose_name='区域名称')
+    continent_code = models.CharField(max_length=3, default='', verbose_name='洲代码')
+    api = models.CharField(max_length=50, default='', verbose_name='请求地址')
+
 
     class Meta:
         db_table = 'tb_region'
@@ -1337,6 +1323,7 @@ class RegionModel(models.Model):
 class VPGModel(models.Model):
     id = models.AutoField(primary_key=True)
     name = models.CharField(max_length=32, default='', verbose_name='群组名称')
+    uid_count = models.IntegerField(default=0, verbose_name='uid数量')
     region = models.ForeignKey(RegionModel, to_field='id', on_delete=models.DO_NOTHING, verbose_name='群组用于的地区')
     company = models.ForeignKey(CompanyModel, to_field='id', on_delete=models.DO_NOTHING, verbose_name='关联企业表')
     add_time = models.IntegerField(default=0, verbose_name='添加时间')
@@ -1351,13 +1338,15 @@ class VPGModel(models.Model):
 class UIDModel(models.Model):
     id = models.AutoField(primary_key=True)
     uid = models.CharField(max_length=20, null=False, db_index=True, unique=True, verbose_name='设备id')
-    mac = models.CharField(max_length=17, null=False, default='', verbose_name='设备id对应的mac地址')
+    mac = models.CharField(max_length=17, null=False, default='', unique=True, verbose_name='设备id对应的mac地址')
     uid_extra = models.TextField(default='', verbose_name='uid的额外描述')
-    status = models.SmallIntegerField(default=0, verbose_name='使用状态')
+    status = models.SmallIntegerField(default=0, verbose_name='使用状态')   # 0:未分配,1:已分配,2:已使用
     add_time = models.IntegerField(default=0, verbose_name='添加时间')
     update_time = models.IntegerField(default=0, verbose_name='更新时间')
     area = models.SmallIntegerField(default=0, verbose_name='区域')  #0:国内;1:国外
     vpg = models.ForeignKey(VPGModel, to_field='id', default=1, on_delete=models.DO_NOTHING, verbose_name='关联VPG表的id')
+    p2p_type = models.IntegerField(default=1, verbose_name='p2p类型。1:宸云,2:tutk')
+    full_uid_code = models.CharField(max_length=256, default='', verbose_name='宸云完整uid')
 
     class Meta:
         ordering = ('-add_time',)
@@ -1470,6 +1459,8 @@ class CountryModel(models.Model):
     add_time = models.IntegerField(default=0, verbose_name='添加时间')
     update_time = models.IntegerField(default=0, verbose_name='更新时间')
     region = models.ForeignKey(RegionModel, to_field='id', on_delete=models.DO_NOTHING, verbose_name='关联区域表')
+    country_code = models.CharField(max_length=2, default='', verbose_name='国家iso2代码')
+    country_name = models.CharField(max_length=20, default='', verbose_name='国家名')
 
     class Meta:
         db_table = 'tb_country'
@@ -1506,8 +1497,9 @@ class CountryLanguageModel(models.Model):
 
 class SerialNumberModel(models.Model):
     id = models.AutoField(primary_key=True)
-    serial_number = models.CharField(max_length=9, db_index=True, verbose_name='序列号')
+    serial_number = models.CharField(max_length=9, db_index=True, unique=True, verbose_name='序列号')
     status = models.SmallIntegerField(default=1, verbose_name='可用状态。0:不可用,1:可用')
+    p2p = models.SmallIntegerField(default=0, verbose_name='p2p类型。0:无,1:宸云,2:tutk')
     add_time = models.IntegerField(default=0, verbose_name='添加时间')
 
     class Meta:
@@ -1545,14 +1537,24 @@ class UIDCompanySerialModel(models.Model):
 
 class iotdeviceInfoModel(models.Model):
     id = models.AutoField(primary_key=True)
-    uid = models.CharField(blank=True, max_length=32, default='', verbose_name=u'设备uid')
-    certificateId = models.CharField(blank=True, max_length=256, default='', verbose_name=u'证书id')
-    certificatePem = models.TextField(blank=True, default='', verbose_name=u'证书项目')
-    publicKey = models.TextField(blank=True, default='', verbose_name=u'公有密钥')
-    privateKey = models.TextField(blank=True, default='', verbose_name=u'私有密钥')
-    Thingname = models.CharField(blank=True, max_length=256, default='', verbose_name=u'IoT Thing Name')
-
+    serial_number = models.ForeignKey(SerialNumberModel, to_field='id', default='', on_delete=models.CASCADE, verbose_name='关联序列号表的id')
+    certificate_id = models.CharField(blank=True, max_length=256, default='', verbose_name=u'证书id')
+    certificate_pem = models.TextField(blank=True, default='', verbose_name=u'证书项目')
+    public_key = models.TextField(blank=True, default='', verbose_name=u'公有密钥')
+    private_key = models.TextField(blank=True, default='', verbose_name=u'私有密钥')
+    thing_name = models.CharField(blank=True, max_length=256, default='', verbose_name=u'IoT Thing Name')
+    endpoint = models.CharField(blank=True, max_length=256, db_index=True, default='', verbose_name=u'iot端点')
+    token_iot_number = models.CharField(blank=True,  db_index=True ,default='', max_length=50, verbose_name='连接iot令牌')
     class Meta:
         db_table = 'iot_deviceInfo'
         verbose_name = 'iot设备信息表'
+        verbose_name_plural = verbose_name
+
+class UIDMainUser(models.Model):
+    id = models.AutoField(primary_key=True)
+    UID = models.CharField(blank=True, max_length=32, verbose_name=u'设备UID', default='')
+    user_id = models.CharField(blank=True, max_length=32, verbose_name=u'用户ID', default='')
+    class Meta:
+        db_table = 'uid_mainuser'
+        verbose_name = '设备主用户表'
         verbose_name_plural = verbose_name

+ 3 - 0
Model/tests.py

@@ -0,0 +1,3 @@
+from django.test import TestCase
+
+# Create your tests here.

+ 3 - 0
Model/views.py

@@ -0,0 +1,3 @@
+from django.shortcuts import render
+
+# Create your views here.

+ 157 - 0
Object/IOTCore/IotObject.py

@@ -0,0 +1,157 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import json
+from abc import ABCMeta,abstractmethod
+
+import boto3
+
+from Ansjer.config import AWS_IOT_SES_ACCESS_CHINA_REGION, AWS_IOT_SES_ACCESS_CHINA_ID, AWS_IOT_SES_ACCESS_CHINA_SECRET, \
+    AWS_IOT_SES_ACCESS_FOREIGN_REGION_AMERICA, AWS_IOT_SES_ACCESS_FOREIGN_ID, AWS_IOT_SES_ACCESS_FOREIGN_SECRET, \
+    AWS_IOT_SES_ACCESS_FOREIGN_REGION_EUROPE, AWS_IOT_SES_ACCESS_FOREIGN_REGION_ASIA
+
+
+class IOTObject(metaclass=ABCMeta):
+
+    @abstractmethod
+    def create_provisioning_claim(self, templateName):
+        pass
+
+    @abstractmethod
+    def create_keys_and_certificate(self, uid):
+        pass
+
+
+class IOTClient(IOTObject):
+
+    def __init__(self, region_id = 1):
+
+        if region_id == 1:
+            self.client = boto3.client('iot', region_name=AWS_IOT_SES_ACCESS_CHINA_REGION,
+                                       aws_access_key_id=AWS_IOT_SES_ACCESS_CHINA_ID,
+                                       aws_secret_access_key=AWS_IOT_SES_ACCESS_CHINA_SECRET)
+            self.endpoint = 'a250bbr0p9u7as-ats.iot.cn-northwest-1.amazonaws.com.cn'
+
+        if region_id == 2:
+            self.client = boto3.client('iot', region_name=AWS_IOT_SES_ACCESS_FOREIGN_REGION_ASIA,
+                                       aws_access_key_id=AWS_IOT_SES_ACCESS_FOREIGN_ID,
+                                       aws_secret_access_key=AWS_IOT_SES_ACCESS_FOREIGN_SECRET)
+            self.endpoint = 'a2rqy12o004ad8-ats.iot.ap-southeast-1.amazonaws.com'
+
+        if region_id == 3:
+            self.client = boto3.client('iot', region_name=AWS_IOT_SES_ACCESS_FOREIGN_REGION_AMERICA,
+                                       aws_access_key_id=AWS_IOT_SES_ACCESS_FOREIGN_ID,
+                                       aws_secret_access_key=AWS_IOT_SES_ACCESS_FOREIGN_SECRET)
+            self.endpoint = 'a2rqy12o004ad8-ats.iot.us-east-1.amazonaws.com'
+
+        if region_id == 4:
+            self.client = boto3.client('iot', region_name=AWS_IOT_SES_ACCESS_FOREIGN_REGION_EUROPE,
+                                       aws_access_key_id=AWS_IOT_SES_ACCESS_FOREIGN_ID,
+                                       aws_secret_access_key=AWS_IOT_SES_ACCESS_FOREIGN_SECRET)
+            self.endpoint = 'a2rqy12o004ad8-ats.iot.eu-west-1.amazonaws.com'
+
+
+
+    def create_provisioning_claim(self, templateName):
+
+        result = self.client.create_provisioning_claim(templateName=templateName)
+
+        res = {
+            'certificateId': result['certificateId'],
+            'certificatePem': result['certificatePem'],
+            'publicKey': result['keyPair']['PublicKey'],
+            'privateKey': result['keyPair']['PrivateKey'],
+            'endpoint': self.endpoint
+        }
+        return res
+
+    def create_keys_and_certificate(self, serial_number, thingGroup):
+        try:
+            result = self.client.create_keys_and_certificate(setAsActive=True)
+            res = {
+                'certificateId': result['certificateId'],
+                'certificatePem': result['certificatePem'],
+                'publicKey': result['keyPair']['PublicKey'],
+                'privateKey': result['keyPair']['PrivateKey'],
+                'endpoint': self.endpoint
+            }
+            # 搜索是否存在该物品组
+            thing_groups_res = self.client.list_thing_groups(nextToken='', maxResults=1,
+                                                             namePrefixFilter=thingGroup, recursive=False)
+            if thing_groups_res['thingGroups']:
+                thingGroupName = thing_groups_res['thingGroups'][0]['groupName']  # 获取物品组名称
+            else:
+                attributes = {
+                    "update_time": "0"
+                }
+                thingGroupProperties = {
+                    "thingGroupDescription": "OTA",
+                    "attributePayload": {
+                        "attributes": attributes,
+                        "merge": False  # 更新时覆盖掉而不是合并
+                    }
+                }
+                create_thing_group_res = self.client.create_thing_group(thingGroupName=thingGroup,
+                                                                        thingGroupProperties=thingGroupProperties)
+                thingGroupName = create_thing_group_res['thingGroupName']  # 获取物品组名称
+            print('物品组:', thingGroupName)
+            # 根据证书ID注册物品和策略
+            templateBody = {
+                "Parameters": {
+                    "ThingName": {
+                        "Type": "String"
+                    },
+                    "SerialNumber": {
+                        "Type": "String"
+                    },
+                    "thingGroupName": {
+                        "Type": "String"
+                    },
+                    "AWS::IoT::Certificate::Id": {
+                        "Type": "String"
+                    }
+                },
+                "Resources": {
+                    "thing": {
+                        "Type": "AWS::IoT::Thing",
+                        "Properties": {
+                            "AttributePayload": {},
+                            # "ThingGroups" : ["v1-lightbulbs", {"Ref" : "DeviceLocation"}],
+                            "ThingName": {
+                                "Ref": "ThingName"
+                            },
+                            "ThingGroups": [{"Ref": "thingGroupName"}]
+                        },
+                        "OverrideSettings": {
+                            "AttributePayload": "MERGE",
+                            "ThingTypeName": "REPLACE",
+                            "ThingGroups": "DO_NOTHING"
+                        }
+                    },
+                    "certificate": {
+                        "Type": "AWS::IoT::Certificate",
+                        "Properties": {
+                            "CertificateId": {"Ref": "AWS::IoT::Certificate::Id"},
+                            "Status": "Active"
+                        }
+                    },
+                    "policy": {
+                        "Properties": {
+                            "PolicyName": "My_Iot_Policy"
+                        },
+                        "Type": "AWS::IoT::Policy"
+                    },
+                }
+            }
+
+            templateBody = json.dumps(templateBody)
+            parameters = {"ThingName": "Ansjer_Device_" + serial_number,
+                          "thingGroupName": thingGroupName,
+                          "AWS::IoT::Certificate::Id": res['certificateId']}
+            self.client.register_thing(
+                templateBody=templateBody,
+                parameters=parameters
+            )
+            return res, parameters
+        except Exception as e:
+            print(e)
+            # return response.json(500, repr(e))

+ 210 - 0
Object/LogsObject.py

@@ -0,0 +1,210 @@
+from django.shortcuts import HttpResponse
+import simplejson as json
+
+
+class LogsObject(object):
+    def __init__(self, lang='en'):
+        self.lang = lang
+
+    def data(self, code, res={}):
+        data_en = {
+            0: 'Success',
+            5: 'Please try again one minute later!',
+            10: res,
+            12: 'You are not the primary user of the device!',
+            14: 'Device is not belong to you',
+            15: 'Device has been bound',
+            16: 'WeChat has been bound, please log in and unbind using WeChat',
+            17: 'No email or mobile phone login',
+            44: 'System error! Can not send email',
+            48: 'System object error!',
+            89: 'Already send the code, please check it or get it again after 10m',
+            90: 'please check code or get it again after 1m',
+            99: 'Mail doesn\'t exist!',
+            100: 'Phone format error!',
+            101: 'Phone already existed!',
+            102: 'Phone doesn\'t exist!',
+            103: 'Mail already existed!',
+            104: 'Account doesn\'t exist!',
+            105: 'Email format error!',
+            107: 'The username not conform to the rules!',
+            109: 'The password not conform to the rules!',
+            110: 'user doesn\'t activated',
+            111: 'Error password',
+            112: 'Fingerprint login is not turned on',
+            119: 'The qr code has expired',
+            120: 'The code has expired',
+            121: 'The verification code is wrong!',
+            173: 'Data does not exists!',
+            174: 'Data already exists!',
+            176: 'Delete error',
+            177: 'Update error',
+            178: 'ADD error',
+            179: 'Nickname repeated',
+            201: 'You can only add 3 custom voice at most',
+            306: 'The link has expired!',
+            309: 'Please ReLogin! errmsg token',
+            404: 'You don not have permission to access this!',
+            414: 'Please confirm the request url!',
+            424: 'Database Error !',
+            444: 'Wrong parameters!',
+            474: 'System Maintaining!',
+            475: 'App Version too low, please upgrade!',
+            500: 'Query Database Error:',
+            700: 'Upload file error',
+            701: 'The file does not exist!',
+            711: 'Do not downgrade',
+            712: 'Area needs to be consistent',
+            713: 'Storage rules cannot be changed during the validity period',
+            717: 'Authorization expires',
+            800: 'Order does not exist',
+            801: 'The refund amount cannot be greater than the order price',
+            802: 'The order has been completed and cannot be cancelled',
+            804: 'Refund, please do not repeat the operation',
+            900: 'There is no information about this version!',
+            901: 'Getting URL failure!',
+            902: 'No update!',
+            903: 'Error filename',
+            904: 'Version does not support this feature!',
+            906: 'Cause of file operation error',
+            907: 'The download file does not exist!',
+            908: 'userId cannot be empty',
+            10001: 'Customer number, customer confidentiality error',
+            10002: 'Check your configuration: no customer number, customer confidentiality',
+            10003: 'The authorization code does not exist. Please reauthorize',
+            10004: 'The request method is incorrect. Please contact the developer',
+            10005: 'Wrong configuration, wrong customer number',
+            10006: 'Configuration error. The path value is incorrect',
+            10007: 'This device is not an experience package and cannot be reset',
+            10008: 'The user does not have this device and cannot transfer',
+            10009: 'The user already owns the device and cannot transfer it',
+            10010: 'Devices that are not under the same account cannot be transferred',
+            10011: 'Receiving transfer device does not exist and cannot be transferred',
+            10012: 'Experience packages cannot be transferred',
+            10013: 'Original equipment package has expired and cannot be transferred',
+            10014: 'Accept transfer of equipment packages that have not expired and cannot be transferred',
+            10015: 'Shared devices cannot be transferred',
+            10030: 'No purchase of cloud storage',
+            10031: 'The cloud storage has expired',
+            10032: 'The switched cloud storage package ID cannot be the same as the one in use',
+            10033: 'The primary user of the device cannot purchase it',
+            10034: 'Non device primary users cannot view cloud storage',
+            10035: 'Non device primary users cannot experience cloud storage',
+            10036: 'Non device primary users cannot exchange for cloud storage',
+            10037: 'Non device primary user cannot transfer device',
+            10038: 'Non device primary user cannot transfer packages',
+            10039: 'Activation code has been used',
+            10040: 'Invalid activation code'
+        }
+        data_cn = {
+            0: '成功',
+            5: '请一分钟后再尝试',
+            10: res,
+            12: '非设备主用户',
+            14: '设备不属于您',
+            15: '设备已被绑定',
+            16: '微信已被绑定,请使用微信登录并解绑',
+            17: '未绑定邮箱或者手机登录方式',
+            44: '系统错误!无法发送电子邮件',
+            48: '系统对象错误',
+            89: '已发验证码,请检测或10分钟后重新获取。',
+            90: '请检测或1分钟后重新获取。',
+            99: '邮箱不存在!',
+            100: '手机格式错误!',
+            101: '手机已存在!',
+            102: '手机不存在!',
+            103: '邮箱已存在!',
+            104: '账户不存在!',
+            105: '邮箱格式错误!',
+            107: '用户名格式不符合!',
+            109: '密码格式不符合!',
+            110: '用户未激活!',
+            111: '密码不正确!',
+            112: '未开通指纹登录',
+            119: '二维码过期',
+            120: '验证码过期',
+            121: '验证码错了!',
+            173: '数据不存在!',
+            174: '数据已存在!',
+            176: '删除错误',
+            177: '更新错误',
+            178: '增加错误',
+            179: '名称不能重复',
+            201: '最多只能添加3条自定义语音',
+            306: '链接已超过有效期!',
+            309: '请重新登录!',
+            404: '您没有访问的权限!',
+            414: '请确认请求url!',
+            424: '数据库错误!',
+            444: '参数错误!',
+            474: '系统维护中!',
+            475: '版本过低,请升级程序!',
+            500: '查询数据库错误!',
+            700: '上传文件错误',
+            701: '文件不存在',
+            711: '不可降级',
+            712: '区域不一致',
+            713: '有效期内不可更改存储规则',
+            717: '授权过期',
+            800: '订单不存在',
+            801: '退款金额不能大于订单价格',
+            802: '订单已完成,不能撤销',
+            804: '订单已退款,请勿重复操作',
+            900: '版本信息不存在',
+            901: '获取链接失败',
+            902: '无更新!',
+            903: '文件名不符合!',
+            904: '版本不支持本功能!',
+            906: '文件操作错误',
+            907: '文件不存在!',
+            908: '用户id不能为空',
+            10001: '客户编号,客户机密错误',
+            10002: '检查您的配置:没有客户编号,客户机密',
+            10003: '授权码不存在,请重新授权',
+            10004: '请求方法不正确。请联系开发者',
+            10005: '配置错误,客户编号这个值是错误的',
+            10006: '配置错误,路径这个值是错误的',
+            10007: '此设备不是体验套餐,无法重置',
+            10008: '用户没有此设备,无法转移',
+            10009: '用户已拥有此设备,无法转移',
+            10010: '不是同一账户下的设备,无法转移',
+            10011: '接受转移设备不存在,无法转移',
+            10012: '体验套餐无法转移',
+            10013: '原设备套餐已过期,无法转移',
+            10014: '接受转移设备套餐未过期,无法转移',
+            10015: '分享的设备无法转移',
+            10030: '未购买云存',
+            10031: '云存已过期',
+            10032: '切换的云存套餐ID不能与正在使用中的相同',
+            10033: '非设备主用户无法购买',
+            10034: '非设备主用户无法查看云存',
+            10035: '非设备主用户无法体验云存',
+            10036: '非设备主用户无法兑换云存',
+            10037: '非设备主用户无法转移设备',
+            10038: '非设备主用户无法转移套餐',
+            10039: '激活码已被使用过',
+            10040: '无效激活码'
+        }
+        if self.lang == 'cn':
+            msg = data_cn
+        elif self.lang == 'zh-Hans':
+            msg = data_cn
+        elif self.lang == 'zh-Hant':
+            msg = data_cn
+        else:
+            msg = data_en
+        try:
+            message = msg[code]
+        except Exception as e:
+            message = '系统错误,code不存在'
+        print(self.lang == 'cn')
+        print(msg)
+        return {'result_code': code, 'reason': message, 'result': res, 'error_code': code}
+
+    def formal(self, code, res={}):
+        formal_data = self.data(code, res)
+        return json.dumps(formal_data, ensure_ascii=False)
+
+    def json(self, code, res={}):
+        result = self.formal(code, res)
+        return HttpResponse(result)

+ 7 - 0
Object/RedisObject.py

@@ -70,6 +70,13 @@ class RedisObject:
     def rpush(self, name, val):
         self.CONN.rpush(name, val)
 
+    def lpop(self, key):
+        val = self.CONN.lpop(key)
+        if val:
+            return val.decode('utf-8')
+        else:
+            return False
+
     # 获取列表长度
     def llen(self, name):
         return self.CONN.llen(name=name)

+ 24 - 4
Object/TokenObject.py

@@ -43,10 +43,10 @@ class TokenObject:
             self.lang = res.get('lang', None)
             self.user = res.get('user', '')
             # 刷新登录时间
-            if self.userID:
-                print(self.user)
-                redisObj = RedisObject(db=3)
-                redisObj.set_data(key=self.userID, val=self.user, expire=300)
+            # if self.userID:
+            #     print(self.user)
+            #     redisObj = RedisObject(db=3)
+            #     redisObj.set_data(key=self.userID, val=self.user, expire=300)
 
         except jwt.ExpiredSignatureError as e:
             print('过期')
@@ -97,6 +97,26 @@ class TokenObject:
             self.code = 0
             return res
 
+    def encryption(self, data={}):
+        try:
+            access_expire = int(OAUTH_ACCESS_TOKEN_TIME.total_seconds())
+            refresh_expire = int(OAUTH_REFRESH_TOKEN_TIME.total_seconds())
+            now_stamp = int(time.time())
+            access_data = data
+            refresh_data = data
+            access_data['exp'] = access_expire + now_stamp
+            refresh_data['exp'] = refresh_expire + now_stamp
+            access_token = jwt.encode(access_data,
+                                      OAUTH_ACCESS_TOKEN_SECRET,
+                                      algorithm='HS256')
+            return access_token.decode('utf-8')
+        except Exception as e:
+            self.code = 309
+            print(repr(e))
+        else:
+            self.code = 0
+            return res
+
     def refresh(self):
         if not self.token:
             self.code = 309

+ 113 - 0
Object/uidManageResponseObject.py

@@ -0,0 +1,113 @@
+from django.shortcuts import HttpResponse
+import simplejson as json
+
+
+class uidManageResponseObject(object):
+
+    def __init__(self, lang='cn'):
+        self.lang = lang
+
+    def data(self, code, res={}):
+        data_cn = {
+            0: '成功',
+            5: '请一分钟后再尝试',
+            8: '用户账号已存在',
+            9: '用户账号不存在',
+            10: res,
+            42: '两次输入的新密码错误',
+            43: '客户端服务器已关闭,请下载新版本使用',
+            44: '系统错误,发送邮件失败',
+            45: '系统错误,生成令牌出错!',
+            46: '系统错误,发送短信失败!',
+            47: '旧密码不正确',
+            74: '关联旧用户失败!',
+            79: '您已经申请过重置密码,请到邮箱进行确认!',
+            89: '您已经获得了验证码,请在10分钟后检查或再次确认。',
+            99: '账户或密码错误',
+            101: '手机的用户账号已经存在!',
+            102: '手机的用户账号不存在!',
+            103: '邮箱用户帐户已经存在!',
+            104: '邮箱用户帐户不存在!',
+            107: '用户名格式不符合规则!',
+            108: '邮箱格式不符合规则!',
+            110: '因为用户未激活,用户是无效用户!',
+            111: '您输入的密码不正确!',
+            120: '验证码已过期或不存在、请重新获得验证码!',
+            121: '验证码错了!',
+            138: '手机格式不符合规则!',
+            173: '数据不存在!',
+            174: '数据已存在',
+            175: 'mac地址已用完',
+            176: '数据库异常',
+            305: '令牌格式是错误的,相关参数是不存在的!',
+            307: '令牌已过期!',
+            308: '此次下载已失效',
+            309: '你没有权限访问',
+            373: '没有相应的公司',
+            374: '没有相应的地区',
+            375: 'uid不足',
+            404: 'You don not have permission to access this!',
+            444: '请确认参数的正确性!',
+            1112: '您输入的两次密码不一致!',
+            208: '只能预定当天的或者以后的!',
+        }
+        data_en = {
+            0: 'Success',
+            5: 'Please try again one minute later!',
+            8: 'User accounts already exist',
+            9: 'User accounts is not exist',
+            10: res,
+            42: 'The new password entered twice is incorrect',
+            43: 'The client server is closed. Please download the new version for use',
+            44: 'System error,send email fail!',
+            45: 'System error,generate token fail!',
+            46: 'System error, sending SMS failed!',
+            47: 'Old password is incorrect',
+            74: 'Failed to connect old users!',
+            79: 'You have applied for reset password, please go to email for confirmation!',
+            89: 'You have already obtained the verification code, please check it or get it again after 10 minutes.',
+            99: ' ERROR Incorrect account or password',
+            101: 'The user account of the mobile phone has already existed!',
+            102: 'The user account of the mobile phone does not exist!',
+            103: 'The mailbox user account has already existed!',
+            104: 'The mailbox user account does not exist!',
+            107: 'The username format does not conform to the rules!',
+            108: 'The mailbox format does not conform to the rules! ',
+            110: 'Because the user is not activated, the user is an invalid user!',
+            111: 'The password you entered is incorrect!',
+            120: 'The captcha has expired or does not exist, please obtain the captcha again!',
+            121: 'The verification code is wrong!',
+            138: 'The phone format does not conform to the rules! ',
+            173: 'Data does not exists!',
+            174: 'Data already exists',
+            175: 'MAC address has been used up',
+            176: 'Database exception',
+            305: 'The Token format is wrong and the related parameter is None!',
+            307: 'The Token has expired!',
+            308: 'This download has expired!',
+            309: 'You have no access',
+            373: 'No corresponding company',
+            374: 'Region does not exist',
+            375: 'uid不足',
+            404: 'You don not have permission to access this!',
+            444: 'Please confirm the correctness of the parameters!',
+            1112: 'The two passwords you entered do not match!',
+        }
+
+        if self.lang == 'cn':
+            msg = data_cn
+        else:
+            msg = data_en
+        try:
+            message = msg[code]
+        except Exception as e:
+            message = '系统错误,code不存在'
+        return {'result_code': code, 'reason': message, 'result': res, 'error_code': code}
+
+    def formal(self, code, res={}):
+        formal_data = self.data(code, res)
+        return json.dumps(formal_data,ensure_ascii=False)
+
+    def json(self, code, res={}):
+        result = self.formal(code, res)
+        return HttpResponse(result)

+ 55 - 0
Service/AlgorithmService.py

@@ -0,0 +1,55 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import math
+
+
+class AlgorithmBaseOn35:
+
+    letters = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
+               'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
+               'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T',
+               'U', 'V', 'W', 'X', 'Y', 'Z']
+
+    len1 = len(letters)
+
+    def getLetter(self, number):
+        tmp = int(number / self.len1)
+        current = number % self.len1
+
+        if tmp >= self.len1:
+            return self.getLetter(tmp) + self.letters[current]
+        else:
+            return self.letters[tmp] + self.letters[current]
+
+    def add(self, a, b):
+        sum = a + b
+        serial_number = self.getLetter(sum)
+        return serial_number
+
+    def __findLetter(self, char):
+        for i in range(self.len1):
+            if char == self.letters[i]:
+                return i
+        return -1
+
+    def __drop0(self, text):
+        char = text[0]
+        if char == '0':
+            return self.__drop0(text[1:])
+        else:
+            return text
+
+    def to10(self, serial):
+        serial = self.__drop0(serial)
+        print(serial)
+        len1 = len(serial)
+        print(len1)
+        sum = 0
+        for char in serial:
+            tmp = self.__findLetter(char)
+            if tmp == -1:
+                return None
+            print(tmp)
+            sum += (tmp * math.pow(35, len1 - 1))
+            len1 -= 1
+        return sum

+ 141 - 0
Service/LogMiddleware.py

@@ -0,0 +1,141 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import json
+import threading
+import time
+
+from django.utils.deprecation import MiddlewareMixin
+
+from Model.models import UserModel, LogModel
+from Object import TokenObject
+from Object.TokenObject import TokenObject
+from Service.CommonService import CommonService
+
+
+class LogMiddleware(MiddlewareMixin):
+
+    # def process_request(self, request):
+        # if request.path == '/upload':
+        #     request.encoding = 'utf-8'
+        #     request_dict = request.POST
+        #     print(request.POST)
+        #     request.POST = request_dict
+
+    def process_response(self, request, response):
+
+        if request.path != '/favicon.ico':
+            self.start_log_thread(request, response)
+        return response
+
+    def start_log_thread(self, request, response):
+        print('start_log_thread')
+        asy = threading.Thread(target=add_log, args=(request, response))
+        asy.start()
+
+
+def add_log(request, response):
+    request.encoding = 'utf-8'
+    if request.method == 'GET':
+        request_dict = request.GET
+    elif request.method == 'POST':
+        request_dict = request.POST
+    else:
+        return
+
+    # print(response.content.decode().strip())
+    request_path = request.path.strip().strip('/')
+    print(request_path)
+    jsonObject = {}
+    if request_path == 'download' or request_path == 'uid/download':
+        if response.status_code != 200:
+            return
+    else:
+        try:
+            jsonObject = json.loads(response.content.decode().strip())
+            code = jsonObject.get('code')
+        except Exception as e:
+            print(repr(e))
+            return
+
+        if code is None or code != 0 and response.status_code != 200:
+            print('code is {code}'.format(code=code))
+            return
+
+    token = request_dict.get('token', None)
+    # print(token)
+    token = TokenObject(token)
+
+    status = response.status_code
+    # 去除密码
+    contentDict = dict(request_dict)
+    # print(contentDict)
+    password = contentDict.get('password')
+    if password:
+        contentDict.pop('password')
+
+    content = json.dumps(contentDict)
+    ip = CommonService.get_ip_address(request)
+    now_time = time.time()
+
+    if token.code == 0:
+        user_qs = UserModel.objects.filter(id=token.userID)
+    else:
+        # print(token.code)
+        username = request_dict.get('username', None)
+        if username is None:
+            print('username')
+            return
+        user_qs = UserModel.objects.filter(username=username)
+
+    if not user_qs.exists():
+        # print('exists')
+        return
+
+    user = user_qs[0]
+    operation = ''
+    # print(request_path)
+    if request_path == 'user/login':
+        operation = '登录账号'
+    elif request_path == 'user/logout':
+        operation = '退出登录'
+    elif request_path == 'user/modify':
+        operation = '修改密码'
+    elif request_path == 'upload':
+        area = request_dict.get('area', None)
+        count = jsonObject['res']['count']
+        operation = formatOperation('上传', int(count), int(area))
+    elif request_path == 'uid/allot':
+        area = request_dict.get('area', None)
+        quantity = request_dict.get('quantity', None)
+        if area and quantity:
+            operation = formatOperation('分配', int(quantity), int(area))
+    elif request_path == 'download':
+        area = request_dict.get('area', None)
+        quantity = request_dict.get('quantity', None)
+        if area and quantity:
+            operation = formatOperation('下载', int(quantity), int(area))
+    else:
+        return
+
+    log = {
+        'status': status,
+        'content': content,
+        'ip': ip,
+        'time': now_time,
+        'url': request_path,
+        'operation': operation,
+        'user': user
+    }
+
+    try:
+        LogModel.objects.create(**log)
+    except Exception as e:
+        print(repr(e))
+
+
+def formatOperation(operation, quantity, area):
+    str = '{operation}{quantity}个{area}UID'
+    if area == 0:
+        return str.format(operation=operation, quantity=quantity, area='国内')
+    else:
+        return str.format(operation=operation, quantity=quantity, area='国外')

+ 40 - 6
Service/ModelService.py

@@ -5,13 +5,28 @@ import requests
 
 from Ansjer.config import BASE_DIR
 from Model.models import *
-from Service.CommonService import CommonService
 import json
 from django.db.models import Q
 
 
 # 针对模型封装的复用性代码
 class ModelService:
+    # UID Manage检测权限
+    @staticmethod
+    def check_perm_uid_manage(userID, permID):
+        try:
+            user_qs = UserModel.objects.filter(id=userID)
+            if user_qs.exists():
+                user = user_qs[0]
+                if int(user.permission) != 0:
+                    return False
+                else:
+                    return True
+            else:
+                return False
+        except Exception as e:
+            print(repr(e))
+
     # 获取当前用户角色名
     @staticmethod
     def getRole(rid):
@@ -159,26 +174,27 @@ class ModelService:
         uid_list = Device_Info.objects.filter(userID_id=userID).values_list('UID', flat=True)
         return list(uid_list)
 
+
     @staticmethod
-    def notify_alexa_add(uid, userID, nickname, password):
+    def notify_alexa_add(uid, userID, nickname, encrypt_pwd):
         url = 'https://www.zositech.xyz/deviceStatus/addOrUpdate'
         data = {
             'UID': uid,
             'userID': userID,
             'uid_nick': nickname,
-            'password': password
+            'password': encrypt_pwd,
         }
         try:
-            res = requests.post(url, data=data, timeout=10)
+            res = requests.post(url, data=data, timeout=5)
         except Exception as e:
             print(repr(e))
 
     @staticmethod
     def add_log(ip, userID, operation):
-        file_path = '/'.join((BASE_DIR, 'static/add_device.log'))
+        file_path = '/'.join((BASE_DIR, 'static/delete_device.log'))
         file = open(file_path, 'a+')
         file.write(ip + "; username:" + userID + "; time:" + time.strftime(
-            "%Y-%m-%d %H:%M:%S", time.localtime()) + "; " + operation)
+                "%Y-%m-%d %H:%M:%S", time.localtime()) + "; " + operation)
         file.write('\n')
         file.flush()
         file.close()
@@ -204,6 +220,24 @@ class ModelService:
         file.flush()
         file.close()
 
+    @staticmethod
+    def add_ip_log(ip, info):
+        file_path = '/'.join((BASE_DIR, 'static/get_timezone.log'))
+        file = open(file_path, 'a+')
+        file.write(ip + "; info:" + str(info) + "; time:" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
+        file.write('\n')
+        file.flush()
+        file.close()
+
+    @staticmethod
+    def add_tmp_log(info):
+        file_path = '/'.join((BASE_DIR, 'static/tmp_test.log'))
+        file = open(file_path, 'a+')
+        file.write("info:" + str(info))
+        file.write('\n')
+        file.flush()
+        file.close()
+
     @staticmethod
     def app_log_log(userID, UID):
         file_path = '/'.join((BASE_DIR, 'static/app_log.log'))

+ 95 - 0
Service/OperatingLogs.py

@@ -0,0 +1,95 @@
+import json
+import threading
+import datetime
+import time
+
+from bson import utc
+
+from Model.models import EquipmentLogModel
+from Service.CommonService import CommonService
+from Service.MiscellService import MiscellService
+from Service.TemplateService import TemplateService
+
+
+def add_access_log(request, status_code):
+    # 增加多进程 异步
+    asy = threading.Thread(target=addLog, args=(request, status_code))
+    asy.start()
+
+
+def addLog(request, status_code):
+    request_path = request.path.strip().strip('/')
+    if 'equipment' in request.path:
+        global request_dict
+        try:
+            if request.method == 'GET':
+                request_dict = request.GET
+            elif request.method == 'POST':
+                request_dict = request.POST
+            # api_list = TemplateService.log_api()
+            print('status_code:', status_code)
+            api_list = [
+                'equipment/add',
+                'equipment/delete',
+                'equipment/flowUpdate',
+                'v3/equipment/add',
+                'v3/equipment/modify',
+            ]
+            # 接口中文化
+            jiekou = {
+                'equipment/add': 'v1添加设备',
+                'equipment/delete': 'v1删除设备',
+                'equipment/flowUpdate': '更新设备的版本信息',
+                'v3/equipment/add': 'v3添加设备信息',
+                'v3/equipment/modify': 'v3编辑设备信息'
+            }
+            if request_path in api_list:
+                user = MiscellService.get_access_name(request_dict=request_dict)
+                clientIP = CommonService.get_ip_address(request)
+                # now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
+                nowtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
+                beijing = datetime.timezone(datetime.timedelta(hours=8))
+                utc = datetime.timezone.utc  # 获取 UTC 的时区对象
+                beijing_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(beijing)  # 强制转换加上 UTC 时区。此处敲黑板,需要特别注意。
+                # content:从前端获取到的参数数据,对获取到的数据进行处理
+                content = json.dumps(request_dict)
+                d = eval(content)
+                if 'uid' not in d:
+                    d['uid'] = ''
+                if 'NickName' not in d:
+                    d['NickName'] = ''
+                if 'equipmentid' not in d:
+                    d['equipmentid'] = ''
+                if 'UID' in d:
+                    d['uid'] = d['UID']
+                if 'id' in d:
+                    d['equipmentid'] = d['id']
+                password = request_dict.get('userPwd', None)
+                if password is not None:
+                    request_dict = dict(request_dict)
+                    request_dict.pop('userPwd')
+                if user != '':
+                    user = user
+                else:
+                    print('空')
+                    user = '空'
+                # 数据拼接
+                caozuo = '用户账号为:[' + user + ']' + '在' + str(beijing_time) + '进行' + str(jiekou[request_path])
+                # + ',' + '设备uid或主键id为:' + str(d['uid']) + str(d['equipmentid'])
+                print('request_dict:', d)
+                add_data = {
+                    'user': user,
+                    'uid': d['uid'],
+                    'equipmentid': d['equipmentid'],
+                    'NickName': d['NickName'],
+                    'ip': clientIP,
+                    'time': beijing_time,
+                    'url': request.path,
+                    'operatingcontent': caozuo,
+                }
+                print('操作数据:', add_data)
+                # 设备日志添加
+                EquipmentLogModel.objects.create(**add_data)
+        except Exception as e:
+            print(repr(e))
+            pass

+ 15 - 11
Service/TemplateService.py

@@ -28,9 +28,6 @@ class TemplateService:
             'account/delUser',
             'account/setUserValid',
             'account/unsharedUserEquipment',
-            'equipment/addNewUserEquipment',
-            'equipment/delUserEquipment',
-            'equipment/modifyUserEquipment',
             'roles/addNewRole',
             'roles/delRole',
             'roles/modifyRole',
@@ -38,7 +35,6 @@ class TemplateService:
             'perms/delPerms',
             'perms/modifyPerms',
             'uploads/upgrade',
-            'equipment/OTA',
             # 'appInfo',
             'OTA/getNewVer',
             'v2/account/authcode',
@@ -53,24 +49,17 @@ class TemplateService:
             'cloudVod/findVod',
             'cloudVod/aliPayCreateOrder',
             'cloudVod/aliPayCallback',
-            'equipment/add',
             'deviceShare/queryUser',
             'deviceShare/showShareInfo',
             'deviceShare/confirm',
             'deviceShare/deleteUser',
-            'equipment/delete',
-            'equipment/query',
             'order/querylist',
             'detect/changeStatus',
             # 'notify/push',
-            'equipment/flowUpdate',
             'wechat/authsign',
             'login/oauth/authorize',
             'login/oauth/access_token',
             'login/oauth/user',
-            'v3/equipment/query',
-            'v3/equipment/add',
-            'v3/equipment/modify',
             'v2/account/login',
             'v3/account/login',
             'detect/queryInfo',
@@ -79,6 +68,21 @@ class TemplateService:
             'v3/account/changePwd',
             'v3/account/resetPwdByCode',
             'account/appFrequency',
+            'equipment/OTA',
+            'equipment/addNewUserEquipment',
+            'equipment/delUserEquipment',
+            'equipment/modifyUserEquipment',
+            'equipment/add',
+            'equipment/delete',
+            'equipment/query',
+            'equipment/flowUpdate',
+            'v3/equipment/query',
+            'v3/equipment/add',
+            'v3/equipment/modify',
+            'Cloudsum/cloudservicesum',
+            'Cloudsum/userappversion',
+            'Cloudsum/usercount',
+            'Cloudsum/usercloud',
         ]
         return apiList
 

+ 2 - 0
Service/middleware.py

@@ -7,6 +7,7 @@ from Ansjer.config import SERVER_TYPE
 
 from Object.ResponseObject import ResponseObject
 from Service.MiscellService import MiscellService
+from Service import OperatingLogs
 import django.db
 
 
@@ -87,6 +88,7 @@ class StatisticsUrlMiddleware(MiddlewareMixin):
                 # mysql
                 if SERVER_TYPE!="Ansjer.formal_settings":
                     # print('添加日志')
+                    OperatingLogs.add_access_log(request=request, status_code=response.status_code)
                     MiscellService.add_access_log(request=request, status_code=response.status_code)
                 # else:
                 #     print('不添加日志')

+ 269 - 36
requirements.txt

@@ -1,36 +1,269 @@
-Django==2
-
-django-cors-headers
-django-imagekit
-django-guardian
-django-rest-framework
-simplejson
-djangorestframework-jwt
-South
-qcloudsms_py
-itsdangerous
-openpyxl
-xlrd
-mysqlclient
-boto3
-requests_aws4auth
-ffmpy
-xmltodict
-var_dump
-django-middleware-global-request
-jpush
-pyipip
-boto
-django-ratelimit
-paypalrestsdk
-pymongo
-image
-pyfcm
-pillow
-oss2
-redis
-ipip-ipdb
-alipay-sdk-python
-https://www.cnblogs.com/victorwu/p/8505336.html
-apns2
-aliyun-python-sdk-sts
+alabaster==0.7.12
+aliyun-python-sdk-core==2.13.15
+aliyun-python-sdk-core-v3==2.13.11
+aliyun-python-sdk-dysmsapi==1.0.0
+aliyun-python-sdk-kms==2.10.1
+aliyun-python-sdk-sts==3.0.1
+anaconda-client==1.7.2
+anaconda-navigator==1.9.7
+anaconda-project==0.8.3
+apns2==0.7.1
+asn1crypto==1.0.1
+astroid==2.3.1
+astropy==3.2.1
+atomicwrites==1.3.0
+attrs==19.2.0
+Babel==2.7.0
+backcall==0.1.0
+backports.functools-lru-cache==1.5
+backports.os==0.1.1
+backports.shutil-get-terminal-size==1.0.0
+backports.tempfile==1.0
+backports.weakref==1.0.post1
+beautifulsoup4==4.8.0
+bitarray==1.0.1
+bkcharts==0.2
+bleach==3.1.0
+bokeh==1.3.4
+boto==2.49.0
+boto3==1.12.13
+botocore==1.15.13
+Bottleneck==1.2.1
+certifi==2019.9.11
+cffi==1.12.3
+chardet==3.0.4
+Click==7.0
+cloudpickle==1.2.2
+clyent==1.2.2
+colorama==0.4.1
+comtypes==1.1.7
+conda==4.7.12
+conda-build==3.18.9
+conda-package-handling==1.6.0
+conda-verify==3.4.2
+contextlib2==0.6.0
+crcmod==1.7
+cryptography==2.8
+cssselect==1.1.0
+cycler==0.10.0
+Cython==0.29.13
+cytoolz==0.10.0
+dask==2.5.2
+decorator==4.4.0
+defusedxml==0.6.0
+distributed==2.5.2
+Django==2.1
+django-appconf==1.0.3
+django-cors-headers==3.2.1
+django-guardian==2.2.0
+django-imagekit==4.0.2
+django-middleware-global-request==0.1.2
+django-ratelimit==2.0.0
+django-rest-framework==0.1.0
+djangorestframework==3.11.0
+djangorestframework-jwt==1.11.0
+docutils==0.15.2
+entrypoints==0.3
+et-xmlfile==1.0.1
+fastcache==1.1.0
+ffmpy==0.2.2
+filelock==3.0.12
+Flask==1.1.1
+fsspec==0.5.2
+future==0.17.1
+gevent==1.4.0
+glob2==0.7
+greenlet==0.4.15
+gunicorn==20.0.4
+h2==2.6.2
+h5py==2.9.0
+HeapDict==1.0.1
+hpack==3.0.0
+html5lib==1.0.1
+hyper==0.7.0
+hyperframe==3.2.0
+idna==2.8
+image==1.5.28
+imageio==2.6.0
+imagesize==1.1.0
+importlib-metadata==0.23
+ipip-ipdb==1.3.2
+ipykernel==5.1.2
+ipython==7.8.0
+ipython-genutils==0.2.0
+ipywidgets==7.5.1
+isort==4.3.21
+itsdangerous==1.1.0
+jdcal==1.4.1
+jedi==0.15.1
+Jinja2==2.10.3
+jmespath==0.9.5
+joblib==0.13.2
+jpush==3.3.8
+json5==0.8.5
+jsonschema==3.0.2
+jupyter==1.0.0
+jupyter-client==5.3.3
+jupyter-console==6.0.0
+jupyter-core==4.5.0
+jupyterlab==1.1.4
+jupyterlab-server==1.0.6
+keyring==18.0.0
+kiwisolver==1.1.0
+lazy-object-proxy==1.4.2
+libarchive-c==2.8
+llvmlite==0.29.0
+locket==0.2.0
+lxml==4.4.1
+m3u8-generator==1.5
+MarkupSafe==1.1.1
+matplotlib==3.1.1
+mccabe==0.6.1
+menuinst==1.4.16
+mistune==0.8.4
+mkl-fft==1.0.14
+mkl-random==1.1.0
+mkl-service==2.3.0
+mock==3.0.5
+more-itertools==7.2.0
+mpmath==1.1.0
+msgpack==0.6.1
+multipledispatch==0.6.0
+mysqlclient==1.4.6
+navigator-updater==0.2.1
+nbconvert==5.6.0
+nbformat==4.4.0
+networkx==2.3
+nltk==3.4.5
+nose==1.3.7
+notebook==6.0.1
+numba==0.45.1
+numexpr==2.7.0
+numpy==1.16.5
+numpydoc==0.9.1
+olefile==0.46
+openpyxl==3.0.0
+oss2==2.9.1
+packaging==19.2
+pandas==0.25.1
+pandocfilters==1.4.2
+parso==0.5.1
+partd==1.0.0
+path.py==12.0.1
+pathlib2==2.3.5
+patsy==0.5.1
+paypalrestsdk==1.13.1
+pep8==1.7.1
+pickleshare==0.7.5
+pilkit==2.0
+Pillow==6.2.0
+pkginfo==1.5.0.1
+pluggy==0.13.0
+ply==3.11
+prometheus-client==0.7.1
+prompt-toolkit==2.0.10
+psutil==5.6.3
+py==1.8.0
+pyasn1==0.4.8
+pycodestyle==2.5.0
+pycosat==0.6.3
+pycparser==2.19
+pycrypto==2.6.1
+pycryptodome==3.9.7
+pycryptodomex==3.9.4
+pycurl==7.43.0.3
+pyfcm==1.4.7
+pyflakes==2.1.1
+Pygments==2.4.2
+pyipip==0.1.1
+PyJWT==1.7.1
+pylint==2.4.2
+pymongo==3.10.1
+PyMySQL==0.10.1
+pyodbc==4.0.27
+pyOpenSSL==19.1.0
+pyparsing==2.4.2
+pyquery==1.4.1
+pyreadline==2.1
+pyrsistent==0.15.4
+PySocks==1.7.1
+pytest==5.2.1
+pytest-arraydiff==0.3
+pytest-astropy==0.5.0
+pytest-doctestplus==0.4.0
+pytest-openfiles==0.4.0
+pytest-remotedata==0.3.2
+python-alipay-sdk==2.0.1
+python-dateutil==2.8.0
+pytz==2019.3
+PyWavelets==1.0.3
+pywin32==223
+pywinpty==0.5.5
+PyYAML==5.1.2
+pyzmq==18.1.0
+qcloudsms-py==0.1.4
+QtAwesome==0.6.0
+qtconsole==4.5.5
+QtPy==1.9.0
+redis==3.4.1
+requests==2.22.0
+requests-aws4auth==0.9
+rope==0.14.0
+rsa==4.0
+ruamel-yaml==0.15.46
+s3transfer==0.3.3
+scikit-image==0.15.0
+scikit-learn==0.21.3
+scipy==1.3.1
+seaborn==0.9.0
+selenium==3.141.0
+Send2Trash==1.5.0
+simplegeneric==0.8.1
+simplejson==3.17.0
+singledispatch==3.4.0.3
+six==1.12.0
+snowballstemmer==2.0.0
+sortedcollections==1.1.2
+sortedcontainers==2.1.0
+soupsieve==1.9.3
+South==1.0.2
+Sphinx==2.2.0
+sphinxcontrib-applehelp==1.0.1
+sphinxcontrib-devhelp==1.0.1
+sphinxcontrib-htmlhelp==1.0.2
+sphinxcontrib-jsmath==1.0.1
+sphinxcontrib-qthelp==1.0.2
+sphinxcontrib-serializinghtml==1.1.3
+sphinxcontrib-websupport==1.1.2
+spyder==3.3.6
+spyder-kernels==0.5.2
+SQLAlchemy==1.3.9
+statsmodels==0.10.1
+sympy==1.4
+tables==3.5.2
+tblib==1.4.0
+terminado==0.8.2
+testpath==0.4.2
+toolz==0.10.0
+tornado==6.0.3
+tqdm==4.36.1
+traitlets==4.3.3
+unicodecsv==0.14.1
+urllib3==1.24.2
+var-dump==1.2
+wcwidth==0.1.7
+webencodings==0.5.1
+Werkzeug==0.16.0
+widgetsnbextension==3.5.1
+win-inet-pton==1.1.0
+win-unicode-console==0.5
+wincertstore==0.2
+wrapt==1.11.2
+xlrd==1.2.0
+XlsxWriter==1.2.1
+xlwings==0.15.10
+xlwt==1.3.0
+xmltodict==0.12.0
+xpinyin==0.5.6
+zict==1.0.0
+zipp==0.6.0