diff --git a/ad_Readme.md b/ad_Readme.md index 56e4ab4..7b81196 100644 --- a/ad_Readme.md +++ b/ad_Readme.md @@ -11,8 +11,8 @@ ##### 请求示范 -http://spread.kingsome.cn/webapp/index.php?c=Ops&a=getAdList&body={"gameid":"10034","locationid":1001} -http://spread.kingsome.cn/webapp/index.php?c=Ops&a=getAdList&body={"gameid":"1003","area":1} +http://spread-test.kingsome.cn/webapp/index.php?c=Ops&a=getAdList&body={"gameid":"10034","locationid":1001} +http://spread-test.kingsome.cn/webapp/index.php?c=Ops&a=getAdList&body={"gameid":"1003","area":1} ##### 请求参数说明 | 名称 | 类型 | 必填 | 说明 | @@ -72,7 +72,7 @@ http://spread.kingsome.cn/webapp/index.php?c=Ops&a=getAdList&body={"gameid":"100 ##### 接口地址 -http://spread.kingsome.cn/webapp/index.php +http://spread-test.kingsome.cn/webapp/index.php ##### 返回格式:json @@ -86,7 +86,7 @@ let aidStr = JSON.stringify(aids); let url = `${__getUrl()}?c=Ops&a=upAdRecording&adid=${encodeURIComponent(aidStr)}` ''' -https://spread.kingsome.cn/webapp/index.php?c=Ops&a=upAdRecording&adid=%5B%221040%22%2C%221035%22%2C%221039%22%2C%221036%22%2C%221038%22%2C%221037%22%5D +https://spread-test.kingsome.cn/webapp/index.php?c=Ops&a=upAdRecording&adid=%5B%221040%22%2C%221035%22%2C%221039%22%2C%221036%22%2C%221038%22%2C%221037%22%5D ##### 请求参数说明 @@ -113,4 +113,49 @@ https://spread.kingsome.cn/webapp/index.php?c=Ops&a=upAdRecording&adid=%5B%22104 "message": "1002 incr success!" } -{"#account_id":"6001_2001_oJqfX5R1IDH0aUDTFxNqu5D1PsV8","#distinct_id":"SSg9qS1A2sLRHgvldEm9dkLiCJ6fSaa5","#type":"track","#time":"2019-09-06 14:45:45","#ip":"101.84.36.110","#event_name":"event_11_31","properties":{"nickname":"226","button_name":"jc_promotipn","button_param":"[{\"appid\":\"wxdb103a128e118619\",\"channelid\":\"6001\",\"adid\":\"1118\",\"jump_param\":\"yx2nyabgm8\"}]","account_id":"6001_2001_oJqfX5R1IDH0aUDTFxNqu5D1PsV8","account_register_utctime":1562124532,"account_register_date":"2019-07-03 11:28:52","localuuid":"SSg9qS1A2sLRHgvldEm9dkLiCJ6fSaa5","channel":"6001","from_appid":"","ad_channel":"","gameid":"2001"}} +#### 3、广告跳转内容上报 + +##### 接口地址 + +http://spread-test.kingsome.cn/webapp/index.php + +##### 返回格式:json + +##### 请求方式:post + +##### 请求示范 + +上传列表压缩过程 +''' +let aidStr = JSON.stringify(aids); +let url = `${__getUrl()}?c=Ops&a=upAdRecording&adid=${encodeURIComponent(aidStr)}` +''' + +https://spread-test.kingsome.cn/webapp/index.php?c=Ops&a=upJumpRecording + +##### 请求参数说明 + +| 名称 | 类型 | 必填 | 说明 | +| --------- | ---- | ---- | ---------------------------------- | +| c | string | 是 | OPS通用接口标志 | +| a | string | 是 | 方法定义 upJumpRecording | +| gameid | int | 是 | 游戏ID | +| channelid | int | 是 | 平台ID | +| body | string | 是 | 广告属性json (area,locationid,ad_channel,appid) | + + +##### 返回参数说明 + +| 名称 | 类型 | 必填 | 说明 | +| ---- | ---- | ---- | -------- | +| errcode | int | 是 | 返回状态 | +| errmsg | string | 是 | 错误信息 | +| message | string | 是 | 返回信息 | + + + +##### 返回示例 +{ + "errcode": 0, + "errmsg": "", + "message": "1002 incr success!" diff --git a/ad_interface_tornado.py b/ad_interface_tornado.py index b3e2d81..528764c 100644 --- a/ad_interface_tornado.py +++ b/ad_interface_tornado.py @@ -15,7 +15,7 @@ from prod_config import BEGIN, END, ad_list_interface_port from tornado import gen import pdb from urllib.parse import unquote - +from ops.mtga import FromTga, GetTgaConfig define_logger("/data/logs/ad_interface_tornado.log") log = logging.getLogger(__name__) @@ -38,6 +38,63 @@ class DispatchHandler(tornado.web.RequestHandler): else: self.write("pls check args!") + @gen.coroutine + def post(self): + if self.get_query_argument('c') == 'Ops' and self.get_query_argument('a') == 'upJumpRecording': + self._selfupJumpRecording() + + def _selfupJumpRecording(self): + # {"area":"2,0,5,0,0","locationId":"1011","ad_channel":"wxxssss","appid":"sss"} + try: + body = unquote(self.get_query_argument('body'), 'utf-8') + gameid = self.get_query_argument('gameid') + channelid = self.get_query_argument('channelid') + area = json.loads(body)['area'] + locationid = json.loads(body)['locationid'] + ad_channel = json.loads(body)['ad_channel'] + appid = json.loads(body)['appid'] + + except Exception as e: + result = {'errcode': 2, "errmsg": f"get args failed,{str(e)}"} + log.error(result) + return self.write_error(2) + + g = GetTgaConfig() + item = g.get_api_key(gameid) + if not item: + result = {'errcode': 2, "errmsg": f"get config via gameid failed ,gameid={gameid}"} + log.error(result) + return self.write_error(2) + + self.url = item['url'] + self.tgaid = 99 + # self.tgaid = item['tgaid'] + self.suffix = item.get('suffix', 0) + self.api_key = item.get('api_key', None) + self.tga = FromTga(self.url, self.api_key) + self.tga.init_tga_write(self.tgaid) + self.event_type = "jump_recording" + try: + tga_data = {} + tga_data['ad_channel'] = channelid + tga_data['account_id'] = gameid + tga_data['gameid'] = channelid + tga_data['date'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + + tga_data['area'] = area + tga_data['locationid'] = locationid + tga_data['ad_channel'] = ad_channel + tga_data['appid'] = appid + + self.tga.put_event_data(tga_data, f'rep_{self.event_type}') + return self.write({'errcode': 0, "errmsg": '', "message": ""}) + except Exception: + log.error(f"write 2 tga failed!,context={body}", exc_info=True) + return self.write_error(2) + + + + def _selfGetLocation(self): try: input = json.loads(self.get_query_argument('body')) diff --git a/ops/mtga.py b/ops/mtga.py new file mode 100644 index 0000000..e9b27df --- /dev/null +++ b/ops/mtga.py @@ -0,0 +1,146 @@ +# -*- coding: utf-8 -*- + +import requests +import json +import datetime +import os +from tgasdk.sdk import * +import pdb +import pymysql +from ops.mmysql import MysqlBase + + +# 按提供的gameid从tga数据库中查询并输出其对应的url,suffix,appid,api_key,tgaid以dict形式存放 +class GetTgaConfig(): + def __init__(self): + self.url = "http://10.10.3.17:8992/querySql" + self.TGA = {'user': 'mytga', 'pswd': 'gzVwh4HGR68G', 'host': '10.10.3.5', 'db': 'tga'} + + def get_api_key(self, gameid, channel=6001): + item = {} + item['url'] = self.url + sql = "select suffix,appid,api_secret,tgaid from tgainfo where gameid={} and channelid={} and " \ + "in_used=1;".format(gameid, channel) + t = MysqlBase(**self.TGA) + data = t.query(sql) + if data: + item['suffix'], item['appid'], item['api_key'], item['tgaid'] = data[0] + return item + +class FromTga: + def __init__(self, url, token): + if not token: + raise Exception("{0} token not found in env !") + self.url = url + self.token = token + self.output = "/data/logs/tga-report/" + + def get_data(self, sql): + data = {'token': self.token, 'sql': sql} + r = requests.post(self.url, data) + if r.status_code != requests.codes.ok: + print("connect tga failed!") + return None + + out = r.content.decode('utf-8') + if json.loads(out.split('\r\n')[0]).get('return_code', None) != 0: + # raise Exception("get data from tga failed!") + print("get data from tga failed!,sql was {}".format(sql)) + return None + + data_out = out.split('\r\n')[1:] + output = list() + for row in data_out: + if row: + try: + output.append(json.loads(row)) + except Exception as e: + print("转化数据失败,{} 提示为{}".format(row, e)) + return output + + def init_tga_write(self, tgaid): + ''' + from tgasdk.sdk import TGAnalytics, BatchConsumer, LoggingConsumer, AsyncBatchConsumer + 也可引入TGAnalytics与指定的Consumer + ''' + # now = datetime.date.today().strftime('%Y%m%d%H%M%S') + # # 初始化SDK + # filename = "{}/report_{}_{}.log".format(self.output, project, now) + # 检查目录是否存在,如不存在创建之 + paths = "{}/{}".format(self.output, tgaid) + if not os.path.isdir(paths): + os.makedirs(paths, mode=0o755) + + self.tga = TGAnalytics(LoggingConsumer(paths)) + + def _close_tga(self, tga): + self.tga.flush() + self.tga.close() + + def _split_user_data(self, data): + distinct_id = data.get('distinct_id', None) + account_id = data.get('account_id', None) + + if not (distinct_id or account_id): + print("distinct_id 或 account_id 必须有一则有值!") + return None + + if distinct_id: + data.pop('distinct_id') + if account_id: + data.pop('account_id') + + return distinct_id, account_id, data + + def put_event_data(self, data, event_name="Payment"): + # tga = self._init_tga_write() + try: + distinct_id, account_id, new_data = self._split_user_data(data) + except Exception as e: + print("拆解数据错误,输出为{}.请检查!".format(e)) + return False + + # properties = { + # "#time": datetime.datetime.now(), + # "#ip": "192.168.1.1", + # "Product_Name": "月卡", + # "Price": 30, + # "OrderId": "abc_123" + # } + + # 上传事件,包含账号ID与访客ID + try: + self.tga.track(distinct_id, account_id, event_name, new_data) + except Exception as e: + print("write to tga failed,output was {}".format(e)) + # self._close_tga(tga) + return False + # finally: + # self._close_tga(tga) + return True + + def put_user_data(self, data, method='user_set'): + # tga = self._init_tga_write() + try: + distinct_id, account_id, new_data = self._split_user_data(data) + except Exception as e: + print("拆解数据错误,输出为{}.请检查!".format(e)) + return False + try: + if method.lower() == "user_set": + self.tga.user_set(account_id=account_id, distinct_id=distinct_id, properties=new_data) + elif method.lower() == "user_setonce": + self.tga.user_setOnce(account_id=account_id, distinct_id=distinct_id, properties=new_data) + elif method.lower() == "user_add": + self.tga.user_add(account_id=account_id, distinct_id=distinct_id, properties=new_data) + elif method.lower() == "user_del": + self.tga.user_del(account_id=account_id, distinct_id=distinct_id) + else: + print("请提供用户操作类型 [user_set/user_setOnce/user_add/user_del] !") + return False + except Exception as e: + print("write to tga failed,output was {}".format(e)) + return False + # finally: + # self._close_tga(tga) + return True