Exemple #1
0
def back_merge_server(request):
    server_list = request.POST.getlist('sid')
    server_list = [int(s) for s in server_list]
    base_query = Q(id__in=server_list)
    master_server_id = Server.objects.filter(base_query & Q(status=2))[0].id
    request.POST['master_server_id'] = master_server_id
    merge_server_ids = Server.objects.filter(base_query & Q(status=1))
    merge_server_ids = [s.id for s in merge_server_ids]
    request.POST["server_id"] = merge_server_ids
    write_hefu_log(request.admin.id, master_server_id,
                   json.dumps(merge_server_ids), "开始回滚", -1)

    gmp = GMProtocol(master_server_id)
    result = gmp.back_merge_server(merge_server_ids)
    print result
    msg = {"code": 1}
    if result == 0:
        msg["msg"] = "回滚合服成功!!!"
        write_hefu_log(request.admin.id, master_server_id,
                       json.dumps(merge_server_ids), msg["msg"], 2)
        return HttpResponse(json.dumps(msg))
    msg["msg"] = "回滚合服失败:%s" % (result["msg"]
                                if type(result) == dict else "服务端返回失败!")
    write_hefu_log(request.admin.id, master_server_id,
                   json.dumps(merge_server_ids), msg["msg"], 3)
    return HttpResponse(json.dumps(msg))
Exemple #2
0
    def handle(self, *args, **options):
        keep_connections()
        print '检测服务器已删除状态,开服时间自动改状态进程&清白名单 开启:%s ' % datetime.datetime.now()

        while 1:
            keep_connections()
            
            try:
                now = datetime.datetime.now()
                ser_l = Server.objects.using('write').filter(status=-1)
                if ser_l:
                    for s in ser_l:
                        create_time = s.create_time
                        dt = now - create_time
                        if dt.days == 0 and dt.seconds/60 > 0 and dt.seconds/60 < 3:
                            sid = int(s.id)
                            gmp = GMProtocol(sid)
                            result = gmp.modify_white_list([])
                            if result == 0:
                                s.status = 5
                                s.commend = 1
                                s.save()
                                if s.status == 5:
                                    print '%s-----%s服务器状态修改成火爆' %(now,sid)

                                    server_make({})
                                    print '%s-----%s服务器白名单清空并生成服务器列表' %(now,sid)

            except Exception,e:
                traceback.print_exc()

            time.sleep(60)
Exemple #3
0
def send_resource_to_gm(card_log_model):
    msg = ''
    if card_log_model.status != 1:
        card_log_model.status = 3
        try:
            msg = json.loads(card_log_model.prize)
            #线程内mysql连接不同享,每个线程的内连接必须先ping下,防止mysql超时断开
            try:
                connections['write'].connection.ping()
            except:
                connections['write'].close()
            try:
                connections['card'].connection.ping()
            except:
                connections['card'].close()
            server_model = Server.objects.using('write').get(
                id=card_log_model.server_id)
            gmp = GMProtocol(card_log_model.server_id,
                             'card',
                             server_model=server_model)
            gmp.time_out = 7
            result = gmp.send_card_resouces(card_log_model.player_id,
                                            card_log_model.card_name, msg)
            card_log_model.status = 3
            if result == 0:
                card_log_model.status = 1
            msg = '成功!'
        except Exception, e:
            msg = '失败[%s]!' % str(e)
            traceback.print_exc()
Exemple #4
0
def save_battle_many(request):
    params = request.REQUEST.get("params",{})
    action = request.REQUEST.get("action",False)
    send_to_server = request.REQUEST.get("send_to_server",[])
    params = json.loads(params)
    send_to_server = json.loads(send_to_server)
    msg = ""
    print params,send_to_server,action
    if action == "change_sort":
        sort = int(request.REQUEST.get("sort",0))
    if action == "change_version":
        version = int(request.REQUEST.get("ver",0))
    if action == "send_reward":
        for s in params:
            gmp = GMProtocol(int(s))
            result = gmp.send_battle_reward()
            if result == 0:
                msg = json.dumps({"code":0,"msg":"发送成功"})
                model = BattleList.objects.filter(server=int(s))[0]
                model.status = 2
                model.save(using='write')
            else:
                msg = json.dumps({"code":1,"msg":"发送失败"})
        return  HttpResponse(msg)

    for k,v in params.iteritems():
        try:
            model = BattleList.objects.filter(server = int(k))
            model = model[0]
            if action == "change_sort":
                model.sort = sort
            elif action == "change_version":
                model.version = version
            if v[0] and v[1]:
                model.group = v[0].upper()
                model.sub_group = v[1].strip()
            if send_to_server[-1]["run_time"]:
                model.run_time = send_to_server[-1]["run_time"]
            model.last_time = datetime.datetime.now()
            model.save(using='write')
        except BaseException as e :
            print e
            continue

    #保存完批量发送
    if send_to_server and not send_to_server[-1]["run_time"]:
        print send_to_server.pop()
        msg = send_all_battle(request.admin.id,params=params,send_type=send_to_server)

    if msg:
        print msg
        return HttpResponse(json.dumps({"code":0,"msg":"%s没主服发送失败"%json.dumps(msg)}))
    return HttpResponse(json.dumps({"code":0,"msg":"发送成功"}))
