Browse Source

250326-1代码。

baoyubo 3 tháng trước cách đây
mục cha
commit
cac27fe4ea
1 tập tin đã thay đổi với 195 bổ sung64 xóa
  1. 195 64
      routers/api/videoResource/videoinfo.py

+ 195 - 64
routers/api/videoResource/videoinfo.py

@@ -1,6 +1,6 @@
 #!/usr/bin/env python3
 # -*- coding: utf-8 -*-
-from fastapi import APIRouter, Request, Depends,Query,HTTPException
+from fastapi import APIRouter, Request, Depends,Query,HTTPException,status
 from database import get_db
 from sqlalchemy.orm import Session
 from sqlalchemy import case,or_
@@ -15,86 +15,217 @@ from datetime import datetime
 
 router = APIRouter()
 
+# @router.get('/get_video_list_new')
+# async def get_video_url_by_id(
+#         area_code :str = Query(None,  description='区划编码'),
+#         video_from :str = Query(None,  description='视频来源'),
+#         video_tag :str = Query(None,  description='视频标签'),
+#         video_name :str = Query(None,  description='视频名称'),
+#     longitude:float = Query(None,  description='经度'),
+#     latitude:float = Query(None,  description='纬度'),
+#     db: Session = Depends(get_db),
+#     body=Depends(remove_xss_json),
+#     user_id=Depends(valid_access_token),
+#     page: int = Query(1, gt=0, description='页码'),
+#     pageSize: int = Query(10, gt=0, description='每页条目数量')
+# ):
+#     querystr = ''
+#     if area_code:
+#         querystr +=f"and gbIndexCode like '%{area_code}%'"
+#     if video_from:
+#         querystr +=f"and regionPath like '%{video_from}%'"
+#     if video_name:
+#         querystr +=f"and `name` like '%{video_name}%'"
+#     if video_tag:
+#         videoli = tag_get_video_tag_list(db, video_tag)
+#         querystr +=f"and gbIndexCode in {videoli}"
+#     if longitude is not None and latitude is not None:
+#         location = f"""ST_Distance_Sphere(
+#         ST_GeomFromText(CONCAT('POINT(', longitude, ' ', latitude, ')')),
+#         ST_PointFromText('POINT({longitude} {latitude})'))"""
+#         orddis = 'distance'
+#     else:
+#         location = 0
+#         orddis = ''
+#     videoIds = user_id_get_user_videoIds(db, user_id)
+#     video_list = [i.video_code_int for i in videoIds]
+#     if len(video_list)==0:
+#         video = ''
+#     else:
+#         video = ""
+#         for i in video_list:
+#             video += f"WHEN '{i}' THEN 0 \n"
+#
+#         video = f"""CASE video_code_int
+#     {video}
+#     ELSE 1
+# END """
+#     if orddis != '' and video !='':
+#         video += ','
+#     sql  = f"""SELECT T1.*,
+#         {location} AS distance
+#     FROM tp_video_info T1 where 1=1
+#     ORDER BY {video} {orddis} """
+#     totalsql = f'select count(*) from ({sql})t'
+#     print(video_list)
+#
+#     total_items = db.execute(totalsql).first()[0]
+#
+#     lim = f"limit  {pageSize*(page-1)}, {pageSize};"
+#     videos = db.execute(sql+lim).fetchall()
+#
+#     return {
+#             "code": 200,
+#             "msg": "操作成功",
+#             "rows": videos,
+#             "total": total_items,
+#             "page": page,
+#             "pageSize": pageSize,
+#             "totalPages": (total_items + pageSize - 1) // pageSize
+#         }
+@router.get('/video_from')
+async def get_dict_data_by_type(
+    db: Session = Depends(get_db),
+    body = Depends(remove_xss_json),
+    user_id = Depends(valid_access_token)
+):
+    try:
+        # 根据 dict_type 查询字典数据
+        # dict_data = db.query(SysDictData).filter_by(dict_type=dictType).all()
+        query = db.query(TPVideoRegion)
+
+        # 添加查询条件
+        # if dictType:
+        query = query.filter(TPVideoRegion.parentIndexCode=='root00000000')
+        query = query.filter(TPVideoRegion.status == '0')
+        query = query.order_by(TPVideoRegion.sort)
+        dict_data = query.all()
+
+        # 转换为字典
+        dict_data_list = [
+            {
+                "dictCode": d.indexCode,
+                "dictSort": d.sort,
+                "dictLabel": d.name,
+                "dictValue": d.indexCode,
+                "dictType": 'video',
+                "cssClass": '',
+                "listClass": 'default',
+                "isDefault": 'N',
+                "remark": '',
+                "createTime": d.createTime.strftime('%Y-%m-%d %H:%M:%S') if d.createTime else ''
+            }
+            for d in dict_data
+        ]
+
+        # 构建返回结果
+        result = {
+            "rows": dict_data_list,
+            "code": 200,
+            "msg": "查询成功"
+        }
+        return result
+
+    except Exception as e:
+        # 处理异常
+        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))
+
 @router.get('/get_video_list_new')
 async def get_video_url_by_id(
-    longitude:float = Query(None,  description='经度'),
-    latitude:float = Query(None,  description='纬度'),
+    area_code: str = Query(None, description='区划编码'),
+    video_from: str = Query(None, description='视频来源'),
+    video_tag: str = Query(None, description='视频标签'),
+    video_name: str = Query(None, description='视频名称'),
+    longitude: float = Query(None, description='经度'),
+    latitude: float = Query(None, description='纬度'),
     db: Session = Depends(get_db),
     body=Depends(remove_xss_json),
     user_id=Depends(valid_access_token),
     page: int = Query(1, gt=0, description='页码'),
     pageSize: int = Query(10, gt=0, description='每页条目数量')
 ):
