This commit is contained in:
xy
2026-03-13 01:38:40 +00:00
parent e6e4f88257
commit 28855885cd
311 changed files with 89544 additions and 94350 deletions

View File

@@ -1,26 +1,26 @@
import { UserModel } from '@db/User';
import { LadderMatchRecModel } from '@db/LadderMatchRec';
import { PvpRecordModel } from '@db/PvpRecord';
import { BattleRecordModel } from '@db/BattleRecord';
import { STATUS, WAR_TYPE } from '@consts';
import { UserModel } from '../../../shared/db/User';
import { LadderMatchRecModel } from '../../../shared/db/LadderMatchRec';
import { PvpRecordModel } from '../../../shared/db/PvpRecord';
import { BattleRecordModel } from '../../../shared/db/BattleRecord';
import { STATUS, WAR_TYPE } from '../../../shared/consts';
import { Controller } from 'egg';
import * as fs from 'fs';
import { RoleModel } from '@db/Role';
import { NoticeModel } from '@db/Notice';
import { ServerParamWithRole, GroupParam } from '../domain/gameField/serverlist';
import { reloadResources } from 'app/pubUtils/data';
import { ServerlistModel } from '@db/Serverlist';
import { dispatch } from 'app/pubUtils/dispatcher';
import { RoleModel } from '../../../shared/db/Role';
import { NoticeModel } from '../../../shared/db/Notice';
import { ServerParamWithRole, GroupParam } from '../../../shared/domain/gameField/serverlist';
import { reloadResources } from '../../../shared/pubUtils/data';
import { ServerlistModel } from '../../../shared/db/Serverlist';
import { dispatch } from '../../../shared/pubUtils/dispatcher';
import { RedisClient } from 'redis';
import { REDIS_KEY } from '@consts';
import { RegionModel } from '@db/Region';
import { getRandEelmWithWeight } from 'app/pubUtils/util';
import { getLocalRplUrl, getRemoteRplUrl, getRemoteRplPrefix } from 'app/pubUtils/battleUtils'
import { ChannelInfoModel } from '@db/ChannelInfo';
import { GVGVestigeRecModel } from '@db/GVGVestigeRec';
import { GVGBattleRecModel } from '@db/GVGBattleRec';
import { PackageModel } from '@db/Package';
import { nowSeconds } from 'app/pubUtils/timeUtil';
import { REDIS_KEY } from '../../../shared/consts';
import { RegionModel } from '../../../shared/db/Region';
import { getRandEelmWithWeight } from '../../../shared/pubUtils/util';
import { getLocalRplUrl, getRemoteRplUrl, getRemoteRplPrefix } from '../../../shared/pubUtils/battleUtils'
import { ChannelInfoModel } from '../../../shared/db/ChannelInfo';
import { GVGVestigeRecModel } from '../../../shared/db/GVGVestigeRec';
import { GVGBattleRecModel } from '../../../shared/db/GVGBattleRec';
import { PackageModel } from '../../../shared/db/Package';
import { nowSeconds } from '../../../shared/pubUtils/timeUtil';
const sendToWormhole = require('stream-wormhole');
const pump = require('mz-modules/pump');
@@ -49,12 +49,16 @@ export default class GameController extends Controller {
const { ctx } = this;
const { version, platformAppid, platformAppId, addressType, platform: clientPlatform } = ctx.request.body;
console.log('****** checkReview realEnv:', this.app.config.realEnv);
let curRegion = await RegionModel.findRegionByEnv(this.app.config.realEnv);
console.log('****** checkReview curRegion:', JSON.stringify(curRegion, null, 2));
if(!curRegion) {
console.log('****** checkReview curRegion is null');
return ctx.body = ctx.service.utils.resResult(STATUS.VERSION_ERR);
}
if(curRegion.addressType != addressType) {
console.log('****** checkReview addressType mismatch:', curRegion.addressType, '!=', addressType);
return ctx.body = ctx.service.utils.resResult(STATUS.ADDRESS_ERR);
}
@@ -202,29 +206,31 @@ export default class GameController extends Controller {
const { ctx } = this;
const { app, userCode } = ctx;
let redisClient: RedisClient = app.context.redisClient;
let hash = await redisClient.hvalsAsync(REDIS_KEY.SYS_SERVER);
let connectors = hash.map(cur => JSON.parse(cur));
let redisClient: RedisClient = (app.context as any).redisClient;
let hash = await (redisClient as any).hvalsAsync(REDIS_KEY.SYS_SERVER);
let connectors = hash.map((cur: string) => JSON.parse(cur));
if (!connectors || connectors.length === 0) {
ctx.body = ctx.service.utils.resResult(STATUS.CONNECTOR_ERR);
return
}
// select connector
let sum = connectors.reduce((pre, cur) => pre + (cur['num']||0), 0);
let sum = connectors.reduce((pre: number, cur: any) => pre + (cur['num']||0), 0);
let res;
if(sum > 0) {
let serversWithWeight = connectors.map(cur => ({...cur, weight: sum - (cur['num']||0)}));
let serversWithWeight = connectors.map((cur: any) => ({...cur, weight: sum - (cur['num']||0)}));
let randResult = getRandEelmWithWeight(serversWithWeight);
res = randResult.dic;
}
if(!res) {
res = await dispatch(ctx.app.context.redisClient, userCode, connectors, 'connector');
res = await dispatch((ctx.app.context as any).redisClient, userCode, connectors, 'connector');
}
let { id, serverType, clientHost, clientPort, num = 0 } = res;
// 使用类型断言确保TypeScript知道res是ServerInfo类型
const serverInfo = res as any;
let { id, serverType, clientHost, clientPort, num = 0 } = serverInfo;
await redisClient.hsetAsync(REDIS_KEY.SYS_SERVER, id, JSON.stringify({ serverType, clientHost, clientPort, id, num: num + 1 }));
ctx.body = ctx.service.utils.resResult(STATUS.SUCCESS, { host: res.clientHost, port: res.clientPort });
await (redisClient as any).hsetAsync(REDIS_KEY.SYS_SERVER, id, JSON.stringify({ serverType, clientHost, clientPort, id, num: num + 1 }));
ctx.body = ctx.service.utils.resResult(STATUS.SUCCESS, { host: serverInfo.clientHost, port: serverInfo.clientPort });
return
}

View File

@@ -1,5 +1,5 @@
import { Controller } from 'egg';
import { GetGuildInfoByUserParam, GetRoleByServerParam, GetRoleByUidParam, GetServerAndUidParam, GetServerListParam, GetServerParam, GuildNameCallBackParam, IOSRefundParam, PayCallback37Data, RoleNameCallBackParam, SendGiftCodeParam } from '../domain/sdk';
import { GetGuildInfoByUserParam, GetRoleByServerParam, GetRoleByUidParam, GetServerAndUidParam, GetServerListParam, GetServerParam, GuildNameCallBackParam, IOSRefundParam, PayCallback37Data, RoleNameCallBackParam, SendGiftCodeParam } from '../../../shared/domain/sdk';
export default class SdkController extends Controller {

View File

@@ -1,7 +1,7 @@
import { Controller } from 'egg';
import { RegionModel } from '@db/Region';
import { STATUS } from '@consts';
import { checkWhiteList } from 'app/pubUtils/sysUtil';
import { checkWhiteList } from '@pubUtils/sysUtil';
export default class UpdateController extends Controller {
public async getversion() {

View File

@@ -1,11 +1,12 @@
import { STATUS } from '@consts';
import { ServerlistModel } from '@db/Serverlist';
import { nowSeconds } from 'app/pubUtils/timeUtil';
import { checkWhiteList } from 'app/pubUtils/sysUtil';
import { nowSeconds } from '@pubUtils/timeUtil';
import { checkWhiteList } from '@pubUtils/sysUtil';
import { RoleModel } from '@db/Role';
import { Context } from 'egg';
module.exports = () => {
return async function checkMainten(ctx, next) {
return async function checkMainten(ctx: Context, next: () => Promise<any>) {
const { serverId, version } = ctx.request.body;
if (serverId) {
let server = await ServerlistModel.findByServerId(serverId);

View File

@@ -2,6 +2,14 @@ import c2k = require('koa-connect');
import { createProxyMiddleware, Options as ContextOptions } from 'http-proxy-middleware';
import * as micromatch from 'micromatch';
import * as isGlob from 'is-glob';
import { Context } from 'egg';
// 扩展Request接口添加rawBody属性
declare module 'egg' {
interface Request {
rawBody: string;
}
}
function match(context: string, path: string): boolean {
// single path
@@ -19,7 +27,7 @@ export interface Options {
}
export default function (options: Options) {
return async (ctx, next) => {
return async (ctx: Context, next: () => Promise<any>) => {
for (const context of Object.keys(options)) {
if (match(context, ctx.path)) {
const contextOptions: ContextOptions = options[context];
@@ -41,7 +49,7 @@ export default function (options: Options) {
return proxyReq;
},
}) as any
)(ctx, next);
)(ctx as any, next);
}
}
await next();

View File

@@ -1,7 +1,7 @@
import { Context } from 'egg';
module.exports = () => {
return async function parmsDecode(ctx: Context, next) {
return async function parmsDecode(ctx: Context, next: () => Promise<any>) {
let clientIp = null;
if (ctx.header['x-forwarded-for'] && (typeof ctx.header['x-forwarded-for'] == 'string')) {

View File

@@ -2,17 +2,19 @@ import { GMUserModel } from '@db/GMUser';
import { GMGroupModel } from '@db/GMGroup'
import { GMRecordModel } from '@db/GMRecord'
import { GM_API_TYPE, STATUS } from '@consts';
import { gameData } from 'app/pubUtils/data';
import { gameData } from '@pubUtils/data';
import { Context } from 'egg';
module.exports = () => {
return async function tokenParser(ctx, next) {
return async function tokenParser(ctx: Context, next: () => Promise<any>) {
if (!ctx.request.headers || !ctx.request.headers.token) {
console.error('token not found');
ctx.body = ctx.service.utils.resResult(STATUS.WRONG_PARMS);
return;
}
const user = await GMUserModel.getGmAccountByToken(ctx.request.headers.token);
const token = typeof ctx.request.headers.token === 'string' ? ctx.request.headers.token : ctx.request.headers.token[0];
const user = await GMUserModel.getGmAccountByToken(token);
if (!user) {
console.error('token invalid');
ctx.body = ctx.service.utils.resResult(STATUS.TOKEN_ERR);

View File

@@ -1,39 +1,41 @@
import { genCode } from 'app/pubUtils/util';
import { MsgEncrypt } from "app/pubUtils/sysUtil";
import { genCode } from '../../../shared/pubUtils/util';
import { MsgEncrypt } from "../../../shared/pubUtils/sysUtil";
import { Context } from 'egg';
module.exports = options => {
return async function parmsDecode(ctx: Context, next) {
module.exports = (options: any) => {
return async function parmsDecode(ctx: Context, next: () => Promise<any>) {
let url = ctx.request.url;
ctx.logcode = genCode(10);
if(url.indexOf("/dev") == 0 || url.indexOf("/web") == 0 || url.indexOf("/cb") == 0) {
if (url.indexOf("/dev") == 0 || url.indexOf("/web") == 0 || url.indexOf("/cb") == 0) {
ctx.service.utils.log('INFO', `[${ctx.request.url}] [${ctx.logcode}] request: ${JSON.stringify(ctx.request.body)}`);
await next();
ctx.service.utils.log('INFO', `[${ctx.request.url}] [${ctx.logcode}] res: ${JSON.stringify(ctx.body)}`)
return;
}
}
if (options.threshold && ctx.length < options.threshold) return;
const reqBody = ctx.request.body;
const reqHeader = ctx.request.header;
console.log(ctx.app.config.decodeParm)
if(ctx.app.config.decodeParm == false) {
if (ctx.app.config.decodeParm == false) {
await next();
return;
}
if (!reqBody.data) return;
let msgEncrypt = new MsgEncrypt({ encodeK: reqHeader['k'], encodeV: reqHeader['v'] });
const k = typeof reqHeader['k'] === 'string' ? reqHeader['k'] : reqHeader['k'][0];
const v = typeof reqHeader['v'] === 'string' ? reqHeader['v'] : reqHeader['v'][0];
let msgEncrypt = new MsgEncrypt({ encodeK: k, encodeV: v });
console.log(`encode str ${msgEncrypt.encryptMsg(reqBody)}`);
try {
let decryptResult = msgEncrypt.decryptMsg(reqBody.data);
if(!decryptResult) throw new Error('params parse err');
if (!decryptResult) throw new Error('params parse err');
ctx.request.body = decryptResult;
console.log('req body', ctx.request.body);
console.log('req body', ctx.request.body);
ctx.service.utils.log('INFO', `[${ctx.request.url}] [${ctx.logcode}] request: ${JSON.stringify(ctx.request.body)}`)
} catch (e) {
console.error('parms parse err');
@@ -41,9 +43,9 @@ module.exports = options => {
}
try{
try {
await next();
} catch(e) {
} catch (e) {
ctx.service.utils.log('ERROR', `[${ctx.request.url}] [${ctx.logcode}] err: ${(<Error>e).stack}`);
throw e;
}

View File

@@ -1,9 +1,20 @@
import { RegionModel } from '@db/Region';
import { ServerlistModel } from '@db/Serverlist';
import proxy from './egg-proxy';
import { Context } from 'egg';
interface ProxyOptions {
[key: string]: {
target: string;
changeOrigin: boolean;
secure: boolean;
pathRewrite?: (path: string) => string;
headers?: { [key: string]: string };
};
}
module.exports = () => {
return async function (ctx, next) {
return async function (ctx: Context, next: () => Promise<any>) {
if(!ctx.app.config.envToHost) {
let envToHost = new Map<string, string>();
let regions = await RegionModel.getAllRegion();
@@ -16,13 +27,13 @@ module.exports = () => {
await getNewHost(ctx);
}
let options = {};
let options: ProxyOptions = {};
for(let [env, webHost] of ctx.app.config.envToHost) {
options[`/web/${env}/`] = {
target: webHost,
changeOrigin: true,
secure: true,
pathRewrite: function(path) {
pathRewrite: function(path: string) {
console.log('proxy', path, path.replace(`/web/${env}/`, '/web/'))
return path.replace(`/web/${env}/`, '/web/')
}
@@ -37,7 +48,7 @@ module.exports = () => {
}
if(!!ctx.app.config.sidToHost.get(sid)) {
options[url] = {
target: ctx.app.config.sidToHost.get(sid),
target: ctx.app.config.sidToHost.get(sid) as string,
changeOrigin: true,
secure: true,
headers: { "is-proxy": "true" }
@@ -50,20 +61,20 @@ module.exports = () => {
};
};
async function getNewHost(ctx) {
async function getNewHost(ctx: Context) {
let envToHost = ctx.app.config.envToHost||new Map();
let sidToHost = new Map<string, string>();
let servers = await ServerlistModel.getAllServerList();
for(let { id, env, isMain } of servers) {
let webHost = envToHost.get(env);
sidToHost.set(id.toString(), webHost);
if(isMain) sidToHost.set('main', webHost);
sidToHost.set(id.toString(), webHost as string);
if(isMain) sidToHost.set('main', webHost as string);
}
if(!sidToHost.has('main') && servers.length > 0) sidToHost.set('main', envToHost.get(servers[0].env));
if(!sidToHost.has('main') && servers.length > 0) sidToHost.set('main', envToHost.get(servers[0].env) as string);
ctx.app.config.sidToHost = sidToHost;
}
function getProxyUrl(url: string) {
function getProxyUrl(url: string): string | undefined {
const urls = [
'/cb/treatusername',
'/cb/treatguildname',
@@ -80,9 +91,10 @@ module.exports = () => {
return str;
}
}
return undefined;
}
function getServerId(url: string, ctx: any) {
function getServerId(url: string, ctx: Context): string {
switch(url) {
case '/cb/treatusername':
case '/cb/treatguildname':
@@ -99,5 +111,7 @@ module.exports = () => {
return ctx.query? ctx.query.dsid.toString(): ctx.request.body.dsid.toString();
case '/cb/getrolebyuid':
return 'main';
default:
return 'main';
}
}

View File

@@ -1,8 +1,9 @@
import { STATUS } from '@consts';
import { UserModel } from '@db/User';
import { Context } from 'egg';
module.exports = () => {
return async function tokenParser(ctx, next) {
return async function tokenParser(ctx: Context, next: () => Promise<any>) {
if (!ctx.request.body || !ctx.request.body.token) {
console.error('token not found');

View File

@@ -1,23 +1,23 @@
import { COUNTER, DEFAULT_LV, ADULT_AGE, GUEST_MAX_TIME, BLOCK_TYPE, DEBUG_MAGIC_WORD } from '@consts';
import { RoleModel, WarStar } from '@db/Role';
import { UserModel, UserType } from '@db/User';
import { STATUS, GET_SMS_TYPE, ADDICTION_PREVENTION_CODE } from '@consts';
import { smsModel } from '@db/Sms';
import { COUNTER, DEFAULT_LV, ADULT_AGE, GUEST_MAX_TIME, BLOCK_TYPE, DEBUG_MAGIC_WORD } from '../../../shared/consts';
import { RoleModel, WarStar } from '../../../shared/db/Role';
import { UserModel, UserType } from '../../../shared/db/User';
import { STATUS, GET_SMS_TYPE, ADDICTION_PREVENTION_CODE } from '../../../shared/consts';
import { smsModel } from '../../../shared/db/Sms';
import { Service } from 'egg';
import Counter from '@db/Counter';
import { gameData, getExpByLv } from '../pubUtils/data';
import Counter from '../../../shared/db/Counter';
import { gameData, getExpByLv } from '../../../shared/pubUtils/data';
import { isString } from 'underscore';
import { getAge, nowSeconds } from '../pubUtils/timeUtil';
import { isDevelopEnv, resResult } from '../pubUtils/util';
import { checkTeeanAgerTime } from '../pubUtils/authenticateUtil';
// import { authenticate } from '../pubUtils/httpUtil';
import { getChannelId, loginValidata } from '../pubUtils/sdkUtil';
import { LoginValidateData37 } from 'app/domain/sdk';
import { ServerlistModel } from '@db/Serverlist';
import { DicWar } from '../pubUtils/dictionary/DicWar';
import { RScriptRecordModel } from '@db/RScriptRecord';
import { deletRole } from '../pubUtils/roleUtil';
import { getAge, nowSeconds } from '../../../shared/pubUtils/timeUtil';
import { isDevelopEnv, resResult } from '../../../shared/pubUtils/util';
import { checkTeeanAgerTime } from '../../../shared/pubUtils/authenticateUtil';
// import { authenticate } from '../../../shared/pubUtils/httpUtil';
import { getChannelId, loginValidata } from '../../../shared/pubUtils/sdkUtil';
import { LoginValidateData37 } from '../../../shared/domain/sdk';
import { ServerlistModel } from '../../../shared/db/Serverlist';
import { DicWar } from '../../../shared/pubUtils/dictionary/DicWar';
import { RScriptRecordModel } from '../../../shared/db/RScriptRecord';
import { deletRole } from '../../../shared/pubUtils/roleUtil';
/**
* Test Service
@@ -51,7 +51,7 @@ export default class Auth extends Service {
if (getuiCID) {//更新个推cid
await UserModel.updateGetuiCID(tel, getuiCID);
}
if(user && user.userCode) {
if (user && user.userCode) {
ctx.service.utils.checkOnlineUser(user.userCode);
}
let param = this.getReturnParam(user, null);
@@ -74,7 +74,7 @@ export default class Auth extends Service {
if (getuiCID) {//更新个推cid
await UserModel.updateGetuiCID(user.tel, getuiCID);
}
if(user && user.userCode) {
if (user && user.userCode) {
ctx.service.utils.checkOnlineUser(user.userCode);
}
let param = this.getReturnParam(user, oldUser.deviceId);
@@ -113,7 +113,7 @@ export default class Auth extends Service {
}
}
public checkTelNo(telNo) {
public checkTelNo(telNo: string) {
if (!isString(telNo)) {
return { status: 1, resResult: resResult(STATUS.WRONG_PARMS) };
}
@@ -123,7 +123,9 @@ export default class Auth extends Service {
return { status: 0 };
}
async sendSmsCodeByGuodu(tel, code) {
async sendSmsCodeByGuodu(tel: string, code: string) {
console.log("准备发送短信...");
const ctx = this.ctx;
const url = `http://221.179.172.68:8000/QxtSms/QxtFirewall?OperID=bantu3&OperPass=c8XcTffG&DesMobile=${tel}&Content=${encodeURIComponent(`【同人游戏】验证码${code},您正在登录赵云传,若非本人操作,请勿泄露`)}&Content_Code=1`;
const result = await ctx.curl(url, {
@@ -132,7 +134,7 @@ export default class Auth extends Service {
return result.data;
}
testLimit(sms, interval) {
testLimit(sms: any, interval: number) {
if (sms.updateTime.getTime() > Date.now() - interval) {
return true;
}
@@ -146,6 +148,7 @@ export default class Auth extends Service {
public async getSms(type: number, tel: string) {
const ctx = this.ctx;
console.log("准备发送短信...");
const telVerify = this.checkTelNo(tel);
if (telVerify.status !== 0) {
@@ -158,8 +161,16 @@ export default class Auth extends Service {
return ctx.service.utils.resResult(STATUS.TEL_HAS_USED);
}
}
console.log(2, tel);
let sms: any;
try {
sms = await smsModel.findByTel(tel, false);
} catch (error) {
console.log(error);
}
console.log(3, sms);
const sms = await smsModel.findByTel(tel, false);
if (sms) {
if (await sms.timeLimit(10000)) {
return this.ctx.service.utils.resResult(STATUS.SMS_IN_60S);
@@ -168,7 +179,7 @@ export default class Auth extends Service {
return this.ctx.service.utils.resResult(STATUS.SMS_CNT_LIMIT);
}
}
console.log(sms);
let code = '';
if (sms && (!sms.used || sms.isFixed)) {
code = sms.code;
@@ -176,6 +187,7 @@ export default class Auth extends Service {
code = this.ctx.service.utils.generateNum(6);
}
const smsResult = await this.sendSmsCodeByGuodu(tel, code);
console.log(smsResult);
await smsModel.updateByTel(tel, code, false, new Date(), sms?.hasSendToday() ? sms.countToday + 1 : 1);
@@ -225,11 +237,11 @@ export default class Auth extends Service {
// 用户注册登录
const token = ctx.service.utils.generateStr(256);
const {user, deviceId: oldDeviceId} = await UserModel.createOrUpdate(false, tel, token, platform, pkgName, serverType, deviceId, ctx.clientIp);
const { user, deviceId: oldDeviceId } = await UserModel.createOrUpdate(false, tel, token, platform, pkgName, serverType, deviceId, ctx.clientIp);
if (getuiCID) {//更新个推cid
await UserModel.updateGetuiCID(tel, getuiCID);
}
if(user && user.userCode) {
if (user && user.userCode) {
ctx.service.utils.checkOnlineUser(user.userCode);
}
let param = this.getReturnParam(user, oldDeviceId);
@@ -289,12 +301,12 @@ export default class Auth extends Service {
// 用户注册登录
const token = ctx.service.utils.generateStr(256);
const {user, deviceId: oldDeviceId} = await UserModel.checkPass(tel, pw, token, deviceId);
const { user, deviceId: oldDeviceId } = await UserModel.checkPass(tel, pw, token, deviceId);
if (!user) return ctx.service.utils.resResult(STATUS.PASSWORD_ERR);
if (getuiCID) {//更新个推cid
await UserModel.updateGetuiCID(tel, getuiCID);
}
if(user && user.userCode) {
if (user && user.userCode) {
ctx.service.utils.checkOnlineUser(user.userCode);
}
let param = this.getReturnParam(user, oldDeviceId);
@@ -305,14 +317,14 @@ export default class Auth extends Service {
const ctx = this.ctx;
const { uid } = ctx;
let canLogin = await this.ctx.service.utils.validateCanLogin();
if(!canLogin) return this.ctx.service.utils.resResult(STATUS.ONLINE_USER_MAX);
if (!canLogin) return this.ctx.service.utils.resResult(STATUS.ONLINE_USER_MAX);
const role = await RoleModel.findByUid(uid, serverId, 'roleId blockType +closeTime');
if (role) {
if(role.blockType == BLOCK_TYPE.BLOCK) {
if (role.blockType == BLOCK_TYPE.BLOCK) {
return ctx.service.utils.resResult(STATUS.BLOCKED);
}
if(role.closeTime > 0 && role.closeTime < nowSeconds()) {
if (role.closeTime > 0 && role.closeTime < nowSeconds()) {
return ctx.service.utils.resResult(STATUS.ROLE_CLOSED);
}
return ctx.service.utils.resResult(STATUS.SUCCESS, { roleId: role.roleId });
@@ -325,12 +337,12 @@ export default class Auth extends Service {
const ctx = this.ctx;
const { uid } = ctx;
const exist = await RoleModel.exists({ 'userInfo.uid': uid, serverId });
if (exist === true) {
if (exist) {
return ctx.service.utils.resResult(STATUS.ROLE_EXIST);
}
const server = await ServerlistModel.findByServerId(serverId);
if(!server) return ctx.service.utils.resResult(STATUS.SERVER_NOT_FOUND);
if(nowSeconds() > server.stopRegisterTime) return ctx.service.utils.resResult(STATUS.SERVER_STOP_REGISTER);
if (!server) return ctx.service.utils.resResult(STATUS.SERVER_NOT_FOUND);
if (nowSeconds() > server.stopRegisterTime) return ctx.service.utils.resResult(STATUS.SERVER_STOP_REGISTER);
const roleId = ctx.service.utils.genCode(10);
const code = ctx.service.utils.genCode(6);
@@ -338,7 +350,7 @@ export default class Auth extends Service {
const role = await RoleModel.createRole(uid, serverId, { roleId, code, roleName: "默认玩家名", seqId, lv: DEFAULT_LV, exp: (getExpByLv(DEFAULT_LV - 1) || { sum: 0 }).sum || 0 }, distinctId);
if (role) {
if(server.isReview) { // 审核服跳关卡
if (server.isReview) { // 审核服跳关卡
await this.skipPrologueWhenReview(roleId);
}
return ctx.service.utils.resResult(STATUS.SUCCESS, { roleId: role.roleId });
@@ -348,12 +360,12 @@ export default class Auth extends Service {
private async skipPrologueWhenReview(roleId: string) {
const fromWarId = 101, toWarId = 103;
let warStars: WarStar[] = [];
let warStars: WarStar[] = [];
let insertParams: DicWar[] = [];
for(let i = fromWarId; i <= toWarId; i++) {
for (let i = fromWarId; i <= toWarId; i++) {
let dicWar = gameData.war.get(i);
insertParams.push(dicWar);
if(i < toWarId) warStars.push({ id: dicWar.war_id, warType: dicWar.warType, star: 0, stars: [] });
if (i < toWarId) warStars.push({ id: dicWar.war_id, warType: dicWar.warType, star: 0, stars: [] });
}
await RScriptRecordModel.insertScripts(roleId, insertParams, [toWarId]);
await RoleModel.updateRoleInfo(roleId, { warStar: warStars, mainWarId: toWarId - 1 })
@@ -432,22 +444,22 @@ export default class Auth extends Service {
channelType: string, pst: string, clientId: string, deviceId: string, platform: string, platformAppid: string, childGameId: number, pkgName: string, serverType: string, getuiCID: string, distinctId: string
}) {
const { channelType, pst, clientId, deviceId, platform, platformAppid, childGameId, pkgName, serverType, getuiCID } = params;
const ctx = this.ctx;
let requestResult = await loginValidata(channelType, { clientId, pst, platform, platformAppid, childGameId });
if(!requestResult) return this.ctx.service.utils.resResult(STATUS.CHANNEL_ERR);
if (!requestResult) return this.ctx.service.utils.resResult(STATUS.CHANNEL_ERR);
if(requestResult.code != 1) {
if (requestResult.code != 1) {
return this.ctx.service.utils.resResult(STATUS.VALIDATE_ERR, requestResult);
}
let channelId = getChannelId(channelType, requestResult.data.uid);
const token = ctx.service.utils.generateStr(256);
let { user, deviceId: oldDeviceId } = await UserModel.createOrUpdateChannelUser(channelId, channelType, {
...requestResult.data, childGameId:`${childGameId}`, platformAppid
...requestResult.data, childGameId: `${childGameId}`, platformAppid
}, token, platform, pkgName, serverType, deviceId, ctx.clientIp);
if(user && user.userCode) {
if (user && user.userCode) {
ctx.service.utils.checkOnlineUser(user.userCode);
}
@@ -455,7 +467,7 @@ export default class Auth extends Service {
await UserModel.updateGetuiCIDByChannel(channelId, getuiCID);
}
let channelInfo: any = {};
if(channelType == '37') {
if (channelType == '37') {
channelInfo.uid = (<LoginValidateData37>user.channelInfo).uid;
}
return ctx.service.utils.resResult(STATUS.SUCCESS, {
@@ -468,36 +480,36 @@ export default class Auth extends Service {
});
}
public async deleteRole(roleId: string, magicWord: string) {
console.log('enter Auth deleteRole');
const ctx = this.ctx;
if(magicWord != DEBUG_MAGIC_WORD) {
if (magicWord != DEBUG_MAGIC_WORD) {
return ctx.service.utils.resResult(STATUS.WRONG_PARMS);
}
if(!isDevelopEnv(ctx.app.config.realEnv)) {
if (!isDevelopEnv(ctx.app.config.realEnv)) {
return ctx.service.utils.resResult(STATUS.DEVELOP_ONLY);
}
let result = await deletRole(roleId);
if(!result) return ctx.service.utils.resResult(STATUS.WRONG_PARMS);
if (!result) return ctx.service.utils.resResult(STATUS.WRONG_PARMS);
return ctx.service.utils.resResult(STATUS.SUCCESS);
}
public async closeAccount(roleId: string) {
const ctx = this.ctx;
let role = await RoleModel.findByRoleId(roleId, '+closeTime +cancelCloseTime userInfo');
if(!role || role.userInfo.uid != ctx.uid ) return ctx.service.utils.resResult(STATUS.ROLE_NOT_FOUND);
if(role.cancelCloseTime > 0 && role.cancelCloseTime + 24 * 60 * 60 > nowSeconds() )
if (!role || role.userInfo.uid != ctx.uid) return ctx.service.utils.resResult(STATUS.ROLE_NOT_FOUND);
if (role.cancelCloseTime > 0 && role.cancelCloseTime + 24 * 60 * 60 > nowSeconds())
return ctx.service.utils.resResult(STATUS.ROLE_CLOSE_COOL_DOWN, `注销冷却中,请${this.getCdTimeStr(role.cancelCloseTime)}后再试`);
if(role.closeTime > 0) return ctx.service.utils.resResult(STATUS.ROLE_CLOSED);
if (role.closeTime > 0) return ctx.service.utils.resResult(STATUS.ROLE_CLOSED);
role = await RoleModel.closeAccount(roleId, nowSeconds() + 15 * 24 * 60 * 60);
return ctx.service.utils.resResult(STATUS.SUCCESS, { closeTime: role.closeTime });
}
private getCdTimeStr(cancelCloseTime: number) {
let gap = cancelCloseTime + 24 * 60 * 60 - nowSeconds();
let h = Math.floor(gap/60/60);
let m = Math.floor((gap - h * 60 * 60 )/60);
let h = Math.floor(gap / 60 / 60);
let m = Math.floor((gap - h * 60 * 60) / 60);
let s = gap - h * 60 * 60 - m * 60;
return `${h}小时${m}${s}`
}
@@ -505,10 +517,10 @@ export default class Auth extends Service {
public async cancelCloseAccount(roleId: string) {
const ctx = this.ctx;
let role = await RoleModel.findByRoleId(roleId, '+cancelCloseTime userInfo');
if(!role || role.userInfo.uid != ctx.uid ) return ctx.service.utils.resResult(STATUS.ROLE_NOT_FOUND);
if (!role || role.userInfo.uid != ctx.uid) return ctx.service.utils.resResult(STATUS.ROLE_NOT_FOUND);
role = await RoleModel.cancelCloseAccount(roleId, nowSeconds());
if(!role) return ctx.service.utils.resResult(STATUS.ROLE_CLOSE_TIME_OVER);
if (!role) return ctx.service.utils.resResult(STATUS.ROLE_CLOSE_TIME_OVER);
return ctx.service.utils.resResult(STATUS.SUCCESS, { closeTime: role.closeTime });
}

View File

@@ -1,24 +1,24 @@
import { Service } from 'egg';
import { REDIS_KEY, PAY_37_CALLBACK_CODE, SDK_37_CONST, ORDER_STATE, SDK_37_TREAT_CODE, SERVER_STATUS, SDK_37_REFUND_CODE, SDK_37_ACTIVITY_CODE, PUBLIC_ACCOUNT_GIFT, GIFT_GENERATE_TYPE, GIFT_TYPE } from '@consts';
import { GetGuildInfoByUserParam, GetRoleByServerParam, GetRoleByUidParam, GetServerAndUidParam, GetServerListParam, GetServerParam, GuildNameCallBackParam, IOSRefundParam, PayCallback37Data, RoleNameCallBackParam, SendGiftCodeParam } from '../domain/sdk';
import { REDIS_KEY, PAY_37_CALLBACK_CODE, SDK_37_CONST, ORDER_STATE, SDK_37_TREAT_CODE, SERVER_STATUS, SDK_37_REFUND_CODE, SDK_37_ACTIVITY_CODE, PUBLIC_ACCOUNT_GIFT, GIFT_GENERATE_TYPE, GIFT_TYPE } from '../../../shared/consts';
import { GetGuildInfoByUserParam, GetRoleByServerParam, GetRoleByUidParam, GetServerAndUidParam, GetServerListParam, GetServerParam, GuildNameCallBackParam, IOSRefundParam, PayCallback37Data, RoleNameCallBackParam, SendGiftCodeParam } from '../../../shared/domain/sdk';
import { RedisClient } from 'redis';
import { checkParamPrice, get37GetServerMd5Sign, get37Md5SignA, get37Md5SignB, getChannelId, getRedisSubChannel, md5 } from '../pubUtils/sdkUtil';
import { UserOrderModel } from '@db/UserOrder';
import { nowSeconds } from 'app/pubUtils/timeUtil';
import { RoleModel } from '@db/Role';
import { gameData } from 'app/pubUtils/data';
import { resResult } from 'app/pubUtils/util';
import { UserModel } from '@db/User';
import { UserGuildModel } from '@db/UserGuild';
import { GuildModel } from '@db/Guild';
import { ServerlistModel } from '@db/Serverlist';
import { checkParamPrice, get37GetServerMd5Sign, get37Md5SignA, get37Md5SignB, getChannelId, getRedisSubChannel, md5 } from '../../../shared/pubUtils/sdkUtil';
import { UserOrderModel } from '../../../shared/db/UserOrder';
import { nowSeconds } from '../../../shared/pubUtils/timeUtil';
import { RoleModel } from '../../../shared/db/Role';
import { gameData } from '../../../shared/pubUtils/data';
import { resResult } from '../../../shared/pubUtils/util';
import { UserModel } from '../../../shared/db/User';
import { UserGuildModel } from '../../../shared/db/UserGuild';
import { GuildModel } from '../../../shared/db/Guild';
import { ServerlistModel } from '../../../shared/db/Serverlist';
import moment = require('moment');
import { RegionModel } from '@db/Region';
import { ActivityPublicAccountCodeModel } from '@db/ActivityPublicAccountCode';
import { GiftCodeDetailModel } from '@db/GiftCodeDetail';
import { GiftCodeModel } from '@db/GiftCode';
import { UserGiftCodeDetailModel } from '@db/UserGiftCodeDetail';
import { RegionModel } from '../../../shared/db/Region';
import { ActivityPublicAccountCodeModel } from '../../../shared/db/ActivityPublicAccountCode';
import { GiftCodeDetailModel } from '../../../shared/db/GiftCodeDetail';
import { GiftCodeModel } from '../../../shared/db/GiftCode';
import { UserGiftCodeDetailModel } from '../../../shared/db/UserGiftCodeDetail';
/**
* Test Service
@@ -79,9 +79,9 @@ export default class Sdk extends Service {
}
ctx.service.utils.log('DEBUG', `[${ctx.request.url}] [${ctx.logcode}] pay37Callback save order check ok`);
let redisClient: RedisClient = app.context.redisClient;
let redisClient: RedisClient = (app.context as any).redisClient;
let name = getRedisSubChannel(REDIS_KEY.PAY_CHANNEL, app.config.env);
let result = await redisClient.publishAsync(name, JSON.stringify(params));
let result = await (redisClient as any).publishAsync(name, JSON.stringify(params));
if(result == 0) {
return ctx.service.utils.resResult(PAY_37_CALLBACK_CODE.SERVER_IS_BUSY, '');
}
@@ -140,7 +140,7 @@ export default class Sdk extends Service {
// let redisClient: RedisClient = app.context.redisClient;
// let name = getRedisSubChannel(REDIS_KEY.PAY_CHANNEL, app.config.env);
// let result = await redisClient.publishAsync(name, JSON.stringify(params));
// let result = await (redisClient as any).publishAsync(name, JSON.stringify(params));
// if(result == 0) {
// return ctx.service.utils.resResult(PAY_IOS_37_CALLBACK_CODE.SERVER_IS_BUSY, '');
// }
@@ -193,9 +193,9 @@ export default class Sdk extends Service {
}
console.log('*****refundIOSCallback save order check ok')
let redisClient: RedisClient = app.context.redisClient;
let redisClient: RedisClient = (app.context as any).redisClient;
let name = getRedisSubChannel(REDIS_KEY.REFUND_CHANNEL, app.config.env);
let result = await redisClient.publishAsync(name, JSON.stringify(params));
let result = await (redisClient as any).publishAsync(name, JSON.stringify(params));
if(result == 0) {
return ctx.service.utils.resResult(SDK_37_REFUND_CODE.FAIL, '');
}
@@ -262,9 +262,9 @@ export default class Sdk extends Service {
}
// 2. redis发布
let redisClient: RedisClient = app.context.redisClient;
let redisClient: RedisClient = (app.context as any).redisClient;
let name = getRedisSubChannel(REDIS_KEY.TREAT_ROLE_CHANNEL, app.config.env);
let result = await redisClient.publishAsync(name, role.roleId);
let result = await (redisClient as any).publishAsync(name, role.roleId);
if(result == 0) {
console.error('用户名违规处理, 未发布到订阅频道');
return SDK_37_TREAT_CODE.ERR.code;
@@ -288,10 +288,10 @@ export default class Sdk extends Service {
}
// 2. redis发布
let redisClient: RedisClient = app.context.redisClient;
let redisClient: RedisClient = (app.context as any).redisClient;
let name = getRedisSubChannel(REDIS_KEY.TREAT_GUILD_CHANNEL, app.config.env);
let content = JSON.stringify({ code: guild.code, serverId: params.sid, type: params.type });
let result = await redisClient.publishAsync(name, content);
let result = await (redisClient as any).publishAsync(name, content);
if(result == 0) {
return SDK_37_TREAT_CODE.ERR.code;
}
@@ -375,7 +375,7 @@ export default class Sdk extends Service {
}
public reportTAEventWithDistinctId(distinctId: string, eventName: string, properties: any, ip: string) {
let ta = this.app.context.ta;
let ta = (this.app.context as any).ta;
if(!ta) return
let event = {
// 账号 ID (可选)
@@ -390,7 +390,7 @@ export default class Sdk extends Service {
ip: ip,
// 事件属性 (可选)
properties,
callback(err) {
callback(err: any) {
console.log('*****测试接入事件', err)
}
@@ -399,7 +399,7 @@ export default class Sdk extends Service {
}
public reportTAEventWithRoleIdAndDistinctId(roleId: string, distinctId: string, eventName: string, properties: any, ip?: string) {
let ta = this.app.context.ta;
let ta = (this.app.context as any).ta;
if(!ta) return
let event = {
// 账号 ID (可选)
@@ -414,7 +414,7 @@ export default class Sdk extends Service {
ip: ip,
// 事件属性 (可选)
properties,
callback(err) {
callback(err: any) {
console.log('*****测试接入事件', err)
}
@@ -484,7 +484,7 @@ export default class Sdk extends Service {
await GiftCodeDetailModel.increaseUsedNum(giftCodeDetail.code);
await GiftCodeModel.increaseUsedNum(giftCode.id);
await ctx.service.utils.pushGiftCodeChannel(role.roleId, giftCode.id);
await ctx.service.utils.pushGiftCodeChannel(String(role.roleId), String(giftCode.id));
}
return resResult(SDK_37_ACTIVITY_CODE.SUCCESS, []);
@@ -564,8 +564,8 @@ export default class Sdk extends Service {
let user = await UserModel.findUserByChannel(channelId);
if(!user) return resResult(SDK_37_ACTIVITY_CODE.ROLE_NOT_FOUND);
let redisClient: RedisClient = this.ctx.app.context.redisClient;
let servers = await redisClient.hgetallAsync(REDIS_KEY.SERVER);
let redisClient: RedisClient = (this.ctx.app.context as any).redisClient;
let servers = await (redisClient as any).hgetallAsync(REDIS_KEY.SERVER);
let roles = await RoleModel.findAllByUid(user.uid);
let result = roles
.filter(role => !role.closeTime || role.closeTime > nowSeconds())
@@ -661,7 +661,7 @@ export default class Sdk extends Service {
}
} catch(e) {
console.error(e);
return { state: 0, data: null, msg: SDK_37_ACTIVITY_CODE.INTERNAL_ERR };
return { state: 0, data: null as any, msg: SDK_37_ACTIVITY_CODE.INTERNAL_ERR };
}
}

View File

@@ -57,7 +57,7 @@ export default class TurboCore extends Service {
* @param params 参数列表
* @param secret 密钥
*/
private getTurboSign(params, secret) {
private getTurboSign(params: any, secret: string) {
const paramsString = this.joinParamsStr(params);
let stringToSign = paramsString;
@@ -74,7 +74,7 @@ export default class TurboCore extends Service {
* 将参数组合成字符串
* @param params 参数列表
*/
private joinParamsStr(params) {
private joinParamsStr(params: any) {
const signString = Object.keys(params).filter(function(key) {
return params[key] !== undefined && params[key] !== '' && [ 'pfx', 'partner_key', 'sign', 'key' ].indexOf(key) < 0;
}).sort()

View File

@@ -1,5 +1,5 @@
import { STATUS, } from '@consts';
import { RegionType } from '@db/Region';
import { STATUS, } from '../../../shared/consts';
import { RegionType } from '../../../shared/db/Region';
import { Service } from 'egg';
// let fs = require("fs");

View File

@@ -1,12 +1,12 @@
import { Service } from 'egg';
import { resResult as pubResult } from '../pubUtils/util';
import { gameData } from 'app/pubUtils/data';
import { resResult as pubResult } from '../../../shared/pubUtils/util';
import { gameData } from '../../../shared/pubUtils/data';
import { RedisClient } from 'redis';
import { REDIS_KEY, SERVER_STATUS } from '@consts';
import { getRedisSubChannel } from 'app/pubUtils/sdkUtil';
import { ServerlistType } from '@db/Serverlist';
import { nowSeconds } from 'app/pubUtils/timeUtil';
import { checkWhiteList } from 'app/pubUtils/sysUtil';
import { REDIS_KEY, SERVER_STATUS } from '../../../shared/consts';
import { getRedisSubChannel } from '../../../shared/pubUtils/sdkUtil';
import { ServerlistType } from '../../../shared/db/Serverlist';
import { nowSeconds } from '../../../shared/pubUtils/timeUtil';
import { checkWhiteList } from '../../../shared/pubUtils/sysUtil';
const csprng = require('csprng');
/**
* Utils Service
@@ -21,7 +21,7 @@ export default class Utils extends Service {
return `${csprng(len, radix)}`;
}
public genCode(len) {
public genCode(len: number) {
const chars = '123456789ABCDEFGHJKLMNPQRSTWXYZabcdefghijklmnopqrstuvwxyz';
const charArr = chars.split('');
let code = '';
@@ -43,7 +43,7 @@ export default class Utils extends Service {
return code;
}
public resResult(status: {code: number, simStr: string}, data?, customMsg?: string) {
public resResult(status: {code: number, simStr: string}, data?: any, customMsg?: string) {
return pubResult(status, data, customMsg);
}
@@ -62,18 +62,18 @@ export default class Utils extends Service {
}
public async checkOnlineUser(userCode: string) {
let redisClient: RedisClient = this.ctx.app.context.redisClient;
let onlineRoleId = await redisClient.hgetAsync(REDIS_KEY.USER_CODE, userCode);
let redisClient: RedisClient = (this.ctx.app.context as any).redisClient;
let onlineRoleId = await (redisClient as any).hgetAsync(REDIS_KEY.USER_CODE, userCode);
let isWhiteList = await checkWhiteList(this.ctx.app.config.realEnv, this.ctx.clientIp, this.ctx.uid);
if (!isWhiteList && !!onlineRoleId) { // 多地登陆踢下线
let str = await redisClient.hgetAsync(REDIS_KEY.ONLINE_USERS, onlineRoleId);
let str = await (redisClient as any).hgetAsync(REDIS_KEY.ONLINE_USERS, onlineRoleId);
if(str) {
try {
let [,sid] = str?.split('|')??[];
let name = getRedisSubChannel(REDIS_KEY.USER_CHANNEL, this.ctx.app.config.env);
await redisClient.publishAsync(name, `${sid}|${onlineRoleId}`);
await (redisClient as any).publishAsync(name, `${sid}|${onlineRoleId}`);
} catch(e) {
console.error('checkOnlineUser', e);
}
@@ -82,22 +82,22 @@ export default class Utils extends Service {
}
public async pushPubAccountGiftChannel(activityId: number, userCode: string, channelId: string) {
let redisClient: RedisClient = this.ctx.app.context.redisClient;
let redisClient: RedisClient = (this.ctx.app.context as any).redisClient;
try {
let name = getRedisSubChannel(REDIS_KEY.PUBLIC_ACCOUNT_GIFT, this.ctx.app.config.env);
await redisClient.publishAsync(name, `${activityId}|${userCode}|${channelId}`);
await (redisClient as any).publishAsync(name, `${activityId}|${userCode}|${channelId}`);
} catch(e) {
console.error('pushPubAccountGiftChannel', e);
}
}
public async pushGiftCodeChannel(roleId: string, giftCode: string) {
let redisClient: RedisClient = this.ctx.app.context.redisClient;
let redisClient: RedisClient = (this.ctx.app.context as any).redisClient;
try {
let name = getRedisSubChannel(REDIS_KEY.SEND_GIFT_CODE, this.ctx.app.config.env);
await redisClient.publishAsync(name, `${roleId}|${giftCode}`);
await (redisClient as any).publishAsync(name, `${roleId}|${giftCode}`);
} catch(e) {
console.error('pushPubAccountGiftChannel', e);
}
@@ -109,9 +109,9 @@ export default class Utils extends Service {
if(gameData.serverConst.CLOSE_LOGIN == 1) return false;
if(gameData.serverConst.CLOSE_LOGIN_WHEN_ONLINE_MAX) {
let redisClient: RedisClient = this.ctx.app.context.redisClient;
let count = await redisClient.hlenAsync(REDIS_KEY.ONLINE_USERS);
const Max = await redisClient.getAsync(REDIS_KEY.MAX_ONLINE_USERS);
let redisClient: RedisClient = (this.ctx.app.context as any).redisClient;
let count = await (redisClient as any).hlenAsync(REDIS_KEY.ONLINE_USERS);
const Max = await (redisClient as any).getAsync(REDIS_KEY.MAX_ONLINE_USERS);
console.log('validateCanLogin:', count, Max);
if(Max && count >= parseInt(Max)) {
@@ -128,11 +128,28 @@ export default class Utils extends Service {
// 比较以 . 分隔的版本号。返回 0 则版本号相等,返回正数则 versionA 大,返回负数则 versionB 大
public compareVersion (versionA: string, versionB: string) {
if (!versionA && !versionB) {
return 0;
}
if (!versionA) {
return -1;
}
if (!versionB) {
return 1;
}
var vA = versionA.split('.');
var vB = versionB.split('.');
for (var i = 0; i < vA.length; ++i) {
var a = parseInt(vA[i]);
var b = parseInt(vB[i] || '0');
if (isNaN(a) || isNaN(b)) {
if (a === b) {
continue;
} else {
return isNaN(a) ? -1 : 1;
}
}
if (a === b) {
} else {

View File

@@ -1,7 +1,7 @@
import { SurveyRecModel } from '@db/SurveyRec';
import { SurveyModel } from '@db/Survery';
import { checkWjxSign, getRedisSubChannel } from 'app/pubUtils/sdkUtil';
import { checkWjxSign, getRedisSubChannel } from '@pubUtils/sdkUtil';
import { Service } from 'egg';
import { RedisClient } from 'redis';
import { REDIS_KEY } from '@consts';
@@ -33,7 +33,7 @@ export default class Sdk extends Service {
rec = await SurveyRecModel.createSurveyRec(roleId, params.activity, params.index, JSON.stringify(params));
// 3. 发邮件
let redisClient: RedisClient = this.app.context.redisClient;
let redisClient: RedisClient = (this.app.context as any).redisClient;
let name = getRedisSubChannel(REDIS_KEY.SURVEY_CHANNEL, this.app.config.env);
let result = await redisClient.publishAsync(name, rec.code);
if(result == 0) {