Exemple #5
0
def server_charge_reset(request):
    result_msg = ''
    if request.method == 'POST':
        ids = request.REQUEST.get('ids', '')
        if not ids:
            return HttpResponse("没有选择服务器")
        ids = json.loads(ids)
        for sid in ids:
            gmp = GMProtocol(sid)
            result = gmp.server_charge_reset()
            if result == 0:
                result_msg = '操作成功'
            else:
                result_msg = '操作失败'

    return HttpResponse(result_msg)
Exemple #6
0
def auto_server_merge(request):
    server_list = request.POST.getlist('sid')
    server_list = [int(s) for s in server_list]
    base_query = Q(id__in=server_list)
    master_server_id = Server.objects.filter(base_query & Q(status=2))[0].id
    request.POST['master_server_id'] = master_server_id
    merge_server_ids = Server.objects.filter(base_query & Q(status=1))
    merge_server_ids = [s.id for s in merge_server_ids]
    request.POST["server_id"] = merge_server_ids
    write_hefu_log(request.admin.id, master_server_id,
                   json.dumps(merge_server_ids), "开始合服", -1)

    write_hefu_log(request.admin.id, master_server_id,
                   json.dumps(merge_server_ids), "开始踢人", -1)
    # 先踢所有子服玩家
    for s in merge_server_ids:
        gmp = GMProtocol(s)
        result = gmp.server_offline()
        if result != 0:
            return HttpResponse(
                json.dumps({
                    "code": 0,
                    "msg": "%s 服 踢人失败!!" % (s)
                }))
    write_hefu_log(request.admin.id, master_server_id,
                   json.dumps(merge_server_ids), "踢人成功", -1)

    gmp = GMProtocol(master_server_id)
    result = gmp.auto_merge_server(merge_server_ids)
    print result
    msg = {"code": 1}
    if result == 0:
        write_hefu_log(request.admin.id, master_server_id,
                       json.dumps(merge_server_ids), "杀子服进程", -1)
        # 子服杀自己
        for sid in merge_server_ids:
            gmp = GMProtocol(sid)
            _result = gmp.stop_server()
        write_hefu_log(request.admin.id, master_server_id,
                       json.dumps(merge_server_ids), "杀子服进程完成", -1)
        result = server_merge(request, auto_merge=True)
        print result
        if result["result"] == "success":
            msg["msg"] = "合服成功!!!"
            write_hefu_log(request.admin.id, master_server_id,
                           json.dumps(merge_server_ids), msg["msg"], 1)
            return HttpResponse(json.dumps(msg))
    msg["msg"] = "合服失败:%s" % (result["msg"]
                              if type(result) == dict else "服务端返回失败!")
    write_hefu_log(request.admin.id, master_server_id,
                   json.dumps(merge_server_ids), msg["msg"], 0)
    return HttpResponse(json.dumps(msg))
Exemple #7
0
def player_block(request, server_id=0):
    '''封号
    '''
    player_ids = request.REQUEST.getlist('player_id')
    server_id = int(request.REQUEST.get('server_id', 0))
    _r = {"code": -1, "msg": ""}
    if request.method == 'POST' and player_ids:
        try:
            remark = request.REQUEST.get('remark', '')
            conn = getConn(server_id)
            cursor = conn.cursor()
            the_status = -1
            gmp = GMProtocol(server_id)
            if request.REQUEST.get('block_type', '') == '1':
                the_status = -1
                log_type = GMActionType.block_player
                result = gmp.block_player(player_ids)
                if result != 0:
                    return HttpResponse(json.dumps(_r))
            else:
                the_status = 0
                log_type = GMActionType.unblock_player
                result = gmp.unblock_player(player_ids)
                if result != 0:
                    return HttpResponse(json.dumps(_r))
            query_sql = 'update player_%d set status=%d where player_id in (%s)' % (
                server_id, the_status, ','.join(player_ids))
            cursor.execute(query_sql)
            cursor.close()
            for player_id in player_ids:
                write_gm_log(
                    request.admin.id,
                    log_type,
                    log_type,
                    server_id,
                    player_id,
                    '',
                    0,
                    '',
                    '',
                    remark1=remark,
                )
            _r["code"] = 0

        except Exception, e:
            err_msg = trace_msg()
            _r["msg"] = err_msg
Exemple #8
0
    def get_score(self, server_id=0):
        servers = BattleList.objects.all()
        Arena_score = {1: 10, 2: 5, 3: 1}
        Star_score = {1: 3, 2: 2, 3: 1}
        for s in servers:
            gmp = GMProtocol(int(s.server))
            result = gmp.get_battle_score(21)
            if result:
                for l in result:
                    try:
                        server = BattleList.objects.filter(server=l[1])[0]
                        server.f3 = Arena_score[
                            l[2]] if l[2] in Arena_score else 0
                        server.last_time = datetime.datetime.now()
                        server.save()
                        print u'%s 服 战场排名为:%s,保存成功' % (l[1], l[2])
                    except BaseException as e:
                        print u'%s 服 战场排名为:%s,保存失败.%s' % (l[1], l[2], e)

            result = gmp.get_battle_score(20)
            if result:
                for l in result:
                    try:
                        server = BattleList.objects.filter(server=l[1])[0]
                        server.f2 = l[2]
                        server.last_time = datetime.datetime.now()
                        server.save()
                        print u'%s 服 荒兽数量为:%s,保存成功' % (l[1], l[2])
                    except BaseException as e:
                        print u'%s 服 荒兽数量为:%s,保存失败.%s' % (l[1], l[2], e)

            result = gmp.get_battle_score(19)
            if result:
                del result[0]
                _s = set()
                for l in result:
                    try:
                        server = BattleList.objects.filter(server=l[1])[0]
                        #算积分
                        old_score = server.f1 if server.f1 else 0
                        new_score = Star_score[int(l[1])] * int(l[2])
                        server.f1 = int(old_score) + new_score
                        server.last_time = datetime.datetime.now()
                        server.save()
                        print u'%s 服 魔星数量为:%s,保存成功' % (l[1], l[2])
                    except BaseException as e:
                        print u'%s 服 魔星数量为:%s,保存失败.%s' % (l[1], l[2], e)