-    if longitude is not None and latitude is not None:
-        location = f"""ST_Distance_Sphere(
-        ST_GeomFromText(CONCAT('POINT(', longitude, ' ', latitude, ')')), 
-        ST_PointFromText('POINT({longitude} {latitude})'))"""
-        orddis = 'distance'
-    else:
-        location = 0
-        orddis = ''
-    videoIds = user_id_get_user_videoIds(db, user_id)
-    video_list = [i.video_code_int for i in videoIds]
-    if len(video_list)==0:
-        video = ''
-    else:
-        video = ""
-        for i in video_list:
-            video += f"WHEN '{i}' THEN 0 \n"
-
-        video = f"""CASE video_code_int
-    {video}
-    ELSE 1
-END """
-    if orddis != '' and video !='':
-        video += ','
-    sql  = f"""SELECT T1.indexcode,T2.`name`,T1.longitude,T1.latitude,
-        {location} AS distance,T2.area,T2.ip,T2.`status`,T2.status_lifetime,T2.record_status,T2.inspection_datetime,T2.video_code_int,T2.video_code
-    FROM tp_video_base T1 RIGHT JOIN tp_video_log T2 on T1.indexcode=T2.video_code_int -- where  T1.longitude is not NULL
-    ORDER BY {video} {orddis} """
-    totalsql = f'select count(*) from ({sql})t'
-    print(video_list)
+    try:
+        query = db.query(TPVideoInfo)
+
+        if area_code:
+            query = query.filter(TPVideoInfo.gbIndexCode.like(f'%{area_code}%'))
+        if video_from:
+            query = query.filter(TPVideoInfo.regionPath.like(f'%{video_from}%'))
+        if video_name:
+            query = query.filter(TPVideoInfo.name.like(f'%{video_name}%'))
+        if video_tag:
+            tag_info = get_dict_data_info(db, 'video_type', video_tag)
+            if tag_info:
+                if tag_info.dict_label != '全量视频':
+                    videoli = [info.video_code for info in tag_get_video_tag_list(db, video_tag)]
+                    query = query.filter(TPVideoInfo.gbIndexCode.in_(videoli))
+        if longitude is not None and latitude is not None:
+            point = func.ST_GeomFromText(f'POINT({latitude} {longitude})', 4326)
+            query = query.add_columns(
+                func.ST_Distance_Sphere(TPVideoInfo.location, point).label('distance')
+            ).order_by('distance')
+
+        videoIds = user_id_get_user_videoIds(db, user_id)
+        video_list = [i.video_code_int for i in videoIds]
+
+        if video_list:
+            video_priority_case = case(
+                [
+                    (TPVideoInfo.gbIndexCode == i, 0)
+                    for i in video_list
+                ],
+                else_=1
+            ).label('user_priority')
+            query = query.add_columns(video_priority_case).order_by('user_priority')
 
-    total_items = db.execute(totalsql).first()[0]
 
-    lim = f"limit  {pageSize*(page-1)}, {pageSize};"
-    videos = db.execute(sql+lim).all()
-    # query = db.query(TpVideoLog)
-    # total_items = query.count()
-    #
-    # query = query.order_by(
-    # case(
-    #     [(TpVideoLog.video_code_int == video_code_int, 0) for video_code_int in video_list],
-    #     else_=1
-    # )
-    #     )
-    # videos = query.offset((page - 1) * pageSize).limit(pageSize).all()
-    video_list1 = []
-    for video in videos:
-        videoInfo = {
-            "name": video.name,
-            "invideoIds": video.video_code_int in video_list,
-            "area": video.area,
-            "ip": video.ip,
-            "status": video.status,
-            "status_lifetime": video.status_lifetime,
-            "record_status": video.record_status,
-            "inspection_datetime": video.inspection_datetime,
-            "video_code_int": video.video_code_int,
-            "video_code": video.video_code,
-            "longitude":video.longitude,
-            "latitude":video.latitude
-        }
-        video_list1.append(videoInfo)
-    return {
+        total_items = query.count()
+        videos = query.offset(pageSize * (page - 1)).limit(pageSize).all()
+        data = []
+        for row in videos:
+            row = row[0]
+            # print(type(row),row[0])
+            tag_list =get_video_tag_list(db,row.gbIndexCode)
+            tag = []
+            tag_lable = []
+            for info in tag_list:
+                tag_info = get_dict_data_info(db, info.dict_type, info.dict_value)
+                if tag_info:
+                    if tag_info.dict_label not in tag_lable:
+                        tag.append({"id": info.id,
+                                    "video_code": row.gbIndexCode,
+                                    "dict_type": info.dict_type,
+                                    "dict_value": info.dict_value,
+                                    "dict_label": tag_info.dict_label,
+                                    "dict_code": tag_info.dict_code})
+                        tag_lable.append(tag_info.dict_label)
+            data.append({
+                "name":row.name,
+                "isUserVideos":row.gbIndexCode in video_list,
+                "video_code": row.gbIndexCode,
+                "isTag" : len(tag_list)>0,
+                "tag" : tag,
+                "tagLabels" : "、".join(tag_lable),
+                "status":row.status,
+                "statusName":row.statusName,
+                "regionPath":row.regionPath,
+                "installPlace":row.installPlace,
+                "cameraTypeName":row.cameraTypeName,
+                "cameraType":row.cameraType
+            })
+        return {
             "code": 200,
             "msg": "操作成功",
-            "rows": video_list1,
+            "data": data,
             "total": total_items,
             "page": page,
             "pageSize": pageSize,
             "totalPages": (total_items + pageSize - 1) // pageSize
         }
+    except Exception as e:
+        # 处理异常
+        traceback.print_exc()
+        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))
 
 @router.get('/get_video_list_by_user')
 async def get_video_url_by_id(