def do_task(worker, job): from wanx.base.log import print_log from wanx.base.xredis import Redis from wanx.models.video import UserFaverVideo from wanx.models.user import User data = job.data # 记录日志 print_log('modify_video', data) data = json.loads(data) vid = data['vid'] # action = data['action'] # delta_count = 0 # if action == 'offline': # delta_count = -1 # elif action == 'online': # delta_count = 1 # 更新收藏了此视频的用户计数 uids = UserFaverVideo.favor_video_uids(vid) for uid in uids: user = User.get_one(uid, check_online=False) if user: key = UserFaverVideo.FAVER_VIDEO_IDS % ({'uid': uid}) Redis.delete(key) count = UserFaverVideo.faver_video_count(uid) user.update_model({'$set': {'favor_count': count}}) return ''
def _operation_log(self, obj, action): log_data = dict(user=request.environ.get('REMOTE_USER'), action=action, model=self.Model.__name__, obj_id=str(obj._id), data=bjson.dumps(obj)) print_log('admin_operation', bjson.dumps(log_data))
def user_gifts_class(): """获取用户所有礼物分类 (GET&LOGIN) :uri: /gifts/user_gifts_class :return: {'gifts': list} """ requ_type = request.values['requ_type'] user = request.authed_user pdict = {} for p in Product.get_all_gifts(): pdict[p.product_id] = p.format() uproducts = UserProduct.get_user_products(str(user._id)) from wanx.base.log import print_log print_log('activity/team_vote', '[uproducts]: {0}'.format(uproducts)) for up in uproducts: if up.product_id not in pdict: continue pdict[up.product_id].update(up.format()) if requ_type == 'get_pay_gifts': pay_gifts = [] for gift in pdict.values(): if gift['product_type'] == 3 and gift.get( 'is_money', '') and gift.get('num', 0) != 0: g = Gift.get_gift_by_product_id(gift['product_id']) if g: gift['credit_value'] = float(g.credit_value) / float(100) pay_gifts.append(gift) cfg = GiftExchangeCfg.get_gift_config() is_exchange_time = GiftExchangeCfg.is_exchange_time() # 是否在兑换时间内 total_credit_value = UserProduct.get_current_money(pay_gifts) return { 'gifts': pay_gifts, 'total_credit_value': total_credit_value, 'is_exchange_time': is_exchange_time, 'gifts_config': cfg.format() } elif requ_type == 'get_gold_gifts': gold_gifts = [] from wanx.base.log import print_log print_log('activity/team_vote', '[pdict]: {0}'.format(pdict)) for gift in pdict.values(): if gift['product_type'] == 3 and not gift.get( 'is_money', '') and gift.get('num', 0) != 0: g = Gift.get_gift_by_product_id(gift['product_id']) if g: if int(g.gift_id) == 1: gift['credit_value'] = 0 else: gift['credit_value'] = g.credit_value gold_gifts.append(gift) total_gold_value = UserProduct.get_current_gold(gold_gifts) return {'gifts': gold_gifts, 'total_credit_value': total_gold_value}
def check_request_status(self, job_request): if job_request.complete: return True elif job_request.timed_out: print_log('gearman', 'Job(%s):time out' % (job_request.unique)) else: print_log( 'gearman', 'Job(%s): failed status(%s)' % (job_request.unique, job_request.state)) return False
def get_live_battle(cls, live_id, live_name, device): url = urljoin(app.config.get("MATCH_URL"), '/migu_match/get_live_battle?live_id={0}&live_name={1}&device={2}'.format( live_id, live_name, device)) print_log('activity/team_vote', '[url]: {0}'.format(url)) try: resp = requests.get(url) except requests.exceptions.RequestException: return {} data = json.loads(resp.content) battle = data['data'] return battle if battle else {}
def check_live_red_packets(interval_time): ts = time.time() try: _ids = LiveRedPacket.all_ids() lives = Xlive.get_all_lives() # print "ts", ts, _ids for rp in LiveRedPacket.get_list(_ids): data = dict(id=str(rp._id), expire_at=rp.expire_at) live_authors = [] if not rp.live_authors else rp.live_authors.split( '\r\n') live_games = [] if not rp.live_games else rp.live_games.split( '\r\n') key_words = [] if not rp.keyword else rp.keyword.split(u',') # 如果是定时发红包,则到时间即刻触发弹幕通知 for live in lives: # 过滤非定时及主播开播时长任务 if rp.mode not in [0, 1]: continue # 过滤主播 if live_authors and live['user_id'] not in live_authors: # print "1", live_authors, live['user_id'] continue # 过滤游戏 if live_games and live['game_id'] not in live_games: # print "2", live_games, live['game_id'] continue # 过滤关键字 if key_words and not any( map(lambda x: x in live['name'], key_words)): # print "3", key_words, live['name'] continue # 如果是定时任务,只在第一次发送 if rp.mode == 0 and ts - rp.begin_at > interval_time: # print "5", ts, rp.begin_at, rp.mode, interval_time continue # 如果是主播开播时长任务,在主播时长达到时发送一次 count_at = max(live['create_at'], rp.begin_at) if rp.mode == 1 and not 0 <= ts - count_at - rp.delay * 60 <= interval_time: # print "6", ts, count_at, rp.mode, rp.delay, interval_time continue data.update({'event_id': str(live['event_id'])}) # print "Xlive.send_live_msg", data, 'red_packet', ts record = '[%s] event_id=%s, active_id=%s' % ( 'Red Packet', live['event_id'], data['id']) print_log('timed_task', record) Xlive.send_live_msg(data, 'red_packet') except Exception, e: print_log('timed_task', '[%s] %s' % ('Red Packet', str(e)))
def get_match_live(cls, uid, name): """根据主播id和直播间name获取赛事直播 """ all_lives = cls.get_all_lives() print_log('xlive', '[get_match_live - all_lives]: {0}'.format(all_lives)) match_live = filter( lambda x: x['user_id'] == uid and x['name'] == name, all_lives) match_live.sort(key=lambda x: x['create_at'], reverse=True) print_log('xlive', '[get_match_live - match_live]: {0}'.format(match_live)) return match_live
def send_live_msg(cls, data, mode='gift'): """发送直播弹幕信息 """ # 后台配置是否开启直播服务, 默认开启 api_url = Config.fetch('live_api_url', None, str) if not api_url: return uri = '/events/%s/notify' % (data['event_id']) api_url = urljoin(api_url, uri) msg = {'type': mode, 'data': data} try: requests.post(api_url, json=msg, timeout=2) except requests.exceptions.Timeout: print_log('xlive', '[send_live_msg]: connection timeout') except: print_log('xlive', '[send_live_msg]: connection error')
def postdata(app_key=app.config.get("JPUSH_APP_KEY"), master_secret=app.config.get("JPUSH_MASTER_SECRET")): session, headers, schedule_url = jpush_schedule_auth(app_key, master_secret) r = session.request("POST", schedule_url, data=json.dumps(push_data), params=None, headers=headers, timeout=30) print_log('jpush_create_response_log', r.text) message_tag = [translate_md5(str(id)+'message')] push_data['audience']['tag'] = message_tag del push_data['notification'] push_data['message'] = {"content_type": "text", "title": "msg"} push_data['message']['msg_content'] = message_content push_data['message']['extras'] = {"an_url": an_post_str, "ios_url": ios_post_str, "title": push_title, "content": push_content, "event_id": event_id} r = session.request("POST", schedule_url, data=json.dumps(push_data), params=None, headers=headers, timeout=30) print_log('jpush_create_response_log', r.text)
def get_match_lives(): """获取推荐的赛事直播列表 (GET) :uri: /lives/match :param live_user_id: 主播ID :param live_name: 主播间名称 :returns: {'lives': list} """ user_id = request.values.get('live_user_id') name = request.values.get('live_name') lives = Xlive.get_match_live(str(user_id), name) print_log('xlive', '[get_match_lives - lives]: {0}'.format(lives)) if not lives: return error.LiveError('直播不存在') lives = [Xlive.format(l) for l in lives] return {'lives': lives}
def getbattle(cls, live_user_id, live_name): """所有直播用户id和直播间名称获取对战id """ api_url = app.config.get('MATCH_SERVER_URL', None) if not api_url: return None api_url = urljoin(api_url, '/migu_match/getbattlebylive?live_user_id={0}&live_name={1}' .format(live_user_id, live_name)) try: resp = requests.get(api_url, timeout=2) except requests.exceptions.Timeout: print_log('xmatch', '[getbattle]: connection timeout') return None except: print_log('xmatch', '[getbattle]: connection error') return None battle = resp.content battle = json.loads(battle) return battle
def get_all_lives(cls): """所有直播间列表 """ # 后台配置是否开启直播服务, 默认开启 api_url = Config.fetch('live_api_url', None, str) if not api_url: return [] api_url = urljoin(api_url, '/events') lives = Redis.get(cls.ALL_LIVES) if not lives: try: resp = requests.get(api_url, timeout=2) except requests.exceptions.Timeout: print_log('xlive', '[get_all_lives]: connection timeout') return [] except: print_log('xlive', '[get_all_lives]: connection error') return [] if resp.status_code != requests.codes.ok: print_log('xlive', '[get_all_lives]: status_code not ok') return [] lives = resp.content lives = json.loads(lives)['data']['live'] Redis.setex(cls.ALL_LIVES, 5, json.dumps(lives)) else: lives = json.loads(lives) # 按照人气排序 lives.sort(key=lambda x: x['count'], reverse=True) return lives
def get_event(cls, event_id): """获取直播 """ # 后台配置是否开启直播服务, 默认开启 api_url = Config.fetch('live_api_url', None, str) if not api_url: return [] api_url = urljoin(api_url, '/events/{0}'.format(event_id)) try: resp = requests.get(api_url, timeout=2) except requests.exceptions.Timeout: print_log('xlive', '[get_event]: connection timeout') return [] except: print_log('xlive', '[get_event]: connection error') return [] if resp.status_code != requests.codes.ok: print_log('xlive', '[get_event]: status_code not ok') return [] live = resp.content live = json.loads(live)['data'] return live
def certify_sms_code(): """获取实名认证验证码 (GET|POST) :uri: /users/certify_sms_code :param phone: 手机号 :param ut: ut :returns: {} """ phone = request.values.get("phone", None) ut = request.values.get("ut", None) if not phone: return error.InvalidArguments user_id = User.uid_from_token(ut) code = str(random.randint(0, 9)) + str(random.randint(0, 9)) + str( random.randint(0, 9)) + str(random.randint(0, 9)) + str( random.randint(0, 9)) + str(random.randint(0, 9)) if UserCertify.is_mobile(phone): con = '您在咪咕游戏申请实名认证解绑的验证码为:{0},5分钟有效。'.format(code) # UserCertify.send_code(phone, con) phones = list() phones.append(phone) try: job = 'send_sms' data = dict(phones=phones, content=con) gm_client = gearman.GearmanClient(app.config['GEARMAN_SERVERS']) gm_client.submit_job(job, json.dumps(data), background=True, wait_until_complete=False, max_retries=5) except gearman.errors.GearmanError: pass except Exception, e: print_log('send_sms_err', str(e))
def do_task(worker, job): from wanx.base.log import print_log from wanx.platforms.sms import SendSmsService from wanx.models.user import User, UserGroup data = job.data # 记录日志 print_log('send_sms', data) data = json.loads(data) if 'phones' in data: phones = data['phones'] else: uids = UserGroup.group_user_ids(data['group']) phones = [ user.phone for user in User.get_list(uids, check_online=False) ] content = data['content'] for phone in phones: if not phone: continue SendSmsService.send_report_warning(phone, content) return ''
def do_task(worker, job): from wanx.base.log import print_log from wanx.base import const from wanx.models.video import Video from wanx.models.user import User from wanx.models.game import Game data = job.data # 记录日志 print_log('create_live_video', data) data = json.loads(data) # 记录日志 print_log('create_live_video', '%s ==========================> Start' % (data['event_id'])) user = User.get_one(data['user_id'], check_online=False) if not user: return '' game = Game.get_one(data['game_id'], check_online=False) if not game: return '' video_id = Video.get_video_by_event_id(data['event_id'], str(user._id)) video = Video.get_one(str(video_id), check_online=False) if not video: video = Video.init() video.author = ObjectId(data['user_id']) video.game = ObjectId(data['game_id']) video.title = data['title'] video.duration = data['duration'] video.ratio = data['ratio'] video.cover = data['cover'] video.url = data['url'] video.event_id = data['event_id'] video.status = const.ONLINE video.create_model() else: data['author'] = ObjectId(data.pop('user_id')) data['game'] = ObjectId(data.pop('game_id')) video.update_model({'$set': data}) # 记录日志 print_log('create_live_video', '%s ==========================> Finished' % (data['event_id'])) from wanx.models.activity import Battle battle = Battle.get_live_battle( data['user_id'], data['title'].decode('unicode-escape').encode('utf-8'), None) if battle: Battle.set_video_id(battle['_id'], video_id) return ''
def send_traffic(cls, requestid, phone): """ :param requestid: 唯一标识字符串,客户端生成, :param phone: 手机号码 :return: """ m = hashlib.md5() _m = hashlib.md5() m.update(cls.key) _m.update(requestid + '+' + str(m.hexdigest()).upper()) requesttoken = str(_m.hexdigest()).upper() xml = '''<?xml version='1.0' encoding='utf-8'?> <REQUEST> <ACTION>MeberShipRequest</ACTION> <RequestID>%s</RequestID> <RequestToken>%s</RequestToken> <ECCode>2000001040</ECCode> <ChannelID>1</ChannelID> <BODY> <Member> <CRMApplyCode>10001</CRMApplyCode> <UsecyCle>1</UsecyCle> <Mobile>%s</Mobile> <UserName>全网流量150M套餐</UserName> <EffType>2</EffType> <PrdCode>prod.10000008585103</PrdCode> <OptType>0</OptType> </Member> </BODY> </REQUEST>''' % (str(requestid), requesttoken, str(phone)) headers = {'content-type': 'text/xml'} try: resp = requests.post(cls.send_url, data=xml, headers=headers, timeout=10) except requests.exceptions.Timeout: print_log('migu_traffic', '[send_traffic][%s]: connection timeout' % (requestid)) return False except: print_log('migu_traffic', '[send_traffic][%s]: connection error' % (requestid)) return False print_log('migu_traffic', '[send_traffic][%s]: (%s) %s' % (requestid, resp.status_code, resp.content)) if resp.status_code != requests.codes.ok: return False st = re.compile(r'<ResultCode>(\d+)</ResultCode>') ret = st.findall(resp.content) return int(ret[0]) == 0 if ret else False
def query_traffic(cls, requestid): """ :param requestid: 唯一标识字符串,客户端生成, :returns: 0=成功,-1 = 失败, 1 = 正在处理中 该接口返回含义与充值接口不同,代表提交到上游接口的状态 该接口返回成功仅代表上游接口成功处理(多数情况为成功送出流量,个别省份只能代表已成功收到请求) """ m = hashlib.md5() _m = hashlib.md5() m.update(cls.key) _m.update(requestid + '+' + str(m.hexdigest()).upper()) requesttoken = str(_m.hexdigest()).upper() xml = '''<?xml version='1.0' encoding='utf-8'?> <REQUEST> <ACTION>MeberShipQuery</ACTION> <RequestID>%s</RequestID> <RequestToken>%s</RequestToken> <ECCode>2000001040</ECCode> </REQUEST> ''' % (str(requestid), requesttoken) headers = {'content-type': 'text/xml'} try: resp = requests.post(cls.query_url, data=xml, headers=headers, timeout=10) except requests.exceptions.Timeout: print_log('migu_traffic', '[query_traffic][%s]: connection timeout' % (requestid)) return False except: print_log('migu_traffic', '[query_traffic][%s]: connection error' % (requestid)) return False print_log('migu_traffic', '[query_traffic][%s]: (%s) %s' % (requestid, resp.status_code, resp.content)) if resp.status_code != requests.codes.ok: return False st = re.compile(r'<ResultCode>(\S+)</ResultCode>') ret = st.findall(resp.content) return ret[0]
def do_task(worker, job): from wanx.base.log import print_log from wanx.base import const, util, jpush from wanx.models.user import User from wanx.models.game import Game from wanx.models.live import Live_Activity from wanx.models.activity import ActivityConfig from wanx.models.game import GameActivity from wanx.models.task import BEGIN_LIVE, UserTask from wanx.base.xredis import Redis from wanx.base.xmysql import MYDB from wanx.platforms.xmatch import Xmatch data = job.data # 记录日志 print_log('create_live_activity', data) data = json.loads(data) # 记录日志 print_log('create_live_activity', '%s ==========================> Start' % (data['event_id'])) user = User.get_one(data['user_id'], check_online=False) if not user: return '' # 主播上线push推送 push_content = u"您关注的主播 {0} 正在直播,点击围观".format(user.nickname) message_content = u"您关注的主播 {0} 正在直播,速速去围观吧!".format(user.nickname) an_link = "playsdk://video_live/{0}/".format(data['event_id']) ios_link = "playsdk://live/{0}".format(data['event_id']) jpush.jpush_schedule_create(data['event_id'], user, push_content, message_content, an_link, ios_link) # 赛事预约直播上线推送 battle = Xmatch.getbattle(user._id, data['name']) if battle: battle = battle['data']['battle'] push_title = u'您预约的比赛正在进行' push_content = u"{0} vs {1}正在直播,点击围观".format(battle['team_1'], battle['team_2']) message_content = u"您预约的比赛{0} vs {1}正在直播!".format( battle['team_1'], battle['team_2']) if battle.get('players', '') != "": push_content = message_content = battle['live_name'] an_link = "playsdk://video_live/{0}/".format(data['event_id']) ios_link = "playsdk://live/{0}".format(data['event_id']) jpush.jpush_withtitle_create(data['event_id'], battle['_id'], push_title, push_content, message_content, an_link, ios_link) game = Game.get_one(data['game_id'], check_online=False) if not game: return '' aid = None aids = ActivityConfig.get_by_type(const.FROM_LIVE) for a in ActivityConfig.get_list(aids): gids = GameActivity.game_activity_ids(a['_id']) if gids and data['game_id'] not in gids: continue aid = a['_id'] break if not aid: return '' print_log('create_live_activity', '%s ==========================> activity_id' % (aid)) activity_live = Live_Activity.get_activity_live(str(user._id), aid) if not activity_live: key = 'lock:activity:live:%s:%s' % (str(user._id), aid) with util.Lockit(Redis, key) as locked: if locked: return '' activity_live = Live_Activity.init() activity_live.author = ObjectId(data['user_id']) activity_live.game = ObjectId(data['game_id']) activity_live.event_id = data['event_id'] activity_live.activity_id = ObjectId(aid) activity_live.create_model() # 如果没有活动任务则创建 UserTask.create_and_init_user_tasks(str(user._id)) if not MYDB.is_closed(): MYDB.close() try: UserTask.check_user_tasks(user._id, BEGIN_LIVE, 1, data['game_id'], aid) except Exception as e: print_log('create_live_activity', '%s ========' % e) if not MYDB.is_closed(): MYDB.close() # 记录日志 print_log('create_live_activity', '%s ==========================> Finished' % (data['event_id'])) return ''
def traffic_send(): """发放流量 (GET|POST&LOGIN) :uri: /traffic/send :param traffic_type: (first_login, video_share) :returns: {'message': str} """ user = request.authed_user traffic_type = request.values.get('traffic_type', None) device = request.values.get('device', None) status = ActivityConfig.activity_status() if const.ACTIVITY_PAUSE == status: print_log('app_traffic', '[%s][%s]: activity is pause' % (traffic_type, user.phone)) return error.TrafficSendFail(u'小伙伴们太热情了,稍后再来吧!') elif const.ACTIVITY_END == status: print_log('app_traffic', '[%s][%s]: activity is end' % (traffic_type, user.phone)) return error.UserTrafficZero(u'亲,我们的奖品已经送完啦,下次要早点来哦!') utl = UserTrafficLog.get_traffic_by_type(str(user._id), traffic_type) if not utl and traffic_type == 'video_share': print_log('app_traffic', '[video_share][%s]: UserTrafficExists' % user.phone) return error.UserTrafficExists(u'亲,你还没有分享自己的作品哦,赶快去分享你的游戏视频,再来领取吧!') elif utl and utl.status in [ const.TRAFFIC_SUCCESS, const.TRAFFIC_RECEIVED_SUCCESS, const.TRAFFIC_RECEIVED_PROCESS ]: print_log('app_traffic', '[%s][%s]: TrafficExists' % (traffic_type, user.phone)) return error.TrafficExists utl_device = UserTrafficLog.get_traffic_by_device(device, traffic_type) if utl_device: print_log( 'app_traffic', '[%s][%s][%s]: device repeat' % (traffic_type, user.phone, device)) return error.UserTrafficInvalid(u'亲,同一部终端只能领取一次流量哦!') utl_count = UserTrafficLog.traffic_count_by_type(traffic_type) if utl_count and utl_count > const.TRAFFIC_CATEGORY_NUM.get( traffic_type, None): print_log('app_traffic', '[%s][%s]: UserTrafficZero' % (traffic_type, user.phone)) return error.UserTrafficZero(u'亲,我们的奖品已经送完啦,下次要早点来哦!') key = 'lock:traffic:%s:%s' % (user.phone, utl.order_id) with util.Lockit(Redis, key) as locked: if locked: return error.TrafficSendFail # 移动接口返回 if Traffic.send_traffic(utl.order_id, user.phone): utl.update_model( {'$set': { 'status': const.TRAFFIC_SUCCESS, 'device': device }}) else: utl.update_model({'$set': {'status': const.TRAFFIC_FAIL}}) return error.TrafficSendFail(u'小伙伴们太热情了,稍后再来吧!') return {"message": "你已经成功分享视频, 恭喜你获得免费流量150M, 礼物将以光速飞到你的碗里去哦, 请注意查收!"}
def activity_team_vote(): """战队投票 :uri: activity/team_vote :param source: 投票来源(app_play, activity, activity_share, video_share) :param device: 设备唯一ID :param team_id: 战队ID :param ut: 用户ut :return: {'team_vote_count': int} """ user = request.authed_user print_log('activity/team_vote', '[user]: {0}'.format(user)) params = request.values.to_dict() tid = params.get('team_id', None) source = params.get('source', None) device = params.get('device', None) uid = user and str(user._id) if not tid or not source or not device: return error.InvalidArguments # 增加ip限制,每个ip每天限制20次 user_ip = request.remote_addr ip_key = 'ip_limit:%s:%s:%s' % (user_ip, tid, str(datetime.date.today())) ip_limit = Redis.incr(ip_key) if ip_limit == 1: # 第一次设置key过期时间 Redis.expire(ip_key, 86400) if ip_limit > 20: return error.ActivityVideoNotExist("超出IP限制") mteam = Mteam.get_one(tid) if not mteam: return error.MteamNotExist vote_count = int(mteam['ticket']) mname = str(mteam['mname']) course = MatchCourse.get_course_by_mname(mname) now = int(time.time()) if course: if int(course.course_end) < now: return error.VoteVideoFailed else: return error.VoteVideoFailed vote = VoteMteam.get_vote(uid=uid, device=device, tid=tid) if not vote: key = 'lock:vote_mteam:%s:%s' % (device, tid) with util.Lockit(Redis, key) as locked: if locked: return error.VoteVideoFailed vote = VoteMteam.init() vote.device = device vote.source = source vote.author = ObjectId(uid) vote.target = ObjectId(tid) vote.mname = ObjectId(mname) vote.create_model() # 票数加1 vote_count = vote_count + 1 return {'vote_count': vote_count}
def report(): """举报 :uri: /user/report :param target_id: 被举报id :param type: 举报原因 :param content: 举报内容 :param source: 举报来源,0:来自视频,1:来自直播,2:来自评论,3:来自回复 :returns: {} """ params = request.values tid = params.get('target_id', None) _type = int(params.get('type', 0)) content = params.get('content', None) source = int(params.get('source', 0)) from_user = request.authed_user if not tid or not _type or source not in range(4): return error.InvalidArguments if source == 0: video = Video.get_one(tid) if not video: return error.VideoNotExist uid = video.author title = video.title elif source == 1: live = Xlive.get_live(tid) if not live: return error.LiveError('直播不存在') uid = live.get('user_id') title = live.get('name') elif source == 2: comment = Comment.get_one(tid) if not comment: return error.CommentNotExist uid = comment.author title = comment.content elif source == 3: reply = Reply.get_one(tid) if not reply: return error.ReplyNotExist uid = reply.owner title = reply.content key = 'lock:reports:object:%s' % (tid) with util.Lockit(Redis, key) as locked: if locked: return error.ReportVideoFailed('举报失败,请稍后再试') if ReportVideo.check_reported(tid, source, from_user._id): return error.ReportVideoExists rv = ReportVideo.init() rv.uid = uid rv.vid = tid rv.type = _type rv.content = content if content else '' rv.source = source rv.from_user = from_user._id rv.status = 0 rv.deleted = 0 rv.bannef = 0 rv.create_model() rpc_id = ReportConfig.get_limit_config(source) rpconfig = ReportConfig.get_one(rpc_id) if not rpconfig: return {} max_limit = rpconfig.max_limit if max_limit and ReportVideo.reach_max_limit(tid, max_limit): _templates = [ u'用户ID %(id)s,标题为"%(title)s"的视频正在被举报,请尽快审核', u'房间号为%(id)s,标题为"%(title)s"的直播正在被举报,请尽快审核', u'用户%(id)s针对"%(title)s"视频的评论正在被举报,请尽快审核', u'用户%(id)s针对"%(title)s"评论的回复正在被举报,请尽快审核' ] _id = tid if source == 1 else uid try: job = 'send_sms' data = dict(group=str(rpconfig.group), content=_templates[source] % { 'id': str(_id), 'title': title }) gm_client = gearman.GearmanClient( app.config['GEARMAN_SERVERS']) gm_client.submit_job(job, json.dumps(data), background=True, wait_until_complete=False, max_retries=5) except gearman.errors.GearmanError: pass except Exception, e: print_log('send_sms_err', str(e))
def send_sms(cls, phone, content, smsid, log_func=None, log_id=None): human_errors = { 'send_report_warning': '发送举报消息告警失败', } human_error = human_errors.get(log_func, '未知错误') timeStamp = time.strftime('%Y%m%d%H%M%S') spId = '990123' PASSWORD = '******' OA = '106588997803' tel = '86' + phone code = spId + PASSWORD + timeStamp md5 = hashlib.md5() md5.update(code.encode()) spPassword = md5.hexdigest() headers = {'Content-Type': 'text/xml; charset=utf-8'} xml = ''' <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" \ xmlns:v2="http://www.huawei.com.cn/schema/common/v2_1" \ xmlns:loc="http://www.csapi.org/schema/parlayx/sms/send/v2_2/local"> <soapenv:Header> <v2:RequestSOAPHeader> <v2:spId>{spId}</v2:spId> <v2:spPassword>{spPassword}</v2:spPassword> <v2:serviceId>{spId}</v2:serviceId> <v2:timeStamp>{timeStamp}</v2:timeStamp> <v2:OA>{OA}</v2:OA> <v2:FA>tel:{tel}</v2:FA> <v2:localCarrierID>0</v2:localCarrierID> </v2:RequestSOAPHeader> </soapenv:Header> <soapenv:Body> <loc:sendSms> <loc:addresses>tel:{tel}</loc:addresses> <loc:senderName>{OA}</loc:senderName> <loc:charging> <description>jifei</description> <currency>RMB</currency> <amount>0</amount> <code>223323</code> </loc:charging> <loc:message>{content}</loc:message> <loc:receiptRequest> <endpoint>http://172.16.4.15:8310/SendSmsService/services/Sen</endpoint> <interfaceName>SmsNotification</interfaceName> <correlator>123</correlator> </loc:receiptRequest> </loc:sendSms> </soapenv:Body> </soapenv:Envelope> '''.format(spId=spId, spPassword=spPassword, timeStamp=timeStamp, OA=OA, tel=tel, content=content) try: resp = requests.post(cls.url, data=xml, headers=headers, timeout=5) except requests.exceptions.Timeout: print_log('portalone_sms', '[%s][%s]: connection timeout' % (log_func, log_id)) return error.MiguError('网络连接超时') except: print_log('portalone_sms', '[%s][%s]: connection error' % (log_func, log_id)) return error.MiguError('网络连接失败') print_log( 'portalone_sms', '[%s][%s]: (%s) %s' % (log_func, log_id, resp.status_code, resp.content.decode('utf8'))) if resp.status_code != requests.codes.ok: return error.MiguError('网络请求错误') st = re.compile(r'<status>(\d+)</status>') ret = st.findall(resp.content) if ret and int(ret[0]) != 0: errmsg = error.MIGU_ERROR.get(ret[0], human_error) return error.MiguError(errmsg) return resp.content if ret else error.MiguError(human_error)