Exemple #9
0
def send_all_battle(log_user,params=None,send_type=None):
    servers = BattleList.objects.all()
    kuafu_map = DictDefine.get_dict_for_key("kuafu_type")
    result = []
    save_log('logs/server/battle_server/','params',"%s"%params)
    for s in servers:
        if not s.group or not s.sort:
            continue
        if params:
            if s.server not in [int(x) for x in params.keys()]:
                continue
        base_query = Q(group=s.group) & Q(sort=s.sort)
        other_server = BattleList.objects.filter(base_query)
        server_list = []
        master_server = 0


        for _s in other_server:
            if int(_s.sub_group) == 1:
                master_server = _s.server
            server_list.append(_s.server)

        if not master_server:
            msg = u'%s服 没有主服 配置:大组-%s 分区-%s,分组-%s'%(s.server,s.sort,s.group,s.sub_group)
            save_log('logs/server/battle_server/','error',msg)
            result.append(s.server)
            for t in send_type:
                write_kuafu_log(log_user,t,s.server,s.sort,s.group,s.sub_group,msg,1)
            continue

        gmp = GMProtocol(int(s.server))
        _result = gmp.send_battle_server(master_server,server_list,send_type)
        if _result == 0:
            s.f8 = "success"
            s.last_time = datetime.datetime.now()
            s.status = 1
            s.save()
            msg = u'%s服 已发送 配置:大组-%s 分区-%s,分组-%s'%(s.server,s.sort,s.group,s.sub_group)
            print msg

            save_log('logs/server/battle_server/','success',msg)

            for t in send_type:
                write_kuafu_log(log_user,t,s.server,s.sort,s.group,s.sub_group,msg,0)
    return result
Exemple #10
0
def send_gift(card_no, player_id, server_id):
    """发送礼包卡奖励"""

    # 获取礼包卡标识(前三位)
    card_key = card_no[:3]

    # 根据礼包卡标识查出奖励
    card_batch = CardBatch.objects.using('card').get(key=card_key)
    gifts = json.loads(card_batch.prize)

    # 拼接GM命令
    GM_str = '#gmMail ' + str(player_id) + u' 礼包卡奖励 礼包卡奖励 '
    for gift in gifts:
        GM_str += str(gift['aID']) + ',' + str(gift['id']) + ',' + str(
            gift['v']) + ';'
    GM_str = GM_str.rstrip(';')

    # 发送GM命令
    gmp = GMProtocol(int(server_id))
    gmp.send_mail(GM_str)
Exemple #11
0
    def send_battleList(self):
        servers = BattleList.objects.filter(~Q(run_time=None))
        for s in servers:
            now = datetime.datetime.now()

            if s.run_time.year != now.year:
                continue
            if s.run_time.month != now.month:
                continue
            if s.run_time.day != now.day:
                continue
            if s.run_time.hour != now.hour:
                continue
            if s.run_time.minute != now.minute:
                continue
            if not s.group or not s.sort:
                continue

            print u"正在发送跨服服务器:%s 服" % (s.id)
            base_query = Q(group=s.group) & Q(sort=s.sort)
            other_server = BattleList.objects.filter(base_query)
            server_list = []
            master_server = 0
            for _s in other_server:
                if _s.sub_group == 1:
                    master_server = _s.server
                server_list.append(_s.server)

            if not master_server:
                print u'没有主服'
                continue

            gmp = GMProtocol(int(s.server))
            result = gmp.send_battle_server(master_server, server_list,
                                            [19, 20, 21, 24])
            if result == 0:
                s.f8 = "success"
                s.last_time = datetime.datetime.now()
                s.save()
                print u'%s 已发送' % s.server
