import time import arrow from settings import settings class TaHandler: handler_link = [] def __init__(self, func): TaHandler.handler_link.append(func) @staticmethod def format_data(data: dict): msg = dict() for k in settings.TA_OUTER: v = data.get(k) if v is not None: msg[k] = data.pop(k) msg['properties'] = data.pop('properties') if msg['#type'] == 'track': msg['properties'].update(data) elif msg['#type'] == 'user': msg['#type'] = 'user_' + msg['#event_name'] if msg.get('#user_id'): msg['properties']['#user_id'] = msg['#user_id'] if "#event_name" in msg: del msg["#event_name"] if "#event_time" in msg: del msg["#event_time"] return msg @TaHandler async def add_ip(request, rdb, data): """ 添加源ip :param request: :param rdb: :param data: :return: """ ip = request.client.host data['#ip'] = data.get('#ip') or ip @TaHandler async def to_date(request, rdb, data): """ 时间戳转日期字符串 :param request: :param rdb: :param data: :return: """ data['#time'] = arrow.get(data['#time'], tzinfo='Asia/Shanghai').strftime('%Y-%m-%d %H:%M:%S') data['#event_time'] = data['#time'] @TaHandler async def device_label(request, rdb, data): """ 标记新设备 :param request: :param rdb: :param data: :return: """ # 条件 if data.get('#type') == 'user' and data.get('#event_name') == 'add': v = await rdb.execute('sadd', f'{data["#app_id"]}.devices', data.get('#device_id', '')) if v: data['properties']['is_new_device'] = 1 else: data['properties']['is_new_device'] = 0