Exemple #12
0
def operation_activity_audit(request):
    """运营活动审核"""

    # 获取参数
    sid = request.REQUEST.get('sid')

    # 获取对应运营活动模型类
    model = OperationActivity.objects.get(sid=sid)

    # 判断是否已经审核
    if model.status == 1:
        return HttpResponse(u'SID为%s的活动已审核!' % sid)

    # 获取原本activity.json文件,如果存在,则遍历一遍并根据领取结束时间删除已过期的活动
    path = os.path.abspath(
        os.path.join(os.path.abspath(os.path.join(STATIC_PATH, 'server')),
                     'activity.json'))
    try:
        with open(path, 'r') as f:
            old_activity_list = eval(f.read())
    except IOError:
        old_activity_list = list()
    else:
        for activity in old_activity_list[:]:
            if time_util.now_sec() > activity['endRewardTime']:
                old_activity_list.remove(activity)

    # 构造activity.json文件
    award_list = model.eventActivityRankAwardList.split('\n')
    activity_award_list = list()
    for award in award_list:
        award_config_list = award.split('|')
        award_config_dict = dict()
        award_config_dict['startRank'] = int(award_config_list[0])
        award_config_dict['endRank'] = int(award_config_list[1])
        award_config_dict['rewardId'] = int(award_config_list[2])
        activity_award_list.append(award_config_dict)
    new_activity_dict = dict()
    new_activity_dict['eventActivityRankAwardList'] = activity_award_list
    new_activity_dict['imageIcon'] = model.imageIcon.split('|')
    new_activity_dict['imageContent'] = model.imageContent.split('|')
    new_activity_dict['imageScore'] = map(int, model.imageScore.split('|'))
    new_activity_dict['server'] = eval(model.server)
    new_activity_dict['activityId'] = model.activityId
    new_activity_dict['icon'] = model.icon
    new_activity_dict['backIcon1'] = model.backIcon1
    new_activity_dict['backIcon2'] = model.backIcon2
    new_activity_dict['titleIcon'] = model.titleIcon
    new_activity_dict['shopIcon'] = model.shopIcon
    new_activity_dict['enterIcon'] = model.enterIcon
    new_activity_dict['name'] = model.name
    new_activity_dict['content'] = model.content
    new_activity_dict['startTime'] = time_util.formatTimestamp(
        str(model.startTime))
    new_activity_dict['endTime'] = time_util.formatTimestamp(str(
        model.endTime))
    new_activity_dict['endRewardTime'] = time_util.formatTimestamp(
        str(model.endRewardTime))
    new_activity_dict['sid'] = int(sid)
    old_activity_list.append(new_activity_dict)
    old_activity_list = json.dumps(old_activity_list)
    with open(path, 'w') as f:
        f.write(old_activity_list)

    # 告诉服务端活动变更
    for server in eval(model.server):
        gmp = GMProtocol(server)
        result = gmp.tell_activity_json()
        if result[0] != 0:
            return HttpResponse(u'与服务端协议通讯失败!')

    # 修改活动状态,并添加审核人
    model.status = 1
    model.auditor = request.admin.id
    model.save()

    # 返回应答
    return HttpResponse(u'SID为%s的活动审核成功!' % sid)
Exemple #13
0
                _np.write(json.dumps(content) if content else '')
            msg = " [channel key:%s] " % (channel.channel_key)
            msg += json.dumps(content) if content else ''
            try:
                LogInfo("MD5", msg)
            except BaseException as e:
                print 'LogInfo Error %s' % e

    # 生成all.json,即全部的渠道信息
    content = all_json()
    path = os.path.abspath(os.path.join(folderPath, 'all.json'))
    with open(path, 'w') as f:
        f.write(content.encode('utf-8'))

    # 走服务端协议,告知服务端文件名,让服务端来取配置
    gmp = GMProtocol(constant.gateway_id)
    result = gmp.tell_all_json()
    if result != [0]:
        return HttpResponse(u'向游戏服务端发送请求失败!')

    return render_to_response('feedback.html')


def check_dir(path):
    check_dir = os.path.dirname(path)
    isExists = os.path.exists(check_dir)
    if not isExists:
        os.makedirs(check_dir)


@Route()
Exemple #14
0
        if ajax_post:
            return HttpResponse("保存出错,请重试")
        print('group save error:', e)

    # 编写url.json
    content = url_json_content()
    path = os.path.abspath(
        os.path.join(os.path.abspath(os.path.join(STATIC_PATH, 'server')),
                     'url.json'))
    with open(path, 'w') as f:
        f.write(content)

    # 走服务端协议,告知服务端文件变更
    servers = Server.objects.all()
    for server in servers:
        gmp = GMProtocol(server.id)
        result = gmp.tell_url_json()

    return render_to_response('feedback.html', locals())


def save_group_modify_log(request, source, target, is_updateServerList,
                          post_server_list, source_server_list):
    admin_id = request.admin.id
    msg = []

    msg_str = u"没有操作"

    if source.group_key != target.group_key:
        msg.append('group_key')
    if source.name != target.name:
Exemple #15
0
def conference_send(id):
    audit_id = id
    result_msg = ""

    try:
        eran_all = 0
        for model in Mail.objects.filter(id=int(audit_id)):
            playerIds = []
            if model.player_id:
                playerIds = json.loads(model.player_id)
            if model.status == 1:
                result_status = False
                continue
            msg = {}
            if model.bonus_content:
                msg["rw"] = [{
                    "act": json.loads(model.bonus_content),
                    "gn": "xx"
                }]
                dic = eval(
                    DictValue.objects.get(dict_id=88).json_dict)  ####### 变成字典
                for i in msg["rw"][0]["act"]:
                    single_earn = 0
                    if i["aID"] == 4:
                        single_earn = i["v"] * int(dic[str(
                            i["id"])].encode('gbk'))
                    if i["aID"] == 3:
                        single_earn = round(math.ceil(i["v"] / 1000))
                    if i["aID"] == 2 or i["aID"] == 1:
                        single_earn = i["v"]
                    eran_all += single_earn
                    # if eran_all * playerIds.__len__() > chanel_earn:
                    # return HttpResponse('操作不成功,你的发送余额不足')

            msg["m"] = model.content
            msg["t"] = model.title
            msg["ty"] = model.type
            if model.type == 0:
                msg["arg"] = playerIds
            elif model.type == 2:
                msg["arg"] = []
                msg["svr"] = [-1]
            elif model.type == 3:
                msg["arg"] = model.channel_id
                msg["svr"] = [-1]
            server_id = model.server_ids

            print '==> msg: ', msg
            gmp = GMProtocol(server_id)
            result = gmp.send_mail(msg)
            if result == 0:
                model.status = 1
            else:
                model.status = 2

            result_status = True if result == 0 else False
            model.Auditor = str(model.Applicant)

            if model.time_status == 1:  # 定时的邮件
                model.time_status = 2  #  定时已审
                model.order_time = datetime.datetime.now()
            model.save()

            # 获取当前渠道,然后减值
            if result_status:  #############获取当前渠道,然后减值
                player_id = playerIds[0]
                sql = "select channel_id from player_%s where player_id =%s" % (
                    server_id, player_id)  #############分服获取当前渠道
                con = Server.get_conn(server_id)  #######连接分服的数据库
                cur = con.cursor()
                cur.execute(sql)
                res = cur.fetchone()
                if res[0]:
                    oo = Channel.objects.filter(id=list(res)[0]).first()
                    oo.allow_earn = oo.allow_earn - eran_all * playerIds.__len__(
                    )
                    oo.save()
                else:
                    model.time_status = 3
                cur.close()
                con.commit()
                con.close()

            # 记录日志
            remark2 = str(msg['arg'])
            if model.type == 2:
                remark2 = '全服角色'
            elif model.type == 3:
                remark2 = '联远商ID'

            # player_ids是个列表
            if playerIds:
                for i in playerIds:
                    gmp.save_log(model.Applicant,
                                 gmp.req_type,
                                 result,
                                 remark1=model.content,
                                 remark2=remark2,
                                 player_id=i)
            else:
                gmp.save_log(model.Applicant,
                             gmp.req_type,
                             result,
                             remark1=model.content,
                             remark2=remark2)

        result_msg += "发送成功" if result_status else "发送失败或已经发送过"

    except Exception, e:
        result_msg = trace_msg()
Exemple #16
0
def send_mail(request):
    '''发送邮件
    '''
    audit_ids = [int(request.REQUEST.get("id", '') or 0)]
    server_id = int(request.REQUEST.get("server_id", "") or 0)

    result_msg = ""
    if request.method == 'POST':
        #批量发送
        audit_ids = request.REQUEST.get("ids", "")
        if audit_ids:
            audit_ids = json.loads(audit_ids)
            result_msg = "批量"

    if not audit_ids:
        result_msg = "无此ID或已发送"
        return HttpResponse(result_msg)

    try:
        for audit_id in audit_ids:
            for model in Mail.objects.filter(id=int(audit_id)):
                playerIds = []
                if model.player_id:
                    playerIds = json.loads(model.player_id)

                if model.status == 1:
                    result_status = False
                    continue

                msg = {}
                if model.bonus_content:
                    msg["rw"] = [{
                        "act": json.loads(model.bonus_content),
                        "gn": "xx"
                    }]
                msg["m"] = model.content
                msg["t"] = model.title
                msg["ty"] = model.type
                if model.type == 0:
                    msg["arg"] = playerIds
                elif model.type == 2:
                    msg["arg"] = []
                    msg["svr"] = [-1]
                elif model.type == 3:
                    msg["arg"] = model.channel_id
                    msg["svr"] = [-1]

                server_id = model.server_ids

                print '==> msg: ', msg
                gmp = GMProtocol(server_id)
                result = gmp.send_mail(msg)
                if result == 0:
                    model.status = 1
                else:
                    model.status = 2

                result_status = True if result == 0 else False

                model.Auditor = str(request.admin.id)
                model.save()

                # 记录日志
                remark2 = str(msg['arg'])
                if model.type == 2:
                    remark2 = '全服角色'
                elif model.type == 3:
                    remark2 = '联远商ID'

                # player_ids是个列表
                if playerIds:
                    for i in playerIds:
                        gmp.save_log(request.admin.id,
                                     gmp.req_type,
                                     result,
                                     remark1=model.content,
                                     remark2=remark2,
                                     player_id=i)
                else:
                    gmp.save_log(request.admin.id,
                                 gmp.req_type,
                                 result,
                                 remark1=model.content,
                                 remark2=remark2)

        result_msg += "发送成功" if result_status else "发送失败或已经发送过"

    except Exception, e:
        result_msg = trace_msg()
Exemple #17
0
def send_mail(request):
    '''发送邮件审核
    '''
    audit_ids = [int(request.REQUEST.get("id", '') or 0)]
    server_id = int(request.REQUEST.get("server_id", "") or 0)

    result_msg = ""
    if request.method == 'POST':
        # 批量发送
        audit_ids = request.REQUEST.get("ids", "")
        if audit_ids:
            audit_ids = json.loads(audit_ids)
            result_msg = "批量"

    if not audit_ids:
        result_msg = "无此ID或已发送"
        return HttpResponse(result_msg)

    try:
        for audit_id in audit_ids:
            for model in Mail.objects.filter(id=int(audit_id)):
                playerIds = []
                if model.player_id:
                    playerIds = json.loads(model.player_id)

                if model.status == 1:
                    result_status = False
                    continue

                # msg = {}
                # if model.bonus_content:
                #     msg["rw"] = [{"act": json.loads(model.bonus_content), "gn": "xx"}]
                # msg["m"] = model.content
                # msg["t"] = model.title
                # msg["ty"] = model.type
                # if model.type == 0:
                #     msg["arg"] = playerIds
                # elif model.type == 2:
                #     msg["arg"] = []
                #     msg["svr"] = [-1]
                # elif model.type == 3:
                #     msg["arg"] = model.channel_id
                #     msg["svr"] = [-1]

                # 组织GM命令
                GM_str = '#gmMail '
                if model.type == 2:
                    GM_str += '-1 '
                else:
                    player_list = eval(model.player_id)
                    for player in player_list:
                        GM_str += str(player) + ','
                    GM_str = GM_str.rstrip(',') + ' '
                GM_str += model.title + ' ' + model.content + ' '
                if model.bonus_content:
                    for award in json.loads(model.bonus_content):
                        GM_str += str(award['aID']) + ',' + str(award['id']) + ',' + str(award['v']) + ';'
                    GM_str = GM_str.rstrip(';')
                else:
                    GM_str = GM_str.rstrip()

                server_id = model.server_ids

                print '==> msg: ', GM_str
                gmp = GMProtocol(int(server_id))
                result = gmp.send_mail(GM_str)
                if result == 0:
                    model.status = 1
                else:
                    model.status = 2

                result_status = True if result == 0 else False

                model.Auditor = str(request.admin.id)
                model.save()

                # 记录日志
                # remark2 = str(msg['arg'])
                if model.type == 2:
                    remark2 = '全服角色'
                elif model.type == 3:
                    remark2 = '联远商ID'
                else:
                    remark2 = playerIds

                # player_ids是个列表
                if playerIds:
                    for i in playerIds:
                        gmp.save_log(request.admin.id, gmp.req_type, result,
                                     remark1=model.content, remark2=remark2, player_id=i)
                else:
                    gmp.save_log(request.admin.id, gmp.req_type, result,
                                 remark1=model.content, remark2=remark2)

        result_msg += "发送成功" if result_status else "发送失败或已经发送过"

    except Exception, e:
        result_msg = trace_msg()
Exemple #18
0
def conference_send_mail(request):
    '''公会邮件审核操作'''
    audit_ids = [int(request.REQUEST.get("id", '') or 0)]
    server_id = int(request.REQUEST.get("server_id", "") or 0)
    result_msg = ""
    if request.method == 'POST':
        # 批量发送
        audit_ids = request.REQUEST.get("ids", "")
        if audit_ids:
            audit_ids = json.loads(audit_ids)
            result_msg = "批量"

    if not audit_ids:
        result_msg = "无此ID或已发送"
        return HttpResponse(result_msg)

    try:
        ##################全部的价值,这里来判断是否可以审核
        # cha_list = list(request.admin.role.first().resource_ids['channel'])
        for audit_id in audit_ids:
            # channel_li = Channel.objects.filter(id__in=cha_list)
            # chanel_earn = 0
            # for v in channel_li:
            #     chanel_earn += v.allow_earn
            ########################用户的运行的全部价值
            eran_all = 0
            for model in Mail.objects.filter(id=int(audit_id)):
                playerIds = []
                if model.player_id:
                    playerIds = json.loads(model.player_id)

                if model.status == 1:
                    result_status = False
                    continue
                msg = {}

                moch = model.channel_id
                channel_si = Channel.objects.filter(id=int(moch))[0]

                print channel_si.allow_earn
                if model.bonus_content:
                    msg["rw"] = [{"act": json.loads(model.bonus_content), "gn": "xx"}]
                    ####################################
                    dic = eval(DictValue.objects.get(dict_id=88).json_dict)  ####### 变成字典
                    for i in msg["rw"][0]["act"]:
                        single_earn = 0
                        if i["aID"] == 4:
                            single_earn = i["v"] * int(dic[str(i["id"])].encode('gbk'))
                        if i["aID"] == 3:
                            single_earn = math.ceil(i["v"] / 1000)
                        if i["aID"] == 2 or i["aID"] == 1:
                            single_earn = i["v"]
                        eran_all += single_earn
                        if eran_all * playerIds.__len__() > channel_si.allow_earn:
                            return HttpResponse('操作不成功,渠道 %s 发送余额不足' % (channel_si.name))
                # print 'pppppp',eran_all * playerIds.__len__(),channel_si.allow_earn
                msg["m"] = model.content
                msg["t"] = model.title
                msg["ty"] = model.type
                if model.type == 0:
                    msg["arg"] = playerIds
                elif model.type == 2:
                    msg["arg"] = []
                    msg["svr"] = [-1]
                elif model.type == 3:
                    msg["arg"] = model.channel_id
                    msg["svr"] = [-1]

                server_id = model.server_ids

                print '==> msg: ', msg
                gmp = GMProtocol(server_id)
                result = gmp.send_mail(msg)
                if result == 0:
                    model.status = 1
                else:
                    model.status = 2

                result_status = True if result == 0 else False

                model.Auditor = str(request.admin.id)
                if model.time_status == 1:
                    model.time_status = 0
                    model.order_time = datetime.datetime.now()
                model.save()

                # 获取当前渠道,然后减值
                if result_status:  #############获取当前渠道,然后减值
                    player_id = playerIds[0]
                    sql = "select channel_id from player_%s where player_id =%s" % (
                    server_id, player_id)  #############分服获取当前渠道
                    con = Server.get_conn(server_id)  #######连接分服的数据库
                    cur = con.cursor()
                    cur.execute(sql)
                    res = cur.fetchone()
                    if res[0]:
                        oo = Channel.objects.filter(id=list(res)[0]).first()
                        oo.allow_earn = oo.allow_earn - eran_all * playerIds.__len__()
                        oo.save()

                    cur.close()
                    con.commit()
                    con.close()

                # 记录日志
                remark2 = str(msg['arg'])
                if model.type == 2:
                    remark2 = '全服角色'
                elif model.type == 3:
                    remark2 = '联远商ID'

                # player_ids是个列表
                if playerIds:
                    for i in playerIds:
                        gmp.save_log(request.admin.id, gmp.req_type, result,
                                     remark1=model.content, remark2=remark2, player_id=i)
                else:
                    gmp.save_log(request.admin.id, gmp.req_type, result,
                                 remark1=model.content, remark2=remark2)

        result_msg += "发送成功" if result_status else "发送失败或已经发送过"


    except Exception, e:
        result_msg = trace_msg()
Exemple #19
0
def activity_manage(request, template="game/activity_manage.html"):
    server_ids = request.REQUEST.getlist('server_id')
    server_ids = list(set(server_ids)) if server_ids else []
    server_ids = [int(i) for i in server_ids]
    activity_type = request.REQUEST.get('activity_type', u'7天乐活动')
    query_type = request.REQUEST.get('query_type', None)
    query_type_dict = {
        u'status': u'按活动状态分类',
        u'id': u'按活动ID分类',
        u'type': u'查看当前活动(单服)',
        u'temp': u'查看当前模版活动'
    }

    table_head = []
    results = {}
    server = None

    for server_id in server_ids:
        try:
            server = Server.objects.filter(id=server_id).first()
            gmp = GMProtocol(server_id)
            server_time = gmp.query_server_time()[0]
            results[server] = get_activity_status(activity_type, server,
                                                  server_time, query_type)
        except Exception:
            err_msg = trace_msg()
    activity_data = {}
    if query_type == 'status':
        table_head = ['活动ID', '开始时间', '结束时间', '活动状态', '服务器']
        for server, result in results.iteritems():
            cur = result.get('cur')
            nor = result.get('nor')
            for i in cur:
                activity_data.setdefault(i, {}).setdefault(u'正在进行',
                                                           []).append(server)
            for i in nor:
                activity_data.setdefault(i, {}).setdefault(u'尚未开启',
                                                           []).append(server)

    elif query_type == 'id':
        table_head = ['活动ID', '开始时间', '结束时间', '服务器']
        for server, result in results.iteritems():
            results[server] = []
            results[server].extend(result['cur'])
            results[server].extend(result['nor'])
        for server, ids in sorted(results.iteritems()):
            for i in ids:
                activity_data.setdefault(i, []).append(server)

    elif query_type == 'temp':
        table_head = ['活动类型', '显示开始', '活动开始', '活动结束', '显示结束']
        res = gmp.get_temp_activity()
        res_obj = {}
        res_obj[res[0]] = res[1:5]
        res_obj[res[6]] = res[7:11]
        res_obj[res[12]] = res[13:17]
        res_obj[res[18]] = res[19:23]

    else:
        table_head = ['活动类型', '活动ID']
        if server and results:
            cur = results[server].get('cur')
            for i in cur:
                ac_type = Activity.objects.filter(id=i['aid']).first().type
                if ac_type not in activity_data:
                    activity_data[ac_type] = []
                activity_data[ac_type].append(i)

    model = get_activity_model(request)
    select_server_ids = server_ids
    group_servers_dict = get_group_servers_dict(request)
    return render_to_response(template, locals())
Exemple #20
0
def send_mail(id):
    '''发送邮件
    '''
    audit_id = id
    result_msg = ""
    try:
        for model in Mail.objects.filter(id=int(audit_id)):
            playerIds = []
            if model.player_id:
                playerIds = json.loads(model.player_id)

            if model.status == 1:
                result_status = False
                continue

            # msg = {}
            # if model.bonus_content:
            #     msg["rw"] = [{"act": json.loads(model.bonus_content), "gn": "xx"}]
            # msg["m"] = model.content
            # msg["t"] = model.title
            # msg["ty"] = model.type
            # if model.type == 0:
            #     msg["arg"] = playerIds
            # elif model.type == 2:
            #     msg["arg"] = []
            #     msg["svr"] = [-1]
            # elif model.type == 3:
            #     msg["arg"] = model.channel_id
            #     msg["svr"] = [-1]

            # 组织GM命令
            GM_str = '#gmMail '
            if model.type == 2:
                GM_str += '-1 '
            else:
                player_list = eval(model.player_id)
                for player in player_list:
                    GM_str += str(player) + ','
                GM_str = GM_str.rstrip(',') + ' '
            GM_str += model.title + ' ' + model.content + ' '
            if model.bonus_content:
                for award in json.loads(model.bonus_content):
                    GM_str += str(award['aID']) + ',' + str(
                        award['id']) + ',' + str(award['v']) + ';'
                GM_str = GM_str.rstrip(';')
            else:
                GM_str = GM_str.rstrip()

            server_id = model.server_ids

            print '==> msg: ', GM_str
            gmp = GMProtocol(int(server_id))
            result = gmp.send_mail(GM_str)
            if result == 0:
                model.status = 1
            else:
                model.status = 2

            result_status = True if result == 0 else False

            model.Auditor = str(model.Applicant)
            if result_status:  # 定时的邮件
                model.time_status = 2  #  定时已审

            else:
                model.time_status = 3

            model.save()

            # 记录日志
            # remark2 = str(msg['arg'])
            if model.type == 2:
                remark2 = '全服角色'
            elif model.type == 3:
                remark2 = '联远商ID'
            else:
                remark2 = playerIds

            # player_ids是个列表
            if playerIds:
                for i in playerIds:
                    gmp.save_log(model.Applicant,
                                 gmp.req_type,
                                 result,
                                 remark1=model.content,
                                 remark2=remark2,
                                 player_id=i)
            else:
                gmp.save_log(model.Applicant,
                             gmp.req_type,
                             result,
                             remark1=model.content,
                             remark2=remark2)

        result_msg += "发送成功" if result_status else "发送失败或已经发送过"

    except Exception, e:
        result_msg = trace_msg()
Exemple #21
0
def player_list(request):
    '''玩家列表
    '''

    server_id = int(request.REQUEST.get('server_id', '') or 0)
    player_id = int(request.REQUEST.get('player_id', '') or 0)
    single = request.REQUEST.get("type", "")
    query_name = '玩家角色管理'

    charge_map = DictDefine.get_dict_for_key("recharge_type")
    request.POST.setlist("charge_map", charge_map.values())
    print '玩家角色管理', request.POST.getlist('server_id', '')
    request.has_shutup = True
    if server_id:
        shutup_player_list = {}

        gmp = GMProtocol(server_id)
        result = gmp.player_shutup_list(0)
        resutl = json.dumps(result)

        for l in result[0]:
            try:
                timestamp_to_datetime_str(l[2])
            except Exception as e:
                l[2] = l[1] + max_time
            shutup_player_list[l[0]] = [
                timestamp_to_datetime_str(l[1]),
                timestamp_to_datetime_str(l[2])
            ]
        player_ids = shutup_player_list.keys()

    if server_id and player_id and single == 'single':
        conn = Server.get_conn(server_id)
        cur = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
        sql = """select '',p.player_id,%s,p.player_name,CONVERT(IFNULL(pp.log_level,'1'),SIGNED) level,p.channel_id,p.other,p.user_type,p.link_key,p.login_num,p.mobile_key,p.last_time,p.last_ip,p.create_time,p.status ,
        '' as action
        from player_%s p
        LEFT JOIN ( select log_user,MAX(log_level) as log_level from log_player_level group by log_user ) pp
        ON p.player_id=pp.log_user where player_id = %s""" % (
            server_id, server_id, player_id)
        cur.execute(sql)

        player = cur.fetchone()[0]
        conn.close()
        if player:
            last_time = player["last_time"].strftime('%Y-%m-%d %H:%M:%S')
            create_time = player["create_time"].strftime('%Y-%m-%d %H:%M:%S')
            for t in Player.TYPE_CHOICES:
                if player["user_type"] == t[0]:
                    user_type = t[1]
            for s in Player.STATUS_CHOICES:
                if player["status"] == s[0]:
                    status = s[1]
            request.playerData = [[
                "", player["player_id"], server_id, player["player_name"],
                player["level"], player["channel_id"], player["other"],
                user_type, player["link_key"], player["login_num"],
                player["mobile_key"], last_time, player["last_ip"],
                create_time, status, ""
            ]]

            def list_data_handle(list_data):
                new_list_data = []
                for p in request.playerData:
                    if p[1] in player_ids:
                        new_list_data.append(
                            list(p) +
                            shutup_player_list.get(player_id, [0, 0]))
                if new_list_data:
                    return new_list_data
                return request.playerData

            return query_view(request,
                              query_name=query_name,
                              list_data_handle=list_data_handle)

    if request.REQUEST.get('is_shutup', ''):
        try:
            player_ids = player_ids or [1]
            request.POST.setlist('player_id', player_ids)
            print shutup_player_list

            def list_data_handle(list_data):
                new_list_data = []
                for row in list_data:
                    player_id = row[1]
                    new_list_data.append(
                        list(row) + shutup_player_list.get(player_id, [0, 0]))
                return new_list_data

            return query_view(request,
                              query_name=query_name,
                              list_data_handle=list_data_handle)
        except:
            err_msg = trace_msg()
            return HttpResponse('{"code":-1,"msg":"%s"}' % err_msg)
    else:
        try:

            def list_data_handle(list_data):
                new_list_data = []
                for row in list_data:
                    player_id = row[1]
                    if player_id in player_ids:
                        new_list_data.append(
                            list(row) + shutup_player_list.get(player_id))
                    else:
                        new_list_data.append(list(row))
                return new_list_data

            return query_view(request,
                              query_name=query_name,
                              list_data_handle=list_data_handle)
        except:
            err_msg = trace_msg()
            return HttpResponse('{"code":-1,"msg":"%s"}' % err_msg)

    return query_view(request, query